pi-tsgw 3.0.0 → 3.2.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/README.md +25 -2
- package/extensions/config.ts +4 -1
- package/extensions/dav/calendar-write-schema.ts +50 -0
- package/extensions/dav/calendar-write.ts +186 -0
- package/extensions/dav/calendar.ts +217 -0
- package/extensions/dav/client.ts +105 -0
- package/extensions/dav/config.ts +35 -0
- package/extensions/dav/contact-action-schema.ts +37 -0
- package/extensions/dav/contact-actions.ts +142 -0
- package/extensions/dav/contacts.ts +101 -0
- package/extensions/dav/content.ts +49 -0
- package/extensions/dav/index.ts +18 -0
- package/extensions/dav/mutations.ts +38 -0
- package/extensions/dav/schema.ts +37 -0
- package/extensions/dav/tools.ts +103 -0
- package/extensions/dav/types.ts +37 -0
- package/index.ts +2 -0
- package/package.json +5 -2
- package/skills/tsgw-synology-dav/SKILL.md +34 -6
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# pi-tsgw
|
|
2
2
|
|
|
3
|
-
自用的 Pi 扩展,为 TOSSP AIH gateway 提供模型目录、请求适配、联网搜索、图片生成与编辑、分类模型及配套工作流,并提供可选的 IMAP/SMTP
|
|
3
|
+
自用的 Pi 扩展,为 TOSSP AIH gateway 提供模型目录、请求适配、联网搜索、图片生成与编辑、分类模型及配套工作流,并提供可选的 IMAP/SMTP 邮件与 DAV 日历、联系人组件。以 MIT 许可证公开。
|
|
4
4
|
|
|
5
5
|
## 安装
|
|
6
6
|
|
|
@@ -31,7 +31,7 @@ pi install npm:pi-tsgw
|
|
|
31
31
|
|
|
32
32
|
## 工具入口
|
|
33
33
|
|
|
34
|
-
|
|
34
|
+
图片、上传、代理搜索、邮件及 DAV 工具均为 `deferred` 注册,通过 codemode 按需发现和调用,不默认声明完整工具 schema。使用 `describeNamespace("tsgw_images")`、`describeNamespace("tsgw_upload")`、`describeNamespace("tsgw_search")` 、`describeNamespace("tsgw_email")` 或 `describeNamespace("tsgw_dav")` 查看对应能力。用法见[图片技能](skills/tsgw-image-generation/SKILL.md)、[上传技能](skills/tsgw-upload/SKILL.md)、[搜索技能](skills/tsgw-search/SKILL.md)、[邮件技能](skills/tsgw-email/SKILL.md)及[DAV 技能](skills/tsgw-synology-dav/SKILL.md)。
|
|
35
35
|
|
|
36
36
|
图片工具固定登记已接入的两款模型,不受 `tsgw.includeModels` / `excludeModels` 或网关模型目录缺席影响;仍复用宿主认证,由实际调用确认上游支持,失败不自动重试或换模型。
|
|
37
37
|
|
|
@@ -72,4 +72,27 @@ pi install npm:pi-tsgw
|
|
|
72
72
|
|
|
73
73
|
`implicit` 表示连接即 TLS;`starttls` 必须成功升级 TLS,均校验证书。SMTP 可选 `fromName` 和 `envelopeFrom`;未配置后者时信封发件人跟随最终 From。`allowSenderOverride: true` 允许自定义发件地址和名称;可配非空 `allowedFromDomains` 数组限定最终 From 的域(含默认地址),忽略大小写,兼容 Unicode/Punycode,子域须单列;省略则不额外限制域,不影响已有配置。该字段不限制独立的 `envelopeFrom`,也不验证 SPF/DKIM/DMARC 或保证投递成功。邮件工具统一 `tsgw_email_` 前缀,通过 codemode 的 `describeNamespace("tsgw_email")` 按需发现,不直接声明或内联到模型上下文。无后台同步、磁盘缓存、自动重发、出口切换或发送后存档;读取不自动标已读。附件仅允许当前工作目录或系统临时目录,不允许访问宿主配置目录,符号链接按真实路径校验。超出读取预算、原始头部不是合法 UTF-8,或 inline 文本附件会被库转换字符集/flowed 格式时,会明确报告,不把截断或改写内容当作完整原文。
|
|
74
74
|
|
|
75
|
+
## 可选 DAV 配置
|
|
76
|
+
|
|
77
|
+
在同一 `tsgw.json` 的 `dav` 组按 ID 添加配置,不创建独立文件:
|
|
78
|
+
|
|
79
|
+
```json
|
|
80
|
+
{
|
|
81
|
+
"dav": {
|
|
82
|
+
"work": {
|
|
83
|
+
"url": "https://dav.example.invalid/",
|
|
84
|
+
"user": "<登录账号>",
|
|
85
|
+
"password": "<应用密码>",
|
|
86
|
+
"timeZone": "Asia/Shanghai"
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
`timeZone` 可省略,但事件展开必须在调用时明确时区;不用主机时区推断。密码为本地填写的普通字符串,不支持命令或环境变量占位符。根 URL 的服务发现使用标准 `/.well-known/caldav`/`carddav` 入口,最多跟随三次同源跳转;配置具体服务路径时按原路径发现,不探测其他端口或厂商私有路径。资源读取不跟随跳转,始终校验证书。
|
|
93
|
+
|
|
94
|
+
通过 codemode 发现 `tsgw_dav`,先 `accounts`,再以明确账户和类型调用 `collections`;列表须传实际集合,详情使用返回的资源 URL。提供账户、集合,日程/待办/日记/联系人的 list/get/create/update/delete,以及多字段 contact_search;创建、修改、删除均须明确授权。更新或删除先读取并核对调用方确认的强 ETag,冲突不重试;日历删除针对整资源,不是某次展开实例。日程读取所选日历全部事件资源,再由库按明确时区与窗口展开过滤,避免服务端时区不同导致漏项;代价是大日历读取量较大。待办与日记只返回已存储组件;正常摘要不包含原文,正常详情用 `raw: true` 取得源文本;解释失败的资源保留原文与诊断,并分别标明资源获取和业务结果的完整性,不当作无匹配或已知空闲。日历可仅凭实际资源 URL 与 `raw: true` 取整资源。读取和搜索超过结果预算会明确失败,不截断原文或列表。创建、更新和无变化候选均检查最终整份资源;源异常修订信息不能借自动刷新掩盖,无法修正或验证则停写。写工具只返回身份、版本与结果,不在内部回读;REMOTE_RESULT_UNKNOWN 表示可能已生效,应先核对目标,不能自动重发。
|
|
95
|
+
|
|
96
|
+
DAV 业务调用需要 Node.js 24+ 及可选依赖 `davkit`;Node.js 22 或省略 optional 依赖仍可加载插件并发现工具,调用 DAV 时返回环境指导,不影响其他能力,也不会自动安装依赖或改用旧 MCP。注册阶段不读配置或联网;DAV 配置按次调用加载,不自动迁移旧 DAV 凭据、切换账号或重试。
|
|
97
|
+
|
|
75
98
|
开发维护约定见 [AGENTS.md](https://github.com/tossp/pi-tsgw/blob/main/AGENTS.md)。
|
package/extensions/config.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { readFileSync, statSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
+
import { DavConfigError, parseDavAccounts, type DavAccountConfig } from "./dav/config.ts";
|
|
4
5
|
import {
|
|
5
6
|
EmailConfigError, parseImapAccounts, parseSmtpConfigs,
|
|
6
7
|
type ImapAccountConfig, type SmtpConfig,
|
|
@@ -9,6 +10,7 @@ import {
|
|
|
9
10
|
export interface ConfigMap {
|
|
10
11
|
imap: ImapAccountConfig;
|
|
11
12
|
smtp: SmtpConfig;
|
|
13
|
+
dav: DavAccountConfig;
|
|
12
14
|
}
|
|
13
15
|
|
|
14
16
|
export type ConfigResult<T> =
|
|
@@ -19,6 +21,7 @@ export type ConfigResult<T> =
|
|
|
19
21
|
const factories: { [K in keyof ConfigMap]: (raw: unknown) => Record<string, ConfigMap[K]> } = {
|
|
20
22
|
imap: parseImapAccounts,
|
|
21
23
|
smtp: parseSmtpConfigs,
|
|
24
|
+
dav: parseDavAccounts,
|
|
22
25
|
};
|
|
23
26
|
|
|
24
27
|
/** 只读统一文件并校验本次所需类型;不探测旧入口、不迁移、不联网。 */
|
|
@@ -57,7 +60,7 @@ export function readConfig<K extends keyof ConfigMap>(
|
|
|
57
60
|
const config = factories[kind]((raw as Record<string, unknown>)[kind]);
|
|
58
61
|
return Object.keys(config).length ? { status: "ready", config } : { status: "missing" };
|
|
59
62
|
} catch (error) {
|
|
60
|
-
return { status: "invalid", message: error instanceof EmailConfigError
|
|
63
|
+
return { status: "invalid", message: error instanceof EmailConfigError || error instanceof DavConfigError
|
|
61
64
|
? error.message : "扩展配置类型无效。" };
|
|
62
65
|
}
|
|
63
66
|
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
|
|
3
|
+
const options = { additionalProperties: false } as const;
|
|
4
|
+
const id = Type.String({ minLength: 1, pattern: "^[^\\u0000-\\u001f\\u007f]+$" });
|
|
5
|
+
const url = Type.String({ minLength: 1, description: "已发现的同源完整 URL;创建仅接受明确集合,不接受自定资源路径。" });
|
|
6
|
+
const basicTime = Type.String({ pattern: "^\\d{8}(?:T\\d{6}Z?)?$" });
|
|
7
|
+
const time = Type.Union([
|
|
8
|
+
basicTime,
|
|
9
|
+
Type.Object({ value: basicTime,
|
|
10
|
+
valueType: Type.Optional(Type.Union([Type.Literal("DATE"), Type.Literal("DATE-TIME")])),
|
|
11
|
+
tzid: Type.Optional(Type.String({ minLength: 1 })),
|
|
12
|
+
}, options),
|
|
13
|
+
], { description: "仅基本日历时间 YYYYMMDD / YYYYMMDDTHHmmss[Z],不支持 ISO;对象 DATE 须声明 valueType。创建不猜时区;更新字符串沿用原表示,新增时间属性须用对象。TZID 明确指定,不将当地重复系列固定转 UTC。" });
|
|
14
|
+
const nullableTime = Type.Optional(Type.Union([time, Type.Null()]));
|
|
15
|
+
const scalar = Type.Optional(Type.String());
|
|
16
|
+
const nullableScalar = Type.Optional(Type.Union([Type.String(), Type.Null()]));
|
|
17
|
+
const properties = Type.Optional(Type.Array(Type.String({ minLength: 1 }), {
|
|
18
|
+
description: "未折行的完整逻辑属性;更新按基本名整组替换,省略或 [] 不修改。不得与便捷字段冲突,不能设置 UID/VERSION/RECURRENCE-ID 或受管 DTSTAMP/LAST-MODIFIED/SEQUENCE。",
|
|
19
|
+
}));
|
|
20
|
+
const alarms = Type.Optional(Type.Array(Type.String({ minLength: 1 }), {
|
|
21
|
+
description: "完整 VALARM 块,由库验证依赖;省略保留,[] 清空。不支持日记提醒。",
|
|
22
|
+
}));
|
|
23
|
+
const create = { account: id, collectionUrl: url, summary: Type.String(),
|
|
24
|
+
description: scalar, location: scalar, status: scalar, properties };
|
|
25
|
+
const identity = { account: id, resourceUrl: url, uid: id,
|
|
26
|
+
etag: Type.String({ minLength: 1, description: "上次读取并确认的单个强 ETag;不接受弱标签、通配符或列表。" }) };
|
|
27
|
+
const update = { ...identity,
|
|
28
|
+
recurrenceId: Type.Optional(Type.String({ minLength: 1, description: "已有例外的完整 RECURRENCE-ID 逻辑行;省略只选主件,拒绝 RANGE,不隐式创建例外。" })),
|
|
29
|
+
summary: nullableScalar, description: nullableScalar, location: nullableScalar, status: nullableScalar,
|
|
30
|
+
properties,
|
|
31
|
+
removeProperties: Type.Optional(Type.Array(Type.String({ minLength: 1 }), {
|
|
32
|
+
description: "显式删除整组基本属性名;不能与同名字段/properties 混用,也不能删除身份或受管修订元数据。",
|
|
33
|
+
})),
|
|
34
|
+
};
|
|
35
|
+
const rrule = Type.Optional(Type.String({ minLength: 1, description: "RRULE 的完整值(不带 RRULE:);与 properties/removeProperties 的 RRULE 操作互斥。" }));
|
|
36
|
+
const deleteResource = Type.Object(identity, { ...options,
|
|
37
|
+
description: "删除整份资源而非单次发生项;GET 版本核对及整资源 kind/UID 校验后条件删除,不接受 recurrenceId。" });
|
|
38
|
+
|
|
39
|
+
export const calendarWriteSchemas = {
|
|
40
|
+
event_create: Type.Object({ ...create, start: time, end: Type.Optional(time), rrule, alarms }, options),
|
|
41
|
+
event_update: Type.Object({ ...update, start: nullableTime, end: nullableTime,
|
|
42
|
+
rrule: Type.Optional(Type.Union([Type.String({ minLength: 1 }), Type.Null()])), alarms }, options),
|
|
43
|
+
event_delete: deleteResource,
|
|
44
|
+
todo_create: Type.Object({ ...create, start: Type.Optional(time), due: Type.Optional(time), alarms }, options),
|
|
45
|
+
todo_update: Type.Object({ ...update, start: nullableTime, due: nullableTime, alarms }, options),
|
|
46
|
+
todo_delete: deleteResource,
|
|
47
|
+
journal_create: Type.Object({ ...create, date: time }, options),
|
|
48
|
+
journal_update: Type.Object({ ...update, date: nullableTime }, options),
|
|
49
|
+
journal_delete: deleteResource,
|
|
50
|
+
};
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import type { CalendarComponentEdit, CalendarComponentKind, CalendarTimeInput, ContentValidationResult } from "davkit/ical";
|
|
2
|
+
import { assertManagedMetadata, assertValidContent } from "./content.ts";
|
|
3
|
+
import { contentOperation, createResourceUrl, getVersionedResource, utcStamp } from "./mutations.ts";
|
|
4
|
+
import { DavToolError, type DavReadContext } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
type Time = string | CalendarTimeInput;
|
|
7
|
+
interface Fields {
|
|
8
|
+
summary?: string | null;
|
|
9
|
+
description?: string | null;
|
|
10
|
+
location?: string | null;
|
|
11
|
+
status?: string | null;
|
|
12
|
+
start?: Time | null;
|
|
13
|
+
end?: Time | null;
|
|
14
|
+
due?: Time | null;
|
|
15
|
+
date?: Time | null;
|
|
16
|
+
rrule?: string | null;
|
|
17
|
+
properties?: string[];
|
|
18
|
+
alarms?: string[];
|
|
19
|
+
}
|
|
20
|
+
export interface CalendarCreateInput extends Fields { account: string; collectionUrl: string; summary: string }
|
|
21
|
+
export interface CalendarUpdateInput extends Fields {
|
|
22
|
+
account: string; resourceUrl: string; uid: string; etag: string;
|
|
23
|
+
recurrenceId?: string;
|
|
24
|
+
removeProperties?: string[];
|
|
25
|
+
}
|
|
26
|
+
export interface CalendarDeleteInput { account: string; resourceUrl: string; uid: string; etag: string }
|
|
27
|
+
|
|
28
|
+
const contentType = "text/calendar; charset=utf-8";
|
|
29
|
+
const protectedNames = new Set(["UID", "VERSION", "PRODID", "RECURRENCE-ID", "DTSTAMP", "LAST-MODIFIED", "SEQUENCE", "BEGIN", "END"]);
|
|
30
|
+
const scalarNames = { summary: "SUMMARY", description: "DESCRIPTION", location: "LOCATION", status: "STATUS",
|
|
31
|
+
start: "DTSTART", date: "DTSTART", end: "DTEND", due: "DUE", rrule: "RRULE" } as const;
|
|
32
|
+
|
|
33
|
+
function invalid(message: string): never { throw new DavToolError("INVALID_INPUT", message); }
|
|
34
|
+
|
|
35
|
+
/** 只识别调用方属性的基本名以检查业务冲突,完整语法仍交给库;不扫描源原文。 */
|
|
36
|
+
function inputPropertyName(line: string): string {
|
|
37
|
+
const match = /^(?:[a-z0-9-]+\.)?([a-z0-9-]+)(?=[;:])/i.exec(line);
|
|
38
|
+
if (!match || /[\r\n]/.test(line)) return invalid("properties 必须是未折行的完整逻辑属性。");
|
|
39
|
+
return match[1]!.toUpperCase();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function validateFields(input: Fields & { removeProperties?: string[] }, kind: CalendarComponentKind) {
|
|
43
|
+
if ((kind !== "VEVENT" && (input.end !== undefined || input.rrule !== undefined)) ||
|
|
44
|
+
(kind !== "VTODO" && input.due !== undefined) ||
|
|
45
|
+
(kind !== "VJOURNAL" && input.date !== undefined) ||
|
|
46
|
+
(kind === "VJOURNAL" && (input.start !== undefined || input.alarms !== undefined)))
|
|
47
|
+
invalid("字段不适用于指定日历类型;日记时间使用 date,提醒仅支持事件和待办。");
|
|
48
|
+
const names = new Set((input.properties ?? []).map(inputPropertyName));
|
|
49
|
+
const removals = new Set((input.removeProperties ?? []).map(name => {
|
|
50
|
+
if (!/^[a-z0-9-]+$/i.test(name)) return invalid("removeProperties 仅接受基本属性名。");
|
|
51
|
+
return name.toUpperCase();
|
|
52
|
+
}));
|
|
53
|
+
for (const name of [...names, ...removals]) {
|
|
54
|
+
if (protectedNames.has(name)) invalid("不能直接设置或删除身份、版本及受管修订元数据。");
|
|
55
|
+
if (names.has(name) && removals.has(name)) invalid("同名属性不能同时设置和删除。");
|
|
56
|
+
}
|
|
57
|
+
for (const [key, name] of Object.entries(scalarNames)) {
|
|
58
|
+
if (input[key as keyof typeof scalarNames] !== undefined && (names.has(name) || removals.has(name)))
|
|
59
|
+
invalid("便捷字段与同名完整属性或删除操作冲突。");
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function createTime(context: DavReadContext, name: string, input: Time): string {
|
|
64
|
+
const value = typeof input === "string"
|
|
65
|
+
? { value: input, ...(/^\d{8}$/.test(input) ? { valueType: "DATE" as const } : {}) }
|
|
66
|
+
: input;
|
|
67
|
+
if (value.tzid !== undefined && !/^[a-z0-9_+\-/]+$/i.test(value.tzid))
|
|
68
|
+
invalid("TZID 必须是明确且可解析的时区标识。");
|
|
69
|
+
const time = context.ical.parseCalendarTime(value.value, value);
|
|
70
|
+
if (time.unresolvedReason !== null) invalid("时间或时区无法唯一解释,不能猜测当地时间。");
|
|
71
|
+
return `${name}${time.kind === "date" ? ";VALUE=DATE" : time.tzid ? `;TZID=${time.tzid}` : ""}:${time.value}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function recurrenceLine(value: string): string {
|
|
75
|
+
if (!value || /[\r\n]/.test(value)) invalid("rrule 只接收单行规则值,不包含 RRULE:。");
|
|
76
|
+
return `RRULE:${value}`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function selector(input: CalendarUpdateInput, kind: CalendarComponentKind) {
|
|
80
|
+
if (input.recurrenceId !== undefined &&
|
|
81
|
+
(!/^RECURRENCE-ID[;:]/i.test(input.recurrenceId) || /[\r\n]/.test(input.recurrenceId)))
|
|
82
|
+
invalid("例外选择器必须是完整 RECURRENCE-ID 逻辑行,不能使用裸时间或展开实例身份。");
|
|
83
|
+
return { kind, uid: input.uid, ...(input.recurrenceId === undefined ? {} : { recurrenceId: input.recurrenceId }) };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** 旧编辑器失败时尚无最终候选;只附已取得的库源诊断,不猜测或回显底层异常。 */
|
|
87
|
+
function candidateOperation<T>(operation: () => T, validation: ContentValidationResult,
|
|
88
|
+
details: Record<string, unknown>, stage: "source" | "edit" | "revision"): T {
|
|
89
|
+
try { return operation(); }
|
|
90
|
+
catch (error) {
|
|
91
|
+
if (error instanceof DavToolError) throw error;
|
|
92
|
+
if (stage === "edit" && validation.valid)
|
|
93
|
+
throw new DavToolError("INVALID_INPUT", "库未能应用本次字段组合,尚未生成最终候选;请核对时间表示、属性覆盖和提醒依赖。",
|
|
94
|
+
{ ...details, stage });
|
|
95
|
+
throw new DavToolError("REPAIR_UNSUPPORTED", stage === "source"
|
|
96
|
+
? "源内容无法可靠解析或确认身份,不能确认受管修订信息,未执行写入。"
|
|
97
|
+
: "库未能生成最终候选,尚未执行最终校验;现有单组件编辑无法确认完成所需修正,不能绕过源或兄弟组件限制。",
|
|
98
|
+
{ ...details, stage, issues: validation.issues });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function selectComponent(context: DavReadContext, raw: string, input: CalendarUpdateInput, kind: CalendarComponentKind,
|
|
103
|
+
validation: ContentValidationResult, details: Record<string, unknown>) {
|
|
104
|
+
const components = candidateOperation(() => context.ical.parseCalendar(raw), validation, details, "source").components
|
|
105
|
+
.filter(component => component.kind === kind && component.uid === input.uid &&
|
|
106
|
+
component.recurrenceId === (input.recurrenceId ?? null));
|
|
107
|
+
if (components.length > 1) throw new DavToolError("AMBIGUOUS_TARGET", "资源内目标组件不唯一,未执行写入。");
|
|
108
|
+
const component = components[0];
|
|
109
|
+
if (!component) throw new DavToolError("NOT_FOUND", "资源内未找到指定组件;不能隐式创建例外。");
|
|
110
|
+
if (component.properties.some(property => property.name === "RECURRENCE-ID" && property.parameters.RANGE !== undefined))
|
|
111
|
+
throw new DavToolError("RECURRENCE_UNSUPPORTED", "不支持 RECURRENCE-ID 带 RANGE 的目标。");
|
|
112
|
+
return component;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function createCalendar(context: DavReadContext, input: CalendarCreateInput, kind: CalendarComponentKind) {
|
|
116
|
+
validateFields(input, kind);
|
|
117
|
+
if (typeof input.summary !== "string") invalid("创建必须提供 summary。");
|
|
118
|
+
if (kind === "VEVENT" && input.start == null) invalid("创建事件必须提供 start。");
|
|
119
|
+
if (kind === "VJOURNAL" && input.date == null) invalid("创建日记必须明确提供 date,不使用默认当天。");
|
|
120
|
+
const raw = contentOperation(() => {
|
|
121
|
+
const properties = [...(input.properties ?? []), `LAST-MODIFIED:${utcStamp()}`, "SEQUENCE:0"];
|
|
122
|
+
for (const [field, name] of [["start", "DTSTART"], ["end", "DTEND"], ["due", "DUE"], ["date", "DTSTART"]] as const) {
|
|
123
|
+
const value = input[field];
|
|
124
|
+
if (value === null) invalid("创建时间字段不能为 null。");
|
|
125
|
+
if (value !== undefined) properties.push(createTime(context, name, value));
|
|
126
|
+
}
|
|
127
|
+
if (input.rrule === null) invalid("创建 rrule 不能为 null。");
|
|
128
|
+
if (input.rrule !== undefined) properties.push(recurrenceLine(input.rrule));
|
|
129
|
+
let data = context.ical.buildCalendarComponent({ kind, summary: input.summary, properties, alarms: input.alarms });
|
|
130
|
+
const component = context.ical.parseCalendar(data).components[0]!;
|
|
131
|
+
const edit: CalendarComponentEdit = {};
|
|
132
|
+
for (const field of ["description", "location", "status"] as const) {
|
|
133
|
+
if (input[field] === null) invalid("创建文字字段不能为 null。");
|
|
134
|
+
if (input[field] !== undefined) edit[field] = input[field];
|
|
135
|
+
}
|
|
136
|
+
data = context.ical.updateCalendarComponent(data, { kind, uid: component.uid }, edit);
|
|
137
|
+
return { data, uid: component.uid };
|
|
138
|
+
});
|
|
139
|
+
const resourceUrl = createResourceUrl(input.collectionUrl, "ics");
|
|
140
|
+
assertValidContent(context.ical.validateCalendarResource(raw.data), { account: input.account, resourceUrl, uid: raw.uid, kind });
|
|
141
|
+
context.writeIdentity = { account: input.account, kind, uid: raw.uid };
|
|
142
|
+
const etag = await context.client.create(resourceUrl, raw.data, contentType);
|
|
143
|
+
return { account: input.account, kind, resourceUrl, uid: raw.uid, etag, outcome: "created" as const };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function updateCalendar(context: DavReadContext, input: CalendarUpdateInput, kind: CalendarComponentKind) {
|
|
147
|
+
validateFields(input, kind);
|
|
148
|
+
const target = selector(input, kind);
|
|
149
|
+
const resource = await getVersionedResource(context, input);
|
|
150
|
+
const details = { account: input.account, resourceUrl: input.resourceUrl, uid: input.uid, kind };
|
|
151
|
+
const validation = context.ical.validateCalendarResource(resource.data);
|
|
152
|
+
const component = selectComponent(context, resource.data, input, kind, validation, details);
|
|
153
|
+
// 不要求整个源 valid;只防止正常刷新覆盖尚不能表达修正的源元数据。
|
|
154
|
+
assertManagedMetadata(validation, ["DTSTAMP", "LAST-MODIFIED", "SEQUENCE"], details);
|
|
155
|
+
const edited = candidateOperation(() => {
|
|
156
|
+
const edit: CalendarComponentEdit = { properties: [...(input.properties ?? [])],
|
|
157
|
+
removeProperties: [...(input.removeProperties ?? [])], alarms: input.alarms };
|
|
158
|
+
for (const field of ["summary", "description", "location", "status", "start", "end", "due"] as const) {
|
|
159
|
+
if (input[field] !== undefined) Object.assign(edit, { [field]: input[field] });
|
|
160
|
+
}
|
|
161
|
+
if (input.date !== undefined) edit.start = input.date;
|
|
162
|
+
if (input.rrule === null) edit.removeProperties!.push("RRULE");
|
|
163
|
+
else if (input.rrule !== undefined) edit.properties!.push(recurrenceLine(input.rrule));
|
|
164
|
+
return context.ical.updateCalendarComponent(resource.data, target, edit);
|
|
165
|
+
}, validation, details, "edit");
|
|
166
|
+
if (edited === resource.data) {
|
|
167
|
+
assertValidContent(context.ical.validateCalendarResource(edited), details);
|
|
168
|
+
return { account: input.account, kind, resourceUrl: input.resourceUrl, uid: input.uid, etag: input.etag, outcome: "unchanged" as const };
|
|
169
|
+
}
|
|
170
|
+
// 值与单值约束由源诊断负责;缺省 SEQUENCE 按既有策略从 0 递增。
|
|
171
|
+
const sequence = Number(component.properties.find(property => property.name === "SEQUENCE")?.rawValue ?? 0) + 1;
|
|
172
|
+
const stamp = utcStamp();
|
|
173
|
+
const data = candidateOperation(() => context.ical.updateCalendarComponent(edited, target,
|
|
174
|
+
{ properties: [`DTSTAMP:${stamp}`, `LAST-MODIFIED:${stamp}`, `SEQUENCE:${sequence}`] }), validation, details, "revision");
|
|
175
|
+
assertValidContent(context.ical.validateCalendarResource(data), details);
|
|
176
|
+
const etag = await context.client.update(input.resourceUrl, data, input.etag, contentType);
|
|
177
|
+
return { account: input.account, kind, resourceUrl: input.resourceUrl, uid: input.uid, etag, outcome: "updated" as const };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export async function deleteCalendar(context: DavReadContext, input: CalendarDeleteInput, kind: CalendarComponentKind) {
|
|
181
|
+
if ("recurrenceId" in input) invalid("删除针对整份资源,不接受 recurrenceId。");
|
|
182
|
+
const resource = await getVersionedResource(context, input);
|
|
183
|
+
contentOperation(() => context.ical.assertCalendarResourceIdentity(resource.data, { kind, uid: input.uid }), "DATA_INVALID");
|
|
184
|
+
await context.client.delete(input.resourceUrl, input.etag);
|
|
185
|
+
return { account: input.account, kind, resourceUrl: input.resourceUrl, uid: input.uid, etag: input.etag, outcome: "deleted" as const };
|
|
186
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import type { DavResource } from "davkit/dav";
|
|
2
|
+
import type { CalendarComponent, CalendarComponentKind, CalendarProperty, ContentValidationResult } from "davkit/ical";
|
|
3
|
+
import { unresolvedResource, type ReadFailureStage } from "./content.ts";
|
|
4
|
+
import { DavToolError, type CalendarGetInput, type CalendarListInput, type DavReadContext } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
/** 只包围同步本地内容调用;网络、协议和取消不进入此边界。 */
|
|
7
|
+
function readContent<T>(read: () => T): { ok: true; value: T } | { ok: false } {
|
|
8
|
+
try { return { ok: true, value: read() }; }
|
|
9
|
+
catch (error) {
|
|
10
|
+
// 按库公开的异常名称区分,避免工具登记期加载可选依赖。
|
|
11
|
+
if (error instanceof DavToolError || (error instanceof Error &&
|
|
12
|
+
["DavError", "DavConflictError", "DavProtocolError", "AbortError", "TimeoutError"].includes(error.name))) throw error;
|
|
13
|
+
return { ok: false };
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function validation(context: DavReadContext, raw: string): ContentValidationResult | undefined {
|
|
18
|
+
const result = readContent(() => context.ical.validateCalendarResource(raw));
|
|
19
|
+
return result.ok ? result.value : undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 日期是否合法由公开库校验;Date 只转换显式 offset,不丢弃非零毫秒。 */
|
|
23
|
+
function windowTime(context: DavReadContext, value: string | undefined): { value: string; instant: number } {
|
|
24
|
+
try {
|
|
25
|
+
if (!value) throw new Error();
|
|
26
|
+
let basic = value;
|
|
27
|
+
if (basic.length !== 16 || !/^\d{8}T\d{6}Z$/.test(basic)) {
|
|
28
|
+
const iso = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.000)?(Z|[+-]\d{2}:\d{2})$/.exec(value);
|
|
29
|
+
if (!iso) throw new Error();
|
|
30
|
+
// Date 会把 2 月 30 日等输入归一化,须先验证原始墙钟字段。
|
|
31
|
+
context.ical.parseCalendarTime(`${iso[1]}${iso[2]}${iso[3]}T${iso[4]}${iso[5]}${iso[6]}`);
|
|
32
|
+
basic = new Date(value).toISOString().replace(/[-:]/g, "").replace(".000", "");
|
|
33
|
+
}
|
|
34
|
+
const time = context.ical.parseCalendarTime(basic);
|
|
35
|
+
if (time.kind !== "utc" || time.epochMilliseconds === null) throw new Error();
|
|
36
|
+
return { value: basic, instant: time.epochMilliseconds };
|
|
37
|
+
} catch {
|
|
38
|
+
throw new DavToolError("INVALID_INPUT", "事件时间窗须为有效的秒精度基本 UTC 时间或带显式 Z/offset 的 ISO 8601 时间");
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function eventWindow(context: DavReadContext, input: CalendarListInput) {
|
|
43
|
+
const start = windowTime(context, input.start), end = windowTime(context, input.end);
|
|
44
|
+
if (start.instant >= end.instant) throw new DavToolError("INVALID_INPUT", "事件时间窗的 start 必须早于 end");
|
|
45
|
+
const timeZone = input.timeZone ?? context.timeZone;
|
|
46
|
+
if (!timeZone) throw new DavToolError("TIMEZONE_REQUIRED", "事件展开需要显式指定 timeZone 或配置账户时区");
|
|
47
|
+
try { new Intl.DateTimeFormat("en-US", { timeZone }); }
|
|
48
|
+
catch { throw new DavToolError("INVALID_INPUT", "事件展开时区无效"); }
|
|
49
|
+
return { start: start.value, end: end.value, timeZone };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function rejectRange(component: CalendarComponent) {
|
|
53
|
+
if (component.properties.some(property => property.name === "RECURRENCE-ID" && property.parameters.RANGE !== undefined)) {
|
|
54
|
+
throw new Error("无法解释范围例外");
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function matches(component: CalendarComponent, input: CalendarListInput, kind: CalendarComponentKind) {
|
|
59
|
+
return component.kind === kind && (input.uid === undefined || component.uid === input.uid) &&
|
|
60
|
+
(input.status === undefined || component.status?.toUpperCase() === input.status.toUpperCase());
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function summary(component: CalendarComponent) {
|
|
64
|
+
// 不以解析器的首项投影掩盖单值字段歧义。
|
|
65
|
+
for (const name of ["SUMMARY", "LOCATION", "STATUS"]) {
|
|
66
|
+
if (component.properties.filter(property => property.name === name).length > 1) throw new Error("字段有歧义");
|
|
67
|
+
}
|
|
68
|
+
return { kind: component.kind, uid: component.uid, summary: component.summary,
|
|
69
|
+
location: component.location, status: component.status };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 仅针对筛选/取消语义使用 STATUS 诊断,不用整资源 valid 作为读取门槛。 */
|
|
73
|
+
function reliableStatus(component: CalendarComponent, checked: ContentValidationResult | undefined) {
|
|
74
|
+
if (!component.properties.some(property => property.name === "STATUS")) return true;
|
|
75
|
+
return checked !== undefined && !checked.issues.some(issue => issue.property === "STATUS");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 存储组件只投影时间,不自行解释 floating/DATE 为某个时区的 instant。 */
|
|
79
|
+
function storedTimes(context: DavReadContext, component: CalendarComponent) {
|
|
80
|
+
const fields = { DTSTART: "start", DTEND: "end", DUE: "due", COMPLETED: "completed",
|
|
81
|
+
CREATED: "created", "LAST-MODIFIED": "lastModified", DTSTAMP: "dtstamp" } as const;
|
|
82
|
+
const times: Partial<Record<(typeof fields)[keyof typeof fields], ReturnType<DavReadContext["ical"]["parseCalendarTime"]>>> = {};
|
|
83
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
84
|
+
const found = component.properties.filter(property => property.name === name);
|
|
85
|
+
if (found.length > 1) throw new Error("时间字段有歧义");
|
|
86
|
+
const property = found[0];
|
|
87
|
+
if (!property) continue;
|
|
88
|
+
const values = property.parameters.VALUE, zones = property.parameters.TZID;
|
|
89
|
+
const type = values?.[0]?.toUpperCase();
|
|
90
|
+
if ((values && values.length !== 1) || (zones && zones.length !== 1) ||
|
|
91
|
+
(type !== undefined && type !== "DATE" && type !== "DATE-TIME")) throw new Error("时间参数无法解释");
|
|
92
|
+
const options: Parameters<DavReadContext["ical"]["parseCalendarTime"]>[1] = {};
|
|
93
|
+
if (type !== undefined) options.valueType = type;
|
|
94
|
+
if (zones) options.tzid = zones[0];
|
|
95
|
+
const time = context.ical.parseCalendarTime(property.rawValue, options);
|
|
96
|
+
if (time.unresolvedReason !== null) throw new Error("时间无法解释");
|
|
97
|
+
times[field] = time;
|
|
98
|
+
}
|
|
99
|
+
return times;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function propertyDetails({ raw: _raw, ...property }: CalendarProperty) { return property; }
|
|
103
|
+
|
|
104
|
+
/** 保留库确认的身份与结构;不把时间失败时的主件伪装成发生项。 */
|
|
105
|
+
function readableComponents(components: CalendarComponent[]) {
|
|
106
|
+
return components.map(component => ({ kind: component.kind, uid: component.uid, recurrenceId: component.recurrenceId,
|
|
107
|
+
properties: component.properties.map(propertyDetails) }));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
type UnresolvedCalendarResource = ReturnType<typeof unresolvedResource> & { components?: ReturnType<typeof readableComponents> };
|
|
111
|
+
|
|
112
|
+
function unresolved(context: DavReadContext, resource: DavResource, rawSource: "get" | "report",
|
|
113
|
+
stage: ReadFailureStage, components?: CalendarComponent[]): UnresolvedCalendarResource {
|
|
114
|
+
const result: UnresolvedCalendarResource = unresolvedResource(resource, rawSource, stage, validation(context, resource.data));
|
|
115
|
+
if (components !== undefined) result.components = readableComponents(components);
|
|
116
|
+
return result;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function eventItem(resource: DavResource, occurrence: ReturnType<DavReadContext["ical"]["expandEvents"]>[number]) {
|
|
120
|
+
return { resourceUrl: resource.url, etag: resource.etag, ...summary(occurrence.component),
|
|
121
|
+
// 展开身份仅是发生时间值;存储选择器是完整逻辑行,两者不可互换。
|
|
122
|
+
recurrenceId: occurrence.recurrenceId, storedRecurrenceId: occurrence.component.recurrenceId,
|
|
123
|
+
start: occurrence.start, end: occurrence.end, startInstant: occurrence.startInstant, endInstant: occurrence.endInstant };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function storedItem(context: DavReadContext, resource: DavResource, component: CalendarComponent) {
|
|
127
|
+
return { resourceUrl: resource.url, etag: resource.etag, ...summary(component),
|
|
128
|
+
recurrenceId: component.recurrenceId, storedRecurrenceId: component.recurrenceId, ...storedTimes(context, component) };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function listCalendar(context: DavReadContext, input: CalendarListInput, kind: CalendarComponentKind) {
|
|
132
|
+
const window = kind === "VEVENT" ? eventWindow(context, input) : undefined;
|
|
133
|
+
// 服务端解释 floating 的时区可能不同;只筛组件,避免时间窗预筛选漏项。
|
|
134
|
+
const resources = await context.client.query(input.collectionUrl, "calendar", { component: kind });
|
|
135
|
+
const events: ReturnType<typeof eventItem>[] = [], stored: ReturnType<typeof storedItem>[] = [];
|
|
136
|
+
const unresolvedResources: UnresolvedCalendarResource[] = [];
|
|
137
|
+
for (const resource of resources) {
|
|
138
|
+
const parsed = readContent(() => context.ical.parseCalendar(resource.data));
|
|
139
|
+
if (!parsed.ok) { unresolvedResources.push(unresolved(context, resource, "report", "parse")); continue; }
|
|
140
|
+
const components = parsed.value.components;
|
|
141
|
+
// 身份由库解析确认;未能解析的资源不会进入此排除分支。
|
|
142
|
+
const candidates = components.filter(component => component.kind === kind && (input.uid === undefined || component.uid === input.uid));
|
|
143
|
+
if (!candidates.length) continue;
|
|
144
|
+
const checked = candidates.some(component => component.properties.some(property => property.name === "STATUS"))
|
|
145
|
+
? validation(context, resource.data) : undefined;
|
|
146
|
+
const relevant = candidates.filter(component => !reliableStatus(component, checked) || matches(component, input, kind));
|
|
147
|
+
if (!relevant.length) continue;
|
|
148
|
+
const projected = readContent(() => {
|
|
149
|
+
for (const component of relevant) {
|
|
150
|
+
if (!reliableStatus(component, checked)) throw new Error("状态无法确认");
|
|
151
|
+
summary(component);
|
|
152
|
+
}
|
|
153
|
+
return window ? [] : relevant.map(component => storedItem(context, resource, component));
|
|
154
|
+
});
|
|
155
|
+
if (!projected.ok) { unresolvedResources.push(unresolved(context, resource, "report", "projection", components)); continue; }
|
|
156
|
+
if (!window) { stored.push(...projected.value); continue; }
|
|
157
|
+
// 必须把整份原文交给库:不拆系列/例外,不在失败后输出该资源的部分发生项。
|
|
158
|
+
const expanded = readContent(() => context.ical.expandEvents(resource.data, window));
|
|
159
|
+
if (!expanded.ok) { unresolvedResources.push(unresolved(context, resource, "report", "expand", components)); continue; }
|
|
160
|
+
const items = readContent(() => expanded.value.filter(occurrence => matches(occurrence.component, input, kind))
|
|
161
|
+
.map(occurrence => eventItem(resource, occurrence)));
|
|
162
|
+
if (!items.ok) { unresolvedResources.push(unresolved(context, resource, "report", "projection", components)); continue; }
|
|
163
|
+
events.push(...items.value);
|
|
164
|
+
}
|
|
165
|
+
const common = { complete: unresolvedResources.length === 0, resourcesComplete: true as const,
|
|
166
|
+
account: input.account, collectionUrl: input.collectionUrl, kind, unresolvedResources };
|
|
167
|
+
if (window) {
|
|
168
|
+
events.sort((left, right) => left.startInstant - right.startInstant);
|
|
169
|
+
return { ...common, expanded: true, ...window, items: events };
|
|
170
|
+
}
|
|
171
|
+
return { ...common, storedComponents: true, items: stored };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export async function getCalendar(context: DavReadContext, input: CalendarGetInput, kind: CalendarComponentKind) {
|
|
175
|
+
if ((input.uid === undefined && input.raw !== true) || (input.recurrenceId !== undefined && input.uid === undefined)) {
|
|
176
|
+
throw new DavToolError("INVALID_INPUT", "普通组件详情必须指定 uid;仅 raw:true 可省略 uid,recurrenceId 不得单独出现");
|
|
177
|
+
}
|
|
178
|
+
const resource = await context.client.get(input.resourceUrl);
|
|
179
|
+
const identity = { account: input.account, resourceUrl: resource.url, etag: resource.etag, resourcesComplete: true as const };
|
|
180
|
+
if (input.uid === undefined) {
|
|
181
|
+
// complete 仅确认整资源取得,不确认格式、组件身份或发生项;此模式完全不依赖解析。
|
|
182
|
+
return { ...identity, complete: true as const, completenessScope: "resource" as const,
|
|
183
|
+
selectorVerified: false as const, selectorStatus: "not-requested" as const,
|
|
184
|
+
raw: resource.data, rawSource: "get" as const };
|
|
185
|
+
}
|
|
186
|
+
const failed = (stage: ReadFailureStage, components?: CalendarComponent[]) => ({
|
|
187
|
+
...identity, ...unresolved(context, resource, "get", stage, components),
|
|
188
|
+
complete: false as const, completenessScope: "component" as const,
|
|
189
|
+
selectorVerified: false as const, selectorStatus: "unverified" as const,
|
|
190
|
+
selectionMessage: "内容未能完整解释,未验证请求的组件选择器;不能据此确认匹配或不存在。",
|
|
191
|
+
requestedSelector: { kind, uid: input.uid, recurrenceId: input.recurrenceId ?? null },
|
|
192
|
+
});
|
|
193
|
+
const parsed = readContent(() => context.ical.parseCalendar(resource.data));
|
|
194
|
+
if (!parsed.ok) return failed("parse");
|
|
195
|
+
const components = parsed.value.components.filter(component => component.kind === kind &&
|
|
196
|
+
component.uid === input.uid && component.recurrenceId === (input.recurrenceId ?? null));
|
|
197
|
+
// 可靠的选择错误不能被原文降级掩盖;检查在字段投影之前,且不在内容 catch 内。
|
|
198
|
+
if (components.length > 1) throw new DavToolError("AMBIGUOUS_TARGET", "资源内存在多个匹配组件,无法唯一选择目标");
|
|
199
|
+
const component = components[0];
|
|
200
|
+
if (!component) throw new DavToolError("NOT_FOUND", "资源内未找到指定的日历组件");
|
|
201
|
+
const projected = readContent(() => {
|
|
202
|
+
rejectRange(component);
|
|
203
|
+
if (!reliableStatus(component, component.properties.some(property => property.name === "STATUS")
|
|
204
|
+
? validation(context, resource.data) : undefined)) throw new Error("状态无法确认");
|
|
205
|
+
if (component.properties.filter(property => property.name === "DESCRIPTION").length > 1) throw new Error("详情字段有歧义");
|
|
206
|
+
return { ...summary(component), recurrenceId: component.recurrenceId, description: component.description,
|
|
207
|
+
...storedTimes(context, component), properties: component.properties.map(propertyDetails),
|
|
208
|
+
alarms: component.alarms.map(alarm => ({ properties: alarm.properties.map(propertyDetails) })) };
|
|
209
|
+
});
|
|
210
|
+
if (!projected.ok) return failed("projection", parsed.value.components);
|
|
211
|
+
const response: typeof projected.value & typeof identity & { complete: true; completenessScope: "component";
|
|
212
|
+
selectorVerified: true; selectorStatus: "verified"; raw?: string; rawSource?: "get" } = {
|
|
213
|
+
...identity, ...projected.value, complete: true, completenessScope: "component", selectorVerified: true, selectorStatus: "verified",
|
|
214
|
+
};
|
|
215
|
+
if (input.raw === true) { response.raw = resource.data; response.rawSource = "get"; }
|
|
216
|
+
return response;
|
|
217
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { DavKind } from "davkit/dav";
|
|
2
|
+
import type { DavAccountConfig } from "./config.ts";
|
|
3
|
+
import { DavToolError, type DavReadContext } from "./types.ts";
|
|
4
|
+
|
|
5
|
+
export function supportsDavNode(version: string): boolean {
|
|
6
|
+
return /^(\d+)\./.test(version) && Number(version.split(".")[0]) >= 24;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** 每次调用独立客户端与取消信号;记录写入确认状态,不缓存密码或自动重试。 */
|
|
10
|
+
export async function withDavAccount<T>(
|
|
11
|
+
config: DavAccountConfig,
|
|
12
|
+
signal: AbortSignal | undefined,
|
|
13
|
+
handler: (context: DavReadContext) => Promise<T>,
|
|
14
|
+
options: { discoveryKind?: DavKind; fetch?: typeof globalThis.fetch } = {},
|
|
15
|
+
): Promise<T> {
|
|
16
|
+
if (!supportsDavNode(process.versions.node))
|
|
17
|
+
throw new DavToolError("DAV_UNAVAILABLE", "DAV 业务调用需要 Node.js 24 或更新版本;其他插件能力不受影响。");
|
|
18
|
+
signal?.throwIfAborted();
|
|
19
|
+
const library = await loadLibrary();
|
|
20
|
+
const base = new URL(config.url);
|
|
21
|
+
// 根地址可能是管理门户,按标准协议入口发现;明确路径则按配置使用,不试探厂商私有路径。
|
|
22
|
+
const entry = options.discoveryKind && base.pathname === "/"
|
|
23
|
+
? new URL(`/.well-known/${options.discoveryKind === "calendar" ? "caldav" : "carddav"}`, base).href
|
|
24
|
+
: config.url;
|
|
25
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
26
|
+
const mutation: { method?: string; resourceUrl?: string; status?: number } = {};
|
|
27
|
+
const writeConfirmed = () => mutation.status !== undefined
|
|
28
|
+
&& (mutation.method === "PUT" ? [200, 201, 204] : [200, 204]).includes(mutation.status);
|
|
29
|
+
const makeClient = (baseUrl: string, observe?: (url: string, response: Response) => void) => new library.dav.DavClient({
|
|
30
|
+
baseUrl, basicAuth: { username: config.user, password: config.password },
|
|
31
|
+
fetch: async (url, init) => {
|
|
32
|
+
const signals = [signal, init?.signal].filter((value): value is AbortSignal => !!value);
|
|
33
|
+
const requestSignal = signals.length ? AbortSignal.any(signals) : undefined;
|
|
34
|
+
const writing = init?.method === "PUT" || init?.method === "DELETE";
|
|
35
|
+
if (writing) {
|
|
36
|
+
requestSignal?.throwIfAborted();
|
|
37
|
+
mutation.method = init.method;
|
|
38
|
+
mutation.resourceUrl = String(url);
|
|
39
|
+
}
|
|
40
|
+
const response = await fetchImpl(url, { ...init, signal: requestSignal, redirect: "manual" });
|
|
41
|
+
if (writing) mutation.status = response.status;
|
|
42
|
+
observe?.(String(url), response);
|
|
43
|
+
return response;
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
const client = makeClient(config.url);
|
|
47
|
+
if (options.discoveryKind) client.discover = async kind => {
|
|
48
|
+
let endpoint = entry;
|
|
49
|
+
for (let redirects = 0; ; redirects++) {
|
|
50
|
+
let next: string | undefined;
|
|
51
|
+
let invalid = false;
|
|
52
|
+
const discovery = makeClient(endpoint, (url, response) => {
|
|
53
|
+
if (![301, 302, 307, 308].includes(response.status)) return;
|
|
54
|
+
const location = response.headers.get("location");
|
|
55
|
+
try {
|
|
56
|
+
const target = location ? new URL(location, url) : undefined;
|
|
57
|
+
if (!target || redirects >= 3 || target.origin !== base.origin || target.username || target.password || target.hash) invalid = true;
|
|
58
|
+
else next = target.href;
|
|
59
|
+
} catch { invalid = true; }
|
|
60
|
+
});
|
|
61
|
+
try { return await discovery.discover(kind); }
|
|
62
|
+
catch (error) {
|
|
63
|
+
if (invalid) throw new DavToolError("DISCOVERY_FAILED", "DAV 发现跳转无效、过多或跨源;未转发认证。");
|
|
64
|
+
if (!next) throw error;
|
|
65
|
+
// 由库重新执行发现,确保相对 href 以新入口解析;资源 GET/REPORT 不跟随跳转。
|
|
66
|
+
endpoint = next;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const context: DavReadContext = { client, ical: library.ical, vcard: library.vcard,
|
|
71
|
+
...(config.timeZone === undefined ? {} : { timeZone: config.timeZone }) };
|
|
72
|
+
try {
|
|
73
|
+
const data = await handler(context);
|
|
74
|
+
// 已确认的写入不因随后取消被降为失败;调用方不做写后回读。
|
|
75
|
+
if (!writeConfirmed()) signal?.throwIfAborted();
|
|
76
|
+
return data;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (error instanceof DavToolError) throw error;
|
|
79
|
+
if (mutation.method && (mutation.status === undefined
|
|
80
|
+
|| (mutation.status >= 200 && mutation.status < 300 && !writeConfirmed())))
|
|
81
|
+
throw new DavToolError("REMOTE_RESULT_UNKNOWN", "写入请求已发出,但远端结果尚未确认;不能假定未生效。请先读取目标资源核对,不会自动重发或补偿。",
|
|
82
|
+
{ ...context.writeIdentity, method: mutation.method, resourceUrl: mutation.resourceUrl });
|
|
83
|
+
if (error instanceof library.dav.DavConflictError)
|
|
84
|
+
throw new DavToolError("CONFLICT", "条件写入发生版本或创建冲突,未自动重试;请重新读取并确认变更。");
|
|
85
|
+
if (error instanceof library.dav.DavError && (error.status !== null || !signal?.aborted)) {
|
|
86
|
+
const code = error.status === 401 || error.status === 403 ? "DAV_AUTH_FAILED"
|
|
87
|
+
: error.status === 404 ? "NOT_FOUND" : "DAV_FAILED";
|
|
88
|
+
const status = error.status === null ? "连接或响应读取失败" : `HTTP ${error.status}`;
|
|
89
|
+
throw new DavToolError(code, `DAV 请求失败(${status}),未自动重试;请核对服务入口、账户与权限。`);
|
|
90
|
+
}
|
|
91
|
+
if (signal?.aborted) throw new DavToolError("ABORTED", "DAV 操作已取消,未发出写入请求。");
|
|
92
|
+
if (error instanceof library.dav.DavProtocolError)
|
|
93
|
+
throw new DavToolError("DAV_PROTOCOL", "服务器未返回有效 DAV 数据;请核对服务入口,不把网页响应视为认证成功。");
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function loadLibrary() {
|
|
99
|
+
try {
|
|
100
|
+
const [dav, ical, vcard] = await Promise.all([import("davkit/dav"), import("davkit/ical"), import("davkit/vcard")]);
|
|
101
|
+
return { dav, ical, vcard };
|
|
102
|
+
} catch {
|
|
103
|
+
throw new DavToolError("DAV_UNAVAILABLE", "DAV 可选依赖不可用;请按正常包管理流程安装包含 optional 依赖的插件,不会自动安装或切换旧 MCP。");
|
|
104
|
+
}
|
|
105
|
+
}
|