@tano.page/protocol 0.14.0 → 0.15.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,395 @@
1
+ import {
2
+ canonicalPluginJson,
3
+ parsePluginManifest,
4
+ parsePluginPackage,
5
+ pluginRecord,
6
+ type PluginPackage,
7
+ type PluginUiBundle,
8
+ } from './extensions';
9
+ import { parseFileIconTheme, type FileIconTheme } from './appearance';
10
+
11
+ export const PLUGIN_ARCHIVE_V2_VERSION = 2 as const;
12
+ export const PLUGIN_ARCHIVE_V2_LIMIT = 16 * 1024 * 1024;
13
+ export const PLUGIN_ARCHIVE_MAX_ENTRIES = 256;
14
+
15
+ export interface PluginArchiveV2 {
16
+ packageVersion: typeof PLUGIN_ARCHIVE_V2_VERSION;
17
+ pkg: PluginPackage;
18
+ binaryAssets: Record<string, Uint8Array>;
19
+ entries: string[];
20
+ }
21
+
22
+ export interface PluginArchiveV2Input {
23
+ pkg: PluginPackage;
24
+ binaryAssets?: Record<string, Uint8Array>;
25
+ }
26
+
27
+ const crcTable = (() => {
28
+ const table = new Uint32Array(256);
29
+ for (let i = 0; i < 256; i++) {
30
+ let c = i;
31
+ for (let j = 0; j < 8; j++) {
32
+ c = (c & 1) !== 0 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
33
+ }
34
+ table[i] = c >>> 0;
35
+ }
36
+ return table;
37
+ })();
38
+
39
+ export function crc32(bytes: Uint8Array): number {
40
+ let c = 0xffffffff;
41
+ for (let i = 0; i < bytes.length; i++) {
42
+ c = crcTable[(c ^ bytes[i]!) & 0xff]! ^ (c >>> 8);
43
+ }
44
+ return (c ^ 0xffffffff) >>> 0;
45
+ }
46
+
47
+ function validateArchiveEntryPath(path: string): string {
48
+ const normalized = path.replaceAll('\\', '/');
49
+ if (
50
+ !normalized ||
51
+ normalized.length > 240 ||
52
+ normalized.startsWith('/') ||
53
+ normalized.endsWith('/') ||
54
+ normalized.includes('//') ||
55
+ /[\u0000-\u001f]/.test(normalized) ||
56
+ normalized.split('/').some(seg => !seg || seg === '.' || seg === '..')
57
+ ) {
58
+ throw new Error(`插件归档条目路径无效:${path}`);
59
+ }
60
+ return normalized;
61
+ }
62
+
63
+ function validateBinaryAssetPath(path: string): string {
64
+ const normalized = validateArchiveEntryPath(path);
65
+ if (normalized.startsWith('assets/bin/')) return normalized.slice('assets/bin/'.length);
66
+ return normalized;
67
+ }
68
+
69
+ /**
70
+ * Deterministic STORED (method 0) ZIP encoder.
71
+ * Fixed DOS date/time (1980-01-01 00:00:00), fixed mode, UTF-8 sorted paths.
72
+ * Guarantees bit-for-bit identical bytes and SHA-256 across all OSes and runtimes.
73
+ */
74
+ export function encodeDeterministicZip(files: ReadonlyMap<string, Uint8Array>): Uint8Array {
75
+ const entries = [...files.entries()]
76
+ .map(([name, data]) => [validateArchiveEntryPath(name), data] as const)
77
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
78
+
79
+ if (entries.length > PLUGIN_ARCHIVE_MAX_ENTRIES) {
80
+ throw new Error(`插件归档文件数超过 ${PLUGIN_ARCHIVE_MAX_ENTRIES} 上限`);
81
+ }
82
+
83
+ const encoder = new TextEncoder();
84
+ const localParts: Uint8Array[] = [];
85
+ const centralParts: Uint8Array[] = [];
86
+ let offset = 0;
87
+
88
+ // Fixed DOS timestamp: 1980-01-01 00:00:00 (time = 0, date = 0x0021)
89
+ const DOS_TIME = 0x0000;
90
+ const DOS_DATE = 0x0021;
91
+ const UTF8_FLAG = 0x0800;
92
+
93
+ for (const [name, data] of entries) {
94
+ const nameBytes = encoder.encode(name);
95
+ const checksum = crc32(data);
96
+ const size = data.byteLength;
97
+
98
+ const localHeader = new Uint8Array(30 + nameBytes.length);
99
+ const lv = new DataView(localHeader.buffer);
100
+ lv.setUint32(0, 0x04034b50, true); // Local file header signature
101
+ lv.setUint16(4, 20, true); // Version needed: 2.0
102
+ lv.setUint16(6, UTF8_FLAG, true);
103
+ lv.setUint16(8, 0, true); // Compression method 0 (STORE)
104
+ lv.setUint16(10, DOS_TIME, true);
105
+ lv.setUint16(12, DOS_DATE, true);
106
+ lv.setUint32(14, checksum, true);
107
+ lv.setUint32(18, size, true);
108
+ lv.setUint32(22, size, true);
109
+ lv.setUint16(26, nameBytes.length, true);
110
+ lv.setUint16(28, 0, true); // Extra field length
111
+ localHeader.set(nameBytes, 30);
112
+
113
+ const centralHeader = new Uint8Array(46 + nameBytes.length);
114
+ const cv = new DataView(centralHeader.buffer);
115
+ cv.setUint32(0, 0x02014b50, true); // Central directory signature
116
+ cv.setUint16(4, (3 << 8) | 20, true); // Version made by: Unix, 2.0
117
+ cv.setUint16(6, 20, true);
118
+ cv.setUint16(8, UTF8_FLAG, true);
119
+ cv.setUint16(10, 0, true); // STORE
120
+ cv.setUint16(12, DOS_TIME, true);
121
+ cv.setUint16(14, DOS_DATE, true);
122
+ cv.setUint32(16, checksum, true);
123
+ cv.setUint32(20, size, true);
124
+ cv.setUint32(24, size, true);
125
+ cv.setUint16(28, nameBytes.length, true);
126
+ cv.setUint16(30, 0, true); // Extra length
127
+ cv.setUint16(32, 0, true); // Comment length
128
+ cv.setUint16(34, 0, true); // Disk number
129
+ cv.setUint16(36, 0, true); // Internal attrs
130
+ cv.setUint32(38, 0o100644 << 16, true); // Normalized regular file mode
131
+ cv.setUint32(42, offset, true); // Relative offset of local header
132
+ centralHeader.set(nameBytes, 46);
133
+
134
+ localParts.push(localHeader, data);
135
+ centralParts.push(centralHeader);
136
+ offset += localHeader.byteLength + data.byteLength;
137
+ if (offset > PLUGIN_ARCHIVE_V2_LIMIT) {
138
+ throw new Error(`插件归档体积超过 ${PLUGIN_ARCHIVE_V2_LIMIT} 字节上限`);
139
+ }
140
+ }
141
+
142
+ const centralSize = centralParts.reduce((sum, part) => sum + part.byteLength, 0);
143
+ const eocd = new Uint8Array(22);
144
+ const ev = new DataView(eocd.buffer);
145
+ ev.setUint32(0, 0x06054b50, true); // End of central directory signature
146
+ ev.setUint16(4, 0, true);
147
+ ev.setUint16(6, 0, true);
148
+ ev.setUint16(8, entries.length, true);
149
+ ev.setUint16(10, entries.length, true);
150
+ ev.setUint32(12, centralSize, true);
151
+ ev.setUint32(16, offset, true);
152
+ ev.setUint16(20, 0, true);
153
+
154
+ const totalSize = offset + centralSize + eocd.byteLength;
155
+ if (totalSize > PLUGIN_ARCHIVE_V2_LIMIT) {
156
+ throw new Error(`插件归档体积超过 ${PLUGIN_ARCHIVE_V2_LIMIT} 字节上限`);
157
+ }
158
+
159
+ const output = new Uint8Array(totalSize);
160
+ let cursor = 0;
161
+ for (const part of localParts) {
162
+ output.set(part, cursor);
163
+ cursor += part.byteLength;
164
+ }
165
+ for (const part of centralParts) {
166
+ output.set(part, cursor);
167
+ cursor += part.byteLength;
168
+ }
169
+ output.set(eocd, cursor);
170
+ return output;
171
+ }
172
+
173
+ /**
174
+ * Strict ZIP decoder for deterministic STORED (method 0) plugin archives.
175
+ * Rejects path traversal, duplicate names, compression bombs, symlinks, and CRC mismatches.
176
+ */
177
+ export function decodeDeterministicZip(bytes: Uint8Array): Map<string, Uint8Array> {
178
+ if (bytes.byteLength < 22 || bytes.byteLength > PLUGIN_ARCHIVE_V2_LIMIT) {
179
+ throw new Error('插件 ZIP 归档体积无效');
180
+ }
181
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
182
+ let eocdOffset = -1;
183
+ const minOffset = Math.max(0, bytes.byteLength - 22 - 65535);
184
+ for (let i = bytes.byteLength - 22; i >= minOffset; i--) {
185
+ if (view.getUint32(i, true) === 0x06054b50) {
186
+ eocdOffset = i;
187
+ break;
188
+ }
189
+ }
190
+ if (eocdOffset < 0) throw new Error('无效的 ZIP 归档(缺少目录尾)');
191
+
192
+ const totalEntries = view.getUint16(eocdOffset + 10, true);
193
+ const centralSize = view.getUint32(eocdOffset + 12, true);
194
+ const centralOffset = view.getUint32(eocdOffset + 16, true);
195
+ if (totalEntries > PLUGIN_ARCHIVE_MAX_ENTRIES) {
196
+ throw new Error(`插件 ZIP 条目超过 ${PLUGIN_ARCHIVE_MAX_ENTRIES} 上限`);
197
+ }
198
+ if (centralOffset + centralSize > eocdOffset) {
199
+ throw new Error('ZIP 中央目录边界无效');
200
+ }
201
+
202
+ const decoder = new TextDecoder('utf-8', { fatal: true });
203
+ const files = new Map<string, Uint8Array>();
204
+ let pos = centralOffset;
205
+ for (let i = 0; i < totalEntries; i++) {
206
+ if (pos + 46 > centralOffset + centralSize || view.getUint32(pos, true) !== 0x02014b50) {
207
+ throw new Error('ZIP 中央目录条目损坏');
208
+ }
209
+ const method = view.getUint16(pos + 10, true);
210
+ if (method !== 0) {
211
+ throw new Error('packageVersion 2 归档当前仅支持无损确定性 STORED(method 0)条目');
212
+ }
213
+ const expectedCrc = view.getUint32(pos + 16, true);
214
+ const compSize = view.getUint32(pos + 20, true);
215
+ const uncompSize = view.getUint32(pos + 24, true);
216
+ if (compSize !== uncompSize) throw new Error('ZIP 条目压缩长度不一致');
217
+ const nameLen = view.getUint16(pos + 28, true);
218
+ const extraLen = view.getUint16(pos + 30, true);
219
+ const commentLen = view.getUint16(pos + 32, true);
220
+ const extAttrs = view.getUint32(pos + 38, true);
221
+ const unixMode = (extAttrs >>> 16) & 0o170000;
222
+ if (unixMode === 0o120000) throw new Error('插件归档禁止包含符号链接');
223
+ const localOffset = view.getUint32(pos + 42, true);
224
+ const name = validateArchiveEntryPath(
225
+ decoder.decode(bytes.subarray(pos + 46, pos + 46 + nameLen)),
226
+ );
227
+ if (files.has(name)) throw new Error(`插件归档包含重复条目:${name}`);
228
+
229
+ if (localOffset + 30 > centralOffset || view.getUint32(localOffset, true) !== 0x04034b50) {
230
+ throw new Error(`ZIP 本地文件头损坏:${name}`);
231
+ }
232
+ if (
233
+ view.getUint16(localOffset + 8, true) !== 0 ||
234
+ view.getUint32(localOffset + 14, true) !== expectedCrc ||
235
+ view.getUint32(localOffset + 22, true) !== uncompSize
236
+ ) {
237
+ throw new Error(`ZIP 本地文件头与中央目录不一致:${name}`);
238
+ }
239
+ const localNameLen = view.getUint16(localOffset + 26, true);
240
+ const localExtraLen = view.getUint16(localOffset + 28, true);
241
+ const dataStart = localOffset + 30 + localNameLen + localExtraLen;
242
+ const dataEnd = dataStart + uncompSize;
243
+ if (dataEnd > centralOffset) throw new Error(`ZIP 文件数据越界:${name}`);
244
+ const data = bytes.slice(dataStart, dataEnd);
245
+ if (crc32(data) !== expectedCrc) throw new Error(`ZIP 条目 CRC32 校验失败:${name}`);
246
+ files.set(name, data);
247
+ pos += 46 + nameLen + extraLen + commentLen;
248
+ }
249
+ return files;
250
+ }
251
+
252
+ export function isPluginArchiveV2Bytes(bytes: Uint8Array): boolean {
253
+ return (
254
+ bytes.byteLength >= 4 &&
255
+ bytes[0] === 0x50 &&
256
+ bytes[1] === 0x4b &&
257
+ bytes[2] === 0x03 &&
258
+ bytes[3] === 0x04
259
+ );
260
+ }
261
+
262
+ /** Pack a PluginPackage plus optional raw binary assets (WASM/PNG/SVG/fonts) into a deterministic v2 ZIP. */
263
+ export function packPluginArchiveV2(input: PluginArchiveV2Input): Uint8Array {
264
+ const pkg = parsePluginPackage(JSON.stringify(input.pkg));
265
+ const encoder = new TextEncoder();
266
+ const files = new Map<string, Uint8Array>();
267
+
268
+ files.set('manifest.json', encoder.encode(canonicalPluginJson(pkg.manifest)));
269
+ if (pkg.source !== undefined) {
270
+ files.set('worker.js', encoder.encode(pkg.source));
271
+ }
272
+ if (pkg.automationSource !== undefined) {
273
+ files.set('automation.js', encoder.encode(pkg.automationSource));
274
+ }
275
+ if (pkg.ui) {
276
+ for (const [viewId, bundle] of Object.entries(pkg.ui)) {
277
+ files.set(`ui/${viewId}/index.html`, encoder.encode(bundle.html));
278
+ files.set(`ui/${viewId}/style.css`, encoder.encode(bundle.css));
279
+ files.set(`ui/${viewId}/main.js`, encoder.encode(bundle.source));
280
+ }
281
+ }
282
+ if (pkg.assets?.icons?.length) {
283
+ files.set('assets/icons.json', encoder.encode(canonicalPluginJson(pkg.assets.icons)));
284
+ }
285
+
286
+ const binaryPaths: string[] = [];
287
+ if (input.binaryAssets) {
288
+ for (const [rawPath, data] of Object.entries(input.binaryAssets)) {
289
+ const rel = validateBinaryAssetPath(rawPath);
290
+ if (!(data instanceof Uint8Array)) throw new Error(`二进制资产必须为 Uint8Array:${rawPath}`);
291
+ files.set(`assets/bin/${rel}`, data);
292
+ binaryPaths.push(rel);
293
+ }
294
+ }
295
+ binaryPaths.sort();
296
+ files.set(
297
+ 'archive.json',
298
+ encoder.encode(
299
+ canonicalPluginJson({
300
+ packageVersion: PLUGIN_ARCHIVE_V2_VERSION,
301
+ format: 'tano-zip-v2',
302
+ binaryAssets: binaryPaths,
303
+ }),
304
+ ),
305
+ );
306
+ return encodeDeterministicZip(files);
307
+ }
308
+
309
+ /** Unpack and strictly validate a deterministic packageVersion 2 ZIP container. */
310
+ export function unpackPluginArchiveV2(bytes: Uint8Array): PluginArchiveV2 {
311
+ const files = decodeDeterministicZip(bytes);
312
+ const decoder = new TextDecoder('utf-8', { fatal: true });
313
+ const textOf = (name: string) => {
314
+ const data = files.get(name);
315
+ return data ? decoder.decode(data) : undefined;
316
+ };
317
+
318
+ const archiveMetaRaw = textOf('archive.json');
319
+ if (!archiveMetaRaw) throw new Error('插件 ZIP 缺少 archive.json 元数据');
320
+ const archiveMeta = JSON.parse(archiveMetaRaw);
321
+ if (
322
+ !pluginRecord(archiveMeta) ||
323
+ archiveMeta.packageVersion !== PLUGIN_ARCHIVE_V2_VERSION ||
324
+ archiveMeta.format !== 'tano-zip-v2'
325
+ ) {
326
+ throw new Error('不支持的插件归档版本或格式');
327
+ }
328
+
329
+ const manifestRaw = textOf('manifest.json');
330
+ if (!manifestRaw) throw new Error('插件 ZIP 缺少 manifest.json');
331
+ const manifest = parsePluginManifest(JSON.parse(manifestRaw));
332
+
333
+ const source = textOf('worker.js');
334
+ const automationSource = textOf('automation.js');
335
+
336
+ const uiViewIds = new Set<string>();
337
+ for (const name of files.keys()) {
338
+ const match = name.match(/^ui\/([^/]+)\/(?:index\.html|style\.css|main\.js)$/);
339
+ if (match) uiViewIds.add(match[1]!);
340
+ }
341
+ let ui: Record<string, PluginUiBundle> | undefined;
342
+ if (uiViewIds.size > 0) {
343
+ ui = {};
344
+ for (const viewId of [...uiViewIds].sort()) {
345
+ const html = textOf(`ui/${viewId}/index.html`);
346
+ const css = textOf(`ui/${viewId}/style.css`);
347
+ const uiSource = textOf(`ui/${viewId}/main.js`);
348
+ if (html === undefined || css === undefined || uiSource === undefined) {
349
+ throw new Error(`插件视图 ${viewId} 缺少完整界面资产`);
350
+ }
351
+ ui[viewId] = { html, css, source: uiSource };
352
+ }
353
+ }
354
+
355
+ let icons: FileIconTheme[] | undefined;
356
+ const iconsRaw = textOf('assets/icons.json');
357
+ if (iconsRaw !== undefined) {
358
+ const parsedIcons = JSON.parse(iconsRaw);
359
+ if (!Array.isArray(parsedIcons)) throw new Error('assets/icons.json 格式无效');
360
+ icons = parsedIcons.map((item: unknown) => parseFileIconTheme(item));
361
+ }
362
+
363
+ const pkg = parsePluginPackage(
364
+ JSON.stringify({
365
+ packageVersion: 1,
366
+ manifest,
367
+ ...(source !== undefined ? { source } : {}),
368
+ ...(automationSource !== undefined ? { automationSource } : {}),
369
+ ...(ui ? { ui } : {}),
370
+ ...(icons?.length ? { assets: { icons } } : {}),
371
+ }),
372
+ );
373
+
374
+ const binaryAssets: Record<string, Uint8Array> = {};
375
+ for (const [name, data] of files.entries()) {
376
+ if (name.startsWith('assets/bin/')) {
377
+ binaryAssets[name.slice('assets/bin/'.length)] = data;
378
+ }
379
+ }
380
+
381
+ return {
382
+ packageVersion: PLUGIN_ARCHIVE_V2_VERSION,
383
+ pkg,
384
+ binaryAssets,
385
+ entries: [...files.keys()].sort(),
386
+ };
387
+ }
388
+
389
+ /** Compute SHA-256 hex digest of deterministic archive bytes (Web Crypto, browser + Node 24+). */
390
+ export async function pluginArchiveDigest(bytes: Uint8Array): Promise<string> {
391
+ const copy = new Uint8Array(bytes.byteLength);
392
+ copy.set(bytes);
393
+ const digest = await crypto.subtle.digest('SHA-256', copy.buffer);
394
+ return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('');
395
+ }
@@ -0,0 +1,156 @@
1
+ export const TANO_PLUGIN_API_VERSION = '1.1' as const;
2
+
3
+ export const pluginPlatforms = ['web', 'desktop-local', 'desktop-online', 'mobile'] as const;
4
+ export type PluginPlatform = typeof pluginPlatforms[number];
5
+
6
+ export interface PluginEngines {
7
+ /** Minimum required Tano Core version, e.g. '>=0.14.0'. */
8
+ tano: string;
9
+ }
10
+
11
+ export interface PluginHostEnvironment {
12
+ coreVersion: string;
13
+ platform: PluginPlatform;
14
+ }
15
+
16
+ export interface PluginCompatibilityResult {
17
+ compatible: boolean;
18
+ code?: 'CORE_VERSION_TOO_OLD' | 'PLATFORM_UNSUPPORTED';
19
+ reason?: string;
20
+ }
21
+
22
+ export const pluginErrorCodes = [
23
+ 'PERMISSION_DENIED',
24
+ 'INVALID_ARGUMENT',
25
+ 'NOT_FOUND',
26
+ 'READ_ONLY',
27
+ 'CONFLICT',
28
+ 'STALE_BASELINE',
29
+ 'CURSOR_EXPIRED',
30
+ 'QUOTA_EXCEEDED',
31
+ 'RATE_LIMITED',
32
+ 'TIMEOUT',
33
+ 'UNAVAILABLE',
34
+ 'INSTANCE_STOPPED',
35
+ 'INTERNAL_ERROR',
36
+ ] as const;
37
+ export type PluginErrorCode = typeof pluginErrorCodes[number];
38
+
39
+ export class PluginError extends Error {
40
+ readonly code: PluginErrorCode;
41
+ readonly retryable: boolean;
42
+ constructor(code: PluginErrorCode, message: string, retryable = false) {
43
+ super(message);
44
+ this.name = 'TanoPluginError';
45
+ this.code = code;
46
+ this.retryable = retryable;
47
+ }
48
+ }
49
+
50
+ const triplet = /^(0|[1-9]\d{0,19})\.(0|[1-9]\d{0,19})\.(0|[1-9]\d{0,19})$/;
51
+ const minEngine = /^>=(0|[1-9]\d{0,19})\.(0|[1-9]\d{0,19})\.(0|[1-9]\d{0,19})$/;
52
+
53
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
54
+ return !!value && typeof value === 'object' && !Array.isArray(value);
55
+ }
56
+
57
+ export function compareCoreVersions(left: string, right: string): number {
58
+ const aParts = left.split('.');
59
+ const bParts = right.split('.');
60
+ for (let i = 0; i < 3; i++) {
61
+ const a = BigInt(aParts[i] ?? '0');
62
+ const b = BigInt(bParts[i] ?? '0');
63
+ if (a !== b) return a > b ? 1 : -1;
64
+ }
65
+ return 0;
66
+ }
67
+
68
+ export function parsePluginEngines(value: unknown): PluginEngines {
69
+ if (!isPlainRecord(value) || Object.keys(value).some((key) => key !== 'tano'))
70
+ throw new Error('插件运行环境要求(engines)无效');
71
+ if (typeof value.tano !== 'string' || !minEngine.test(value.tano))
72
+ throw new Error('插件 engines.tano 必须为 >=X.Y.Z 格式的版本要求');
73
+ return { tano: value.tano };
74
+ }
75
+
76
+ export function parsePluginPlatforms(value: unknown): PluginPlatform[] {
77
+ if (
78
+ !Array.isArray(value) ||
79
+ !value.length ||
80
+ value.length > pluginPlatforms.length ||
81
+ value.some((item) => typeof item !== 'string' || !(pluginPlatforms as readonly string[]).includes(item)) ||
82
+ new Set(value).size !== value.length
83
+ )
84
+ throw new Error('插件支持平台(platforms)声明无效');
85
+ return value as PluginPlatform[];
86
+ }
87
+
88
+ const platformLabels: Record<PluginPlatform, string> = {
89
+ web: '浏览器在线端',
90
+ 'desktop-local': '桌面本地工作区',
91
+ 'desktop-online': '桌面在线工作区',
92
+ mobile: '移动端',
93
+ };
94
+
95
+ export function checkPluginCompatibility(
96
+ manifest: { engines?: PluginEngines; platforms?: PluginPlatform[] },
97
+ host: PluginHostEnvironment,
98
+ ): PluginCompatibilityResult {
99
+ if (manifest.engines?.tano) {
100
+ const required = manifest.engines.tano.slice(2);
101
+ const current = host.coreVersion.replace(/-.*$/, '');
102
+ if (triplet.test(current) && compareCoreVersions(current, required) < 0) {
103
+ return {
104
+ compatible: false,
105
+ code: 'CORE_VERSION_TOO_OLD',
106
+ reason: `需要同页核心 >=${required}(当前 ${current}),请升级应用后再启用`,
107
+ };
108
+ }
109
+ }
110
+ if (manifest.platforms?.length && !manifest.platforms.includes(host.platform)) {
111
+ const allowed = manifest.platforms.map((item) => platformLabels[item] ?? item).join('、');
112
+ return {
113
+ compatible: false,
114
+ code: 'PLATFORM_UNSUPPORTED',
115
+ reason: `此插件仅支持 ${allowed},当前环境为 ${platformLabels[host.platform] ?? host.platform}`,
116
+ };
117
+ }
118
+ return { compatible: true };
119
+ }
120
+
121
+ export function classifyPluginError(error: unknown): {
122
+ code: PluginErrorCode;
123
+ message: string;
124
+ retryable: boolean;
125
+ } {
126
+ if (error instanceof PluginError) {
127
+ return { code: error.code, message: error.message, retryable: error.retryable };
128
+ }
129
+ const raw = error instanceof Error ? error.message : String(error);
130
+ const message = raw.replace(/^Error:\s*/, '') || '插件调用失败';
131
+ if (/已停止|已失效|工作区已切换|已关闭/.test(message))
132
+ return { code: 'INSTANCE_STOPPED', message, retryable: false };
133
+ if (/没有\s+[a-z.]+\s+权限|未经授权|未在插件清单中声明|未授权/.test(message))
134
+ return { code: 'PERMISSION_DENIED', message, retryable: false };
135
+ if (/只读|阅读权限/.test(message))
136
+ return { code: 'READ_ONLY', message, retryable: false };
137
+ if (/分页已过期|查询结果已变化/.test(message))
138
+ return { code: 'CURSOR_EXPIRED', message, retryable: true };
139
+ if (/先读取|版本摘要|编辑基线无效|文档版本无效|对象版本无效/.test(message))
140
+ return { code: 'STALE_BASELINE', message, retryable: true };
141
+ if (/冲突|重叠修改|已保存在|发生变化/.test(message))
142
+ return { code: 'CONFLICT', message, retryable: true };
143
+ if (/不存在|不可访问/.test(message))
144
+ return { code: 'NOT_FOUND', message, retryable: false };
145
+ if (/超时/.test(message))
146
+ return { code: 'TIMEOUT', message, retryable: true };
147
+ if (/速率|过多/.test(message))
148
+ return { code: 'RATE_LIMITED', message, retryable: true };
149
+ if (/超过|过大|空间不足|限额/.test(message))
150
+ return { code: 'QUOTA_EXCEEDED', message, retryable: false };
151
+ if (/尚未提供|不可用|不支持此|已关闭/.test(message))
152
+ return { code: 'UNAVAILABLE', message, retryable: false };
153
+ if (/无效|必须|不能|格式/.test(message))
154
+ return { code: 'INVALID_ARGUMENT', message, retryable: false };
155
+ return { code: 'INTERNAL_ERROR', message, retryable: false };
156
+ }
package/src/plugins.ts CHANGED
@@ -1,4 +1,10 @@
1
1
  import { parsePluginAppearance, type PluginAppearance } from './appearance';
2
+ import {
3
+ parsePluginEngines,
4
+ parsePluginPlatforms,
5
+ type PluginEngines,
6
+ type PluginPlatform,
7
+ } from './plugin-compat';
2
8
  import { ObjectTypeRegistry, coreObjectTypes, validObjectType } from './object-types';
3
9
  import type { ObjectField } from './object-types';
4
10
  import type { RelationTypeDefinition } from './relations';
@@ -6,6 +12,8 @@ import type { RelationTypeDefinition } from './relations';
6
12
  export interface ObjectPluginManifest {
7
13
  manifestVersion: 1;
8
14
  appearance?: PluginAppearance;
15
+ engines?: PluginEngines;
16
+ platforms?: PluginPlatform[];
9
17
  id: string;
10
18
  name: string;
11
19
  version: string;
@@ -40,6 +48,8 @@ export function parseObjectPlugin(content: string): ObjectPluginManifest {
40
48
  'objectTypes',
41
49
  'relationTypes',
42
50
  'appearance',
51
+ 'engines',
52
+ 'platforms',
43
53
  ]);
44
54
  if (
45
55
  value.manifestVersion !== 1 ||
@@ -104,6 +114,8 @@ export function parseObjectPlugin(content: string): ObjectPluginManifest {
104
114
  return {
105
115
  ...value,
106
116
  ...(value.appearance === undefined ? {} : { appearance: parsePluginAppearance(value.appearance) }),
117
+ ...(value.engines === undefined ? {} : { engines: parsePluginEngines(value.engines) }),
118
+ ...(value.platforms === undefined ? {} : { platforms: parsePluginPlatforms(value.platforms) }),
107
119
  objectTypes: value.objectTypes.map((type: { fields?: ObjectField[] }) => ({
108
120
  ...type,
109
121
  fields: type.fields ?? [],
package/src/relations.ts CHANGED
@@ -11,10 +11,8 @@ export interface RelationTypeDefinition {
11
11
  plugin?: string;
12
12
  }
13
13
  export const coreRelationTypes: readonly RelationTypeDefinition[] = [
14
- { type: 'member', label: '成员', sourceTypes: ['person'], targetTypes: ['project'], level: 2 },
15
- { type: 'contains', label: '包含', sourceTypes: ['project'], targetTypes: ['task', 'experiment', 'document', 'asset'], level: 2 },
16
14
  { type: 'related', label: '关联', sourceTypes: ['*'], targetTypes: ['*'], level: 2 },
17
- { type: 'assigned', label: '负责', sourceTypes: ['person'], targetTypes: ['event', 'task', 'project', 'experiment'], level: 2 },
15
+ { type: 'assigned', label: '负责', sourceTypes: ['person'], targetTypes: ['event', 'task'], level: 2 },
18
16
  { type: 'authored', label: '撰写', sourceTypes: ['person'], targetTypes: ['document'], level: 2 },
19
17
  { type: 'attends', label: '参加', sourceTypes: ['person'], targetTypes: ['event'], level: 2 },
20
18
  { type: 'attachment', label: '附有资产', sourceTypes: ['*'], targetTypes: ['asset'], level: 2 },
@@ -71,8 +69,6 @@ export function validateRelation(
71
69
  ) {
72
70
  const definition = definitions.find((item) => item.type === row.type);
73
71
  if (!definition) throw new Error('关系类型未启用,请先启用对应插件');
74
- if ([row.source, row.target].some((endpoint) => objectTypeRegistry.get(endpoint.type)?.retired))
75
- throw new Error('项目对象已停用,不能新增关系;已有关系仍保留');
76
72
  if (
77
73
  !acceptsRelationType(definition.sourceTypes, row.source.type) ||
78
74
  !acceptsRelationType(definition.targetTypes, row.target.type)
@@ -1,21 +1,68 @@
1
1
  import { validEventDate } from './object-types';
2
2
  import { isShortId } from './short-id';
3
- export interface TaskRepeat { version: 1; frequency: 'daily' | 'weekly' | 'monthly'; interval: number; anchor: string; until?: string }
3
+ import { isActionableTask } from './plan-item';
4
+
5
+ export type TaskRepeatMode = 'after_complete' | 'schedule';
6
+
7
+ export interface TaskRepeat {
8
+ version: 1;
9
+ mode?: TaskRepeatMode;
10
+ frequency: 'daily' | 'weekly' | 'monthly';
11
+ interval: number;
12
+ anchor: string;
13
+ until?: string;
14
+ exdates?: string[];
15
+ }
16
+
17
+ const ALLOWED_REPEAT_KEYS = new Set([
18
+ 'version',
19
+ 'mode',
20
+ 'frequency',
21
+ 'interval',
22
+ 'anchor',
23
+ 'until',
24
+ 'exdates',
25
+ ]);
26
+
4
27
  export function parseTaskRepeat(value: unknown): TaskRepeat {
5
28
  const rule = value as TaskRepeat;
6
- if (!rule || typeof rule !== 'object' || Array.isArray(rule) || rule.version !== 1 ||
7
- !['daily', 'weekly', 'monthly'].includes(rule.frequency) || !Number.isInteger(rule.interval) || rule.interval < 1 || rule.interval > 99 ||
8
- !validEventDate(rule.anchor) || (rule.until !== undefined && (!validEventDate(rule.until) || rule.until < rule.anchor)) ||
9
- Object.keys(rule).some(key => !['version', 'frequency', 'interval', 'anchor', 'until'].includes(key))) throw new Error('重复任务规则无效');
29
+ if (
30
+ !rule ||
31
+ typeof rule !== 'object' ||
32
+ Array.isArray(rule) ||
33
+ rule.version !== 1 ||
34
+ (rule.mode !== undefined && !['after_complete', 'schedule'].includes(rule.mode)) ||
35
+ !['daily', 'weekly', 'monthly'].includes(rule.frequency) ||
36
+ !Number.isInteger(rule.interval) ||
37
+ rule.interval < 1 ||
38
+ rule.interval > 99 ||
39
+ !validEventDate(rule.anchor) ||
40
+ (rule.until !== undefined && (!validEventDate(rule.until) || rule.until < rule.anchor)) ||
41
+ (rule.exdates !== undefined &&
42
+ (!Array.isArray(rule.exdates) ||
43
+ rule.exdates.length > 500 ||
44
+ !rule.exdates.every((day) => validEventDate(day)))) ||
45
+ Object.keys(rule).some((key) => !ALLOWED_REPEAT_KEYS.has(key))
46
+ ) {
47
+ throw new Error('重复任务规则无效');
48
+ }
10
49
  return rule;
11
50
  }
51
+
12
52
  export function validateTaskRepeat(type: string, properties: Record<string, unknown>) {
13
53
  if (properties.repeat !== undefined) {
14
- if (!(type === 'task' || type === 'event' && properties.checkable === true)) throw new Error('只有任务可以设置重复规则');
15
- parseTaskRepeat(properties.repeat);
54
+ const rule = parseTaskRepeat(properties.repeat);
55
+ if (rule.mode !== 'schedule' && !isActionableTask({ type, properties })) {
56
+ throw new Error('只有任务可以设置重复规则');
57
+ }
16
58
  }
17
59
  if (properties.repeatSourceId !== undefined || properties.repeatOccurrence !== undefined) {
18
- if (!isShortId(properties.repeatSourceId) || !validEventDate(properties.repeatOccurrence) || properties.repeat === undefined)
60
+ if (
61
+ !isShortId(properties.repeatSourceId) ||
62
+ !validEventDate(properties.repeatOccurrence) ||
63
+ properties.repeat === undefined
64
+ ) {
19
65
  throw new Error('重复任务实例身份无效');
66
+ }
20
67
  }
21
68
  }