@nextclaw/channel-extension-wecom 0.1.1-beta.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NextClaw contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ export { };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/main.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { };
package/dist/main.js ADDED
@@ -0,0 +1,12 @@
1
+ import { WeComChannel } from "./services/wecom-channel.service.js";
2
+ import { startBusChannelExtension, warnNcpEventError } from "@nextclaw/extension-sdk";
3
+ //#region src/main.ts
4
+ await startBusChannelExtension({
5
+ channelId: "wecom",
6
+ createChannel: ({ config, bus }) => new WeComChannel(config, bus),
7
+ onChannelStartError: warnNcpEventError("wecom")
8
+ });
9
+ //#endregion
10
+ export {};
11
+
12
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.js","names":[],"sources":["../src/main.ts"],"sourcesContent":["import type { Config, MessageBus } from \"@nextclaw/core\";\nimport { startBusChannelExtension, warnNcpEventError } from \"@nextclaw/extension-sdk\";\nimport { WeComChannel } from \"./services/wecom-channel.service.js\";\n\nawait startBusChannelExtension<Config[\"channels\"][\"wecom\"], MessageBus>({\n channelId: \"wecom\",\n createChannel: ({ config, bus }) => new WeComChannel(config, bus),\n onChannelStartError: warnNcpEventError(\"wecom\"),\n});\n"],"mappings":";;;AAIA,MAAM,yBAAkE;CACtE,WAAW;CACX,gBAAgB,EAAE,QAAQ,UAAU,IAAI,aAAa,QAAQ,IAAI;CACjE,qBAAqB,kBAAkB,QAAQ;CAChD,CAAC"}
@@ -0,0 +1,238 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { BaseChannel } from "@nextclaw/core";
4
+ import { fetch } from "undici";
5
+ //#region src/services/wecom-channel.service.ts
6
+ const MSG_TYPE_FALLBACK = {
7
+ image: "[image]",
8
+ voice: "[voice]",
9
+ video: "[video]",
10
+ file: "[file]",
11
+ location: "[location]",
12
+ event: "[event]"
13
+ };
14
+ const TOKEN_EXPIRY_BUFFER_MS = 6e4;
15
+ var WeComChannel = class extends BaseChannel {
16
+ name = "wecom";
17
+ server = null;
18
+ accessToken = null;
19
+ tokenExpiry = 0;
20
+ processedIds = [];
21
+ processedSet = /* @__PURE__ */ new Set();
22
+ constructor(config, bus) {
23
+ super(config, bus);
24
+ }
25
+ start = async () => {
26
+ if (!this.config.corpId || !this.config.agentId || !this.config.secret || !this.config.token) throw new Error("WeCom corpId/agentId/secret/token not configured");
27
+ this.running = true;
28
+ await new Promise((resolve, reject) => {
29
+ this.server = createServer((req, res) => {
30
+ this.handleCallbackRequest(req, res);
31
+ });
32
+ this.server.once("error", reject);
33
+ this.server.listen(this.config.callbackPort, () => {
34
+ this.server?.off("error", reject);
35
+ resolve();
36
+ });
37
+ });
38
+ };
39
+ stop = async () => {
40
+ this.running = false;
41
+ if (!this.server) return;
42
+ await new Promise((resolve) => {
43
+ this.server?.close(() => resolve());
44
+ });
45
+ this.server = null;
46
+ };
47
+ send = async (msg) => {
48
+ const receiver = msg.chatId?.trim();
49
+ if (!receiver) return;
50
+ const content = normalizeOutboundContent(msg);
51
+ if (!content) return;
52
+ const accessToken = await this.getAccessToken();
53
+ const sendUrl = `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${encodeURIComponent(accessToken)}`;
54
+ const agentIdNumber = Number(this.config.agentId);
55
+ const payload = {
56
+ touser: receiver,
57
+ msgtype: "text",
58
+ agentid: Number.isFinite(agentIdNumber) ? agentIdNumber : this.config.agentId,
59
+ text: { content },
60
+ safe: 0
61
+ };
62
+ const response = await fetch(sendUrl, {
63
+ method: "POST",
64
+ headers: { "content-type": "application/json" },
65
+ body: JSON.stringify(payload)
66
+ });
67
+ if (!response.ok) throw new Error(`WeCom send failed: HTTP ${response.status}`);
68
+ const body = await response.json();
69
+ const errcode = Number(body.errcode ?? -1);
70
+ if (!Number.isFinite(errcode) || errcode !== 0) {
71
+ const errmsg = typeof body.errmsg === "string" ? body.errmsg : "unknown error";
72
+ throw new Error(`WeCom send failed: ${errcode} ${errmsg}`);
73
+ }
74
+ };
75
+ handleCallbackRequest = async (req, res) => {
76
+ const callbackPath = normalizeCallbackPath(this.config.callbackPath);
77
+ const requestUrl = new URL(req.url ?? "/", `http://${req.headers.host ?? "127.0.0.1"}`);
78
+ if (requestUrl.pathname !== callbackPath) {
79
+ res.statusCode = 404;
80
+ res.end("not found");
81
+ return;
82
+ }
83
+ const method = (req.method ?? "GET").toUpperCase();
84
+ if (method === "GET") {
85
+ this.handleVerificationRequest(requestUrl, res);
86
+ return;
87
+ }
88
+ if (method === "POST") {
89
+ await this.handleInboundMessageRequest(req, requestUrl, res);
90
+ return;
91
+ }
92
+ res.statusCode = 405;
93
+ res.end("method not allowed");
94
+ };
95
+ handleVerificationRequest = (requestUrl, res) => {
96
+ const timestamp = requestUrl.searchParams.get("timestamp") ?? "";
97
+ const nonce = requestUrl.searchParams.get("nonce") ?? "";
98
+ const echostr = requestUrl.searchParams.get("echostr") ?? "";
99
+ const signature = requestUrl.searchParams.get("msg_signature") ?? requestUrl.searchParams.get("signature") ?? "";
100
+ if (!timestamp || !nonce || !echostr || !signature) {
101
+ res.statusCode = 400;
102
+ res.end("invalid verification payload");
103
+ return;
104
+ }
105
+ if (!this.verifySignature(timestamp, nonce, signature)) {
106
+ res.statusCode = 401;
107
+ res.end("signature mismatch");
108
+ return;
109
+ }
110
+ res.statusCode = 200;
111
+ res.setHeader("content-type", "text/plain; charset=utf-8");
112
+ res.end(echostr);
113
+ };
114
+ handleInboundMessageRequest = async (req, requestUrl, res) => {
115
+ const timestamp = requestUrl.searchParams.get("timestamp") ?? "";
116
+ const nonce = requestUrl.searchParams.get("nonce") ?? "";
117
+ const signature = requestUrl.searchParams.get("msg_signature") ?? requestUrl.searchParams.get("signature") ?? "";
118
+ if (!timestamp || !nonce || !signature || !this.verifySignature(timestamp, nonce, signature)) {
119
+ res.statusCode = 401;
120
+ res.end("signature mismatch");
121
+ return;
122
+ }
123
+ const rawBody = await readBody(req);
124
+ if (!rawBody.trim()) {
125
+ this.respondSuccess(res);
126
+ return;
127
+ }
128
+ if (extractXmlField(rawBody, "Encrypt")) {
129
+ this.respondSuccess(res);
130
+ return;
131
+ }
132
+ const senderId = extractXmlField(rawBody, "FromUserName");
133
+ if (!senderId || !this.isAllowed(senderId)) {
134
+ this.respondSuccess(res);
135
+ return;
136
+ }
137
+ const msgType = extractXmlField(rawBody, "MsgType") || "text";
138
+ const msgId = extractXmlField(rawBody, "MsgId") || buildSyntheticMessageId(rawBody, senderId, msgType);
139
+ if (this.isDuplicate(msgId)) {
140
+ this.respondSuccess(res);
141
+ return;
142
+ }
143
+ const content = extractXmlField(rawBody, "Content")?.trim() || MSG_TYPE_FALLBACK[msgType.toLowerCase()] || "[unsupported message]";
144
+ await this.handleMessage({
145
+ senderId,
146
+ chatId: senderId,
147
+ content,
148
+ attachments: [],
149
+ metadata: {
150
+ message_id: msgId,
151
+ wecom: {
152
+ msgType,
153
+ toUserName: extractXmlField(rawBody, "ToUserName"),
154
+ agentId: extractXmlField(rawBody, "AgentID"),
155
+ createTime: extractXmlField(rawBody, "CreateTime")
156
+ }
157
+ }
158
+ });
159
+ this.respondSuccess(res);
160
+ };
161
+ respondSuccess = (res) => {
162
+ res.statusCode = 200;
163
+ res.setHeader("content-type", "text/plain; charset=utf-8");
164
+ res.end("success");
165
+ };
166
+ verifySignature = (timestamp, nonce, signature) => {
167
+ return createHash("sha1").update([
168
+ this.config.token,
169
+ timestamp,
170
+ nonce
171
+ ].sort().join("")).digest("hex") === signature;
172
+ };
173
+ getAccessToken = async () => {
174
+ if (this.accessToken && Date.now() < this.tokenExpiry) return this.accessToken;
175
+ const response = await fetch(`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${encodeURIComponent(this.config.corpId)}&corpsecret=${encodeURIComponent(this.config.secret)}`, { method: "GET" });
176
+ if (!response.ok) throw new Error(`WeCom gettoken failed: HTTP ${response.status}`);
177
+ const body = await response.json();
178
+ const errcode = Number(body.errcode ?? -1);
179
+ if (!Number.isFinite(errcode) || errcode !== 0) {
180
+ const errmsg = typeof body.errmsg === "string" ? body.errmsg : "unknown error";
181
+ throw new Error(`WeCom gettoken failed: ${errcode} ${errmsg}`);
182
+ }
183
+ const accessToken = typeof body.access_token === "string" ? body.access_token : "";
184
+ const expiresIn = Number(body.expires_in ?? 7200);
185
+ if (!accessToken) throw new Error("WeCom gettoken failed: missing access_token");
186
+ this.accessToken = accessToken;
187
+ this.tokenExpiry = Date.now() + Math.max(0, expiresIn * 1e3 - TOKEN_EXPIRY_BUFFER_MS);
188
+ return accessToken;
189
+ };
190
+ isDuplicate = (messageId) => {
191
+ if (this.processedSet.has(messageId)) return true;
192
+ this.processedSet.add(messageId);
193
+ this.processedIds.push(messageId);
194
+ if (this.processedIds.length > 1e3) {
195
+ const removed = this.processedIds.splice(0, 500);
196
+ for (const id of removed) this.processedSet.delete(id);
197
+ }
198
+ return false;
199
+ };
200
+ };
201
+ function normalizeCallbackPath(path) {
202
+ if (!path) return "/wecom/callback";
203
+ return path.startsWith("/") ? path : `/${path}`;
204
+ }
205
+ function buildSyntheticMessageId(rawBody, senderId, msgType) {
206
+ return createHash("sha1").update(`${senderId}:${msgType}:${rawBody}`).digest("hex");
207
+ }
208
+ function extractXmlField(xml, field) {
209
+ const cdataPattern = new RegExp(`<${field}><!\\[CDATA\\[(.*?)\\]\\]><\\/${field}>`, "s");
210
+ const cdataMatch = xml.match(cdataPattern);
211
+ if (cdataMatch?.[1]) return cdataMatch[1].trim();
212
+ const textPattern = new RegExp(`<${field}>(.*?)<\\/${field}>`, "s");
213
+ return xml.match(textPattern)?.[1]?.trim() ?? "";
214
+ }
215
+ async function readBody(req) {
216
+ const chunks = [];
217
+ return await new Promise((resolve, reject) => {
218
+ req.on("data", (chunk) => {
219
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
220
+ });
221
+ req.on("error", reject);
222
+ req.on("end", () => {
223
+ resolve(Buffer.concat(chunks).toString("utf8"));
224
+ });
225
+ });
226
+ }
227
+ function normalizeOutboundContent(msg) {
228
+ const segments = [];
229
+ if (typeof msg.content === "string" && msg.content.trim()) segments.push(msg.content.trim());
230
+ if (Array.isArray(msg.media)) {
231
+ for (const item of msg.media) if (typeof item === "string" && item.trim()) segments.push(item.trim());
232
+ }
233
+ return segments.join("\n").trim();
234
+ }
235
+ //#endregion
236
+ export { WeComChannel };
237
+
238
+ //# sourceMappingURL=wecom-channel.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wecom-channel.service.js","names":[],"sources":["../../src/services/wecom-channel.service.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { BaseChannel, type Config, type MessageBus, type OutboundMessage } from \"@nextclaw/core\";\nimport { fetch } from \"undici\";\nconst MSG_TYPE_FALLBACK: Record<string, string> = {\n image: \"[image]\",\n voice: \"[voice]\",\n video: \"[video]\",\n file: \"[file]\",\n location: \"[location]\",\n event: \"[event]\"\n};\nconst TOKEN_EXPIRY_BUFFER_MS = 60000;\nexport class WeComChannel extends BaseChannel<Config[\"channels\"][\"wecom\"]> {\n name = \"wecom\";\n private server: Server | null = null;\n private accessToken: string | null = null;\n private tokenExpiry = 0;\n private processedIds: string[] = [];\n private processedSet: Set<string> = new Set();\n constructor(config: Config[\"channels\"][\"wecom\"], bus: MessageBus) {\n super(config, bus);\n }\n start = async (): Promise<void> => {\n if (!this.config.corpId || !this.config.agentId || !this.config.secret || !this.config.token) {\n throw new Error(\"WeCom corpId/agentId/secret/token not configured\");\n }\n this.running = true;\n await new Promise<void>((resolve, reject) => {\n this.server = createServer((req, res) => {\n void this.handleCallbackRequest(req, res);\n });\n this.server.once(\"error\", reject);\n this.server.listen(this.config.callbackPort, () => {\n this.server?.off(\"error\", reject);\n resolve();\n });\n });\n };\n stop = async (): Promise<void> => {\n this.running = false;\n if (!this.server) {\n return;\n }\n await new Promise<void>((resolve) => {\n this.server?.close(() => resolve());\n });\n this.server = null;\n };\n send = async (msg: OutboundMessage): Promise<void> => {\n const receiver = msg.chatId?.trim();\n if (!receiver) {\n return;\n }\n const content = normalizeOutboundContent(msg);\n if (!content) {\n return;\n }\n const accessToken = await this.getAccessToken();\n const sendUrl = `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${encodeURIComponent(accessToken)}`;\n const agentIdNumber = Number(this.config.agentId);\n const payload = {\n touser: receiver,\n msgtype: \"text\",\n agentid: Number.isFinite(agentIdNumber) ? agentIdNumber : this.config.agentId,\n text: {\n content\n },\n safe: 0\n };\n const response = await fetch(sendUrl, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\"\n },\n body: JSON.stringify(payload)\n });\n if (!response.ok) {\n throw new Error(`WeCom send failed: HTTP ${response.status}`);\n }\n const body = (await response.json()) as Record<string, unknown>;\n const errcode = Number(body.errcode ?? -1);\n if (!Number.isFinite(errcode) || errcode !== 0) {\n const errmsg = typeof body.errmsg === \"string\" ? body.errmsg : \"unknown error\";\n throw new Error(`WeCom send failed: ${errcode} ${errmsg}`);\n }\n };\n private handleCallbackRequest = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const callbackPath = normalizeCallbackPath(this.config.callbackPath);\n const requestUrl = new URL(req.url ?? \"/\", `http://${req.headers.host ?? \"127.0.0.1\"}`);\n if (requestUrl.pathname !== callbackPath) {\n res.statusCode = 404;\n res.end(\"not found\");\n return;\n }\n const method = (req.method ?? \"GET\").toUpperCase();\n if (method === \"GET\") {\n this.handleVerificationRequest(requestUrl, res);\n return;\n }\n if (method === \"POST\") {\n await this.handleInboundMessageRequest(req, requestUrl, res);\n return;\n }\n res.statusCode = 405;\n res.end(\"method not allowed\");\n };\n private handleVerificationRequest = (requestUrl: URL, res: ServerResponse): void => {\n const timestamp = requestUrl.searchParams.get(\"timestamp\") ?? \"\";\n const nonce = requestUrl.searchParams.get(\"nonce\") ?? \"\";\n const echostr = requestUrl.searchParams.get(\"echostr\") ?? \"\";\n const signature = requestUrl.searchParams.get(\"msg_signature\") ?? requestUrl.searchParams.get(\"signature\") ?? \"\";\n if (!timestamp || !nonce || !echostr || !signature) {\n res.statusCode = 400;\n res.end(\"invalid verification payload\");\n return;\n }\n if (!this.verifySignature(timestamp, nonce, signature)) {\n res.statusCode = 401;\n res.end(\"signature mismatch\");\n return;\n }\n res.statusCode = 200;\n res.setHeader(\"content-type\", \"text/plain; charset=utf-8\");\n res.end(echostr);\n };\n private handleInboundMessageRequest = async (req: IncomingMessage, requestUrl: URL, res: ServerResponse): Promise<void> => {\n const timestamp = requestUrl.searchParams.get(\"timestamp\") ?? \"\";\n const nonce = requestUrl.searchParams.get(\"nonce\") ?? \"\";\n const signature = requestUrl.searchParams.get(\"msg_signature\") ?? requestUrl.searchParams.get(\"signature\") ?? \"\";\n if (!timestamp || !nonce || !signature || !this.verifySignature(timestamp, nonce, signature)) {\n res.statusCode = 401;\n res.end(\"signature mismatch\");\n return;\n }\n const rawBody = await readBody(req);\n if (!rawBody.trim()) {\n this.respondSuccess(res);\n return;\n }\n if (extractXmlField(rawBody, \"Encrypt\")) {\n this.respondSuccess(res);\n return;\n }\n const senderId = extractXmlField(rawBody, \"FromUserName\");\n if (!senderId || !this.isAllowed(senderId)) {\n this.respondSuccess(res);\n return;\n }\n const msgType = extractXmlField(rawBody, \"MsgType\") || \"text\";\n const msgId = extractXmlField(rawBody, \"MsgId\") || buildSyntheticMessageId(rawBody, senderId, msgType);\n if (this.isDuplicate(msgId)) {\n this.respondSuccess(res);\n return;\n }\n const content = extractXmlField(rawBody, \"Content\")?.trim() || MSG_TYPE_FALLBACK[msgType.toLowerCase()] || \"[unsupported message]\";\n await this.handleMessage({\n senderId,\n chatId: senderId,\n content,\n attachments: [],\n metadata: {\n message_id: msgId,\n wecom: {\n msgType,\n toUserName: extractXmlField(rawBody, \"ToUserName\"),\n agentId: extractXmlField(rawBody, \"AgentID\"),\n createTime: extractXmlField(rawBody, \"CreateTime\")\n }\n }\n });\n this.respondSuccess(res);\n };\n private respondSuccess = (res: ServerResponse): void => {\n res.statusCode = 200;\n res.setHeader(\"content-type\", \"text/plain; charset=utf-8\");\n res.end(\"success\");\n };\n private verifySignature = (timestamp: string, nonce: string, signature: string): boolean => {\n const expected = createHash(\"sha1\")\n .update([this.config.token, timestamp, nonce].sort().join(\"\"))\n .digest(\"hex\");\n return expected === signature;\n };\n private getAccessToken = async (): Promise<string> => {\n if (this.accessToken && Date.now() < this.tokenExpiry) {\n return this.accessToken;\n }\n const tokenUrl = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${encodeURIComponent(this.config.corpId)}` +\n `&corpsecret=${encodeURIComponent(this.config.secret)}`;\n const response = await fetch(tokenUrl, { method: \"GET\" });\n if (!response.ok) {\n throw new Error(`WeCom gettoken failed: HTTP ${response.status}`);\n }\n const body = (await response.json()) as Record<string, unknown>;\n const errcode = Number(body.errcode ?? -1);\n if (!Number.isFinite(errcode) || errcode !== 0) {\n const errmsg = typeof body.errmsg === \"string\" ? body.errmsg : \"unknown error\";\n throw new Error(`WeCom gettoken failed: ${errcode} ${errmsg}`);\n }\n const accessToken = typeof body.access_token === \"string\" ? body.access_token : \"\";\n const expiresIn = Number(body.expires_in ?? 7200);\n if (!accessToken) {\n throw new Error(\"WeCom gettoken failed: missing access_token\");\n }\n this.accessToken = accessToken;\n this.tokenExpiry = Date.now() + Math.max(0, expiresIn * 1000 - TOKEN_EXPIRY_BUFFER_MS);\n return accessToken;\n };\n private isDuplicate = (messageId: string): boolean => {\n if (this.processedSet.has(messageId)) {\n return true;\n }\n this.processedSet.add(messageId);\n this.processedIds.push(messageId);\n if (this.processedIds.length > 1000) {\n const removed = this.processedIds.splice(0, 500);\n for (const id of removed) {\n this.processedSet.delete(id);\n }\n }\n return false;\n };\n}\nfunction normalizeCallbackPath(path: string): string {\n if (!path) {\n return \"/wecom/callback\";\n }\n return path.startsWith(\"/\") ? path : `/${path}`;\n}\nfunction buildSyntheticMessageId(rawBody: string, senderId: string, msgType: string): string {\n return createHash(\"sha1\").update(`${senderId}:${msgType}:${rawBody}`).digest(\"hex\");\n}\nfunction extractXmlField(xml: string, field: string): string {\n const cdataPattern = new RegExp(`<${field}><!\\\\[CDATA\\\\[(.*?)\\\\]\\\\]><\\\\/${field}>`, \"s\");\n const cdataMatch = xml.match(cdataPattern);\n if (cdataMatch?.[1]) {\n return cdataMatch[1].trim();\n }\n const textPattern = new RegExp(`<${field}>(.*?)<\\\\/${field}>`, \"s\");\n const textMatch = xml.match(textPattern);\n return textMatch?.[1]?.trim() ?? \"\";\n}\nasync function readBody(req: IncomingMessage): Promise<string> {\n const chunks: Buffer[] = [];\n return await new Promise<string>((resolve, reject) => {\n req.on(\"data\", (chunk) => {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n });\n req.on(\"error\", reject);\n req.on(\"end\", () => {\n resolve(Buffer.concat(chunks).toString(\"utf8\"));\n });\n });\n}\nfunction normalizeOutboundContent(msg: OutboundMessage): string {\n const segments: string[] = [];\n if (typeof msg.content === \"string\" && msg.content.trim()) {\n segments.push(msg.content.trim());\n }\n if (Array.isArray(msg.media)) {\n for (const item of msg.media) {\n if (typeof item === \"string\" && item.trim()) {\n segments.push(item.trim());\n }\n }\n }\n return segments.join(\"\\n\").trim();\n}\n"],"mappings":";;;;;AAIA,MAAM,oBAA4C;CAC9C,OAAO;CACP,OAAO;CACP,OAAO;CACP,MAAM;CACN,UAAU;CACV,OAAO;CACV;AACD,MAAM,yBAAyB;AAC/B,IAAa,eAAb,cAAkC,YAAyC;CACvE,OAAO;CACP,SAAgC;CAChC,cAAqC;CACrC,cAAsB;CACtB,eAAiC,EAAE;CACnC,+BAAoC,IAAI,KAAK;CAC7C,YAAY,QAAqC,KAAiB;AAC9D,QAAM,QAAQ,IAAI;;CAEtB,QAAQ,YAA2B;AAC/B,MAAI,CAAC,KAAK,OAAO,UAAU,CAAC,KAAK,OAAO,WAAW,CAAC,KAAK,OAAO,UAAU,CAAC,KAAK,OAAO,MACnF,OAAM,IAAI,MAAM,mDAAmD;AAEvE,OAAK,UAAU;AACf,QAAM,IAAI,SAAe,SAAS,WAAW;AACzC,QAAK,SAAS,cAAc,KAAK,QAAQ;AAChC,SAAK,sBAAsB,KAAK,IAAI;KAC3C;AACF,QAAK,OAAO,KAAK,SAAS,OAAO;AACjC,QAAK,OAAO,OAAO,KAAK,OAAO,oBAAoB;AAC/C,SAAK,QAAQ,IAAI,SAAS,OAAO;AACjC,aAAS;KACX;IACJ;;CAEN,OAAO,YAA2B;AAC9B,OAAK,UAAU;AACf,MAAI,CAAC,KAAK,OACN;AAEJ,QAAM,IAAI,SAAe,YAAY;AACjC,QAAK,QAAQ,YAAY,S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,MAAM,YAAY,MAAM,IAAI,IAAI;AAEnE,QADkB,IAAI,MAAM,YAAY,GACrB,IAAI,MAAM,IAAI;;AAErC,eAAe,SAAS,KAAuC;CAC3D,MAAM,SAAmB,EAAE;AAC3B,QAAO,MAAM,IAAI,SAAiB,SAAS,WAAW;AAClD,MAAI,GAAG,SAAS,UAAU;AACtB,UAAO,KAAK,OAAO,SAAS,MAAM,GAAG,QAAQ,OAAO,KAAK,MAAM,CAAC;IAClE;AACF,MAAI,GAAG,SAAS,OAAO;AACvB,MAAI,GAAG,aAAa;AAChB,WAAQ,OAAO,OAAO,OAAO,CAAC,SAAS,OAAO,CAAC;IACjD;GACJ;;AAEN,SAAS,yBAAyB,KAA8B;CAC5D,MAAM,WAAqB,EAAE;AAC7B,KAAI,OAAO,IAAI,YAAY,YAAY,IAAI,QAAQ,MAAM,CACrD,UAAS,KAAK,IAAI,QAAQ,MAAM,CAAC;AAErC,KAAI,MAAM,QAAQ,IAAI,MAAM;OACnB,MAAM,QAAQ,IAAI,MACnB,KAAI,OAAO,SAAS,YAAY,KAAK,MAAM,CACvC,UAAS,KAAK,KAAK,MAAM,CAAC;;AAItC,QAAO,SAAS,KAAK,KAAK,CAAC,MAAM"}
@@ -0,0 +1,36 @@
1
+ {
2
+ "id": "nextclaw-channel-extension-wecom",
3
+ "name": "NextClaw WeCom Channel Extension",
4
+ "version": "0.1.0",
5
+ "server": {
6
+ "type": "stdio",
7
+ "command": "node",
8
+ "args": ["dist/main.js"]
9
+ },
10
+ "contributes": {
11
+ "channels": [
12
+ {
13
+ "id": "wecom",
14
+ "name": "WeCom",
15
+ "description": "WeCom enterprise messaging channel",
16
+ "configSchema": {
17
+ "type": "object",
18
+ "additionalProperties": true,
19
+ "properties": {
20
+ "enabled": { "type": "boolean" },
21
+ "corpId": { "type": "string" },
22
+ "agentId": { "type": "string" },
23
+ "secret": { "type": "string" },
24
+ "token": { "type": "string" },
25
+ "callbackPort": { "type": "number" },
26
+ "callbackPath": { "type": "string" },
27
+ "allowFrom": {
28
+ "type": "array",
29
+ "items": { "type": "string" }
30
+ }
31
+ }
32
+ }
33
+ }
34
+ ]
35
+ }
36
+ }
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@nextclaw/channel-extension-wecom",
3
+ "version": "0.1.1-beta.0",
4
+ "private": false,
5
+ "description": "NextClaw WeCom channel extension process.",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "development": "./src/index.ts",
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "nextclaw.extension.json"
18
+ ],
19
+ "dependencies": {
20
+ "undici": "^6.21.0",
21
+ "@nextclaw/core": "0.12.25-beta.0",
22
+ "@nextclaw/extension-sdk": "0.1.12-beta.0"
23
+ },
24
+ "devDependencies": {
25
+ "@types/node": "^20.17.6",
26
+ "tsx": "^4.19.2",
27
+ "typescript": "^5.6.3"
28
+ },
29
+ "scripts": {
30
+ "build": "tsdown src/index.ts src/main.ts --dts.sourcemap --clean --target es2022 --no-fixedExtension --unbundle",
31
+ "lint": "eslint src --max-warnings=0",
32
+ "tsc": "tsc -p tsconfig.json"
33
+ }
34
+ }