@openclaw-china/wecom 0.1.20 → 0.1.22

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/dist/index.js CHANGED
@@ -1,12 +1,174 @@
1
- import crypto from 'crypto';
2
- import * as path from 'path';
1
+ import * as path3 from 'path';
2
+ import path3__default, { join } from 'path';
3
3
  import * as fsPromises from 'fs/promises';
4
+ import { access } from 'fs/promises';
5
+ import crypto, { randomBytes } from 'crypto';
6
+ import * as fs3 from 'fs';
7
+ import { promises, existsSync } from 'fs';
8
+ import * as os2 from 'os';
9
+ import { homedir } from 'os';
10
+ import { fileURLToPath } from 'url';
11
+ import N2, { stdout, stdin } from 'process';
12
+ import ot from 'readline';
13
+ import 'tty';
14
+ import 'util';
4
15
 
16
+ var __create = Object.create;
5
17
  var __defProp = Object.defineProperty;
18
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
19
+ var __getOwnPropNames = Object.getOwnPropertyNames;
20
+ var __getProtoOf = Object.getPrototypeOf;
21
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
22
+ var __commonJS = (cb, mod) => function __require() {
23
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
24
+ };
6
25
  var __export = (target, all) => {
7
26
  for (var name in all)
8
27
  __defProp(target, name, { get: all[name], enumerable: true });
9
28
  };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
+ // If the importer is in node compatibility mode or this is not an ESM
39
+ // file that has been converted to a CommonJS file using a Babel-
40
+ // compatible transform (i.e. "__esModule" has not been set), then set
41
+ // "default" to the CommonJS "module.exports" for node compatibility.
42
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
43
+ mod
44
+ ));
45
+
46
+ // ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
47
+ var require_picocolors = __commonJS({
48
+ "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports$1, module) {
49
+ var p = process || {};
50
+ var argv = p.argv || [];
51
+ var env = p.env || {};
52
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
53
+ var formatter = (open, close, replace = open) => (input2) => {
54
+ let string = "" + input2, index = string.indexOf(close, open.length);
55
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
56
+ };
57
+ var replaceClose = (string, close, replace, index) => {
58
+ let result = "", cursor = 0;
59
+ do {
60
+ result += string.substring(cursor, index) + replace;
61
+ cursor = index + close.length;
62
+ index = string.indexOf(close, cursor);
63
+ } while (~index);
64
+ return result + string.substring(cursor);
65
+ };
66
+ var createColors = (enabled = isColorSupported) => {
67
+ let f = enabled ? formatter : () => String;
68
+ return {
69
+ isColorSupported: enabled,
70
+ reset: f("\x1B[0m", "\x1B[0m"),
71
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
72
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
73
+ italic: f("\x1B[3m", "\x1B[23m"),
74
+ underline: f("\x1B[4m", "\x1B[24m"),
75
+ inverse: f("\x1B[7m", "\x1B[27m"),
76
+ hidden: f("\x1B[8m", "\x1B[28m"),
77
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
78
+ black: f("\x1B[30m", "\x1B[39m"),
79
+ red: f("\x1B[31m", "\x1B[39m"),
80
+ green: f("\x1B[32m", "\x1B[39m"),
81
+ yellow: f("\x1B[33m", "\x1B[39m"),
82
+ blue: f("\x1B[34m", "\x1B[39m"),
83
+ magenta: f("\x1B[35m", "\x1B[39m"),
84
+ cyan: f("\x1B[36m", "\x1B[39m"),
85
+ white: f("\x1B[37m", "\x1B[39m"),
86
+ gray: f("\x1B[90m", "\x1B[39m"),
87
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
88
+ bgRed: f("\x1B[41m", "\x1B[49m"),
89
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
90
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
91
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
92
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
93
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
94
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
95
+ blackBright: f("\x1B[90m", "\x1B[39m"),
96
+ redBright: f("\x1B[91m", "\x1B[39m"),
97
+ greenBright: f("\x1B[92m", "\x1B[39m"),
98
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
99
+ blueBright: f("\x1B[94m", "\x1B[39m"),
100
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
101
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
102
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
103
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
104
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
105
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
106
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
107
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
108
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
109
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
110
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
111
+ };
112
+ };
113
+ module.exports = createColors();
114
+ module.exports.createColors = createColors;
115
+ }
116
+ });
117
+
118
+ // ../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
119
+ var require_src = __commonJS({
120
+ "../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports$1, module) {
121
+ var ESC = "\x1B";
122
+ var CSI = `${ESC}[`;
123
+ var beep = "\x07";
124
+ var cursor = {
125
+ to(x3, y2) {
126
+ if (!y2) return `${CSI}${x3 + 1}G`;
127
+ return `${CSI}${y2 + 1};${x3 + 1}H`;
128
+ },
129
+ move(x3, y2) {
130
+ let ret = "";
131
+ if (x3 < 0) ret += `${CSI}${-x3}D`;
132
+ else if (x3 > 0) ret += `${CSI}${x3}C`;
133
+ if (y2 < 0) ret += `${CSI}${-y2}A`;
134
+ else if (y2 > 0) ret += `${CSI}${y2}B`;
135
+ return ret;
136
+ },
137
+ up: (count = 1) => `${CSI}${count}A`,
138
+ down: (count = 1) => `${CSI}${count}B`,
139
+ forward: (count = 1) => `${CSI}${count}C`,
140
+ backward: (count = 1) => `${CSI}${count}D`,
141
+ nextLine: (count = 1) => `${CSI}E`.repeat(count),
142
+ prevLine: (count = 1) => `${CSI}F`.repeat(count),
143
+ left: `${CSI}G`,
144
+ hide: `${CSI}?25l`,
145
+ show: `${CSI}?25h`,
146
+ save: `${ESC}7`,
147
+ restore: `${ESC}8`
148
+ };
149
+ var scroll = {
150
+ up: (count = 1) => `${CSI}S`.repeat(count),
151
+ down: (count = 1) => `${CSI}T`.repeat(count)
152
+ };
153
+ var erase = {
154
+ screen: `${CSI}2J`,
155
+ up: (count = 1) => `${CSI}1J`.repeat(count),
156
+ down: (count = 1) => `${CSI}J`.repeat(count),
157
+ line: `${CSI}2K`,
158
+ lineEnd: `${CSI}K`,
159
+ lineStart: `${CSI}1K`,
160
+ lines(count) {
161
+ let clear = "";
162
+ for (let i = 0; i < count; i++)
163
+ clear += this.line + (i < count - 1 ? cursor.up() : "");
164
+ if (count)
165
+ clear += cursor.left;
166
+ return clear;
167
+ }
168
+ };
169
+ module.exports = { cursor, scroll, erase, beep };
170
+ }
171
+ });
10
172
 
11
173
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
12
174
  var external_exports = {};
@@ -123,7 +285,7 @@ __export(external_exports, {
123
285
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
124
286
  var util;
125
287
  (function(util2) {
126
- util2.assertEqual = (_) => {
288
+ util2.assertEqual = (_2) => {
127
289
  };
128
290
  function assertIs(_arg) {
129
291
  }
@@ -140,16 +302,16 @@ var util;
140
302
  return obj;
141
303
  };
142
304
  util2.getValidEnumValues = (obj) => {
143
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
305
+ const validKeys = util2.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number");
144
306
  const filtered = {};
145
- for (const k of validKeys) {
146
- filtered[k] = obj[k];
307
+ for (const k2 of validKeys) {
308
+ filtered[k2] = obj[k2];
147
309
  }
148
310
  return util2.objectValues(filtered);
149
311
  };
150
312
  util2.objectValues = (obj) => {
151
- return util2.objectKeys(obj).map(function(e) {
152
- return obj[e];
313
+ return util2.objectKeys(obj).map(function(e2) {
314
+ return obj[e2];
153
315
  });
154
316
  };
155
317
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
@@ -173,7 +335,7 @@ var util;
173
335
  return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
174
336
  }
175
337
  util2.joinValues = joinValues;
176
- util2.jsonStringifyReplacer = (_, value) => {
338
+ util2.jsonStringifyReplacer = (_2, value) => {
177
339
  if (typeof value === "bigint") {
178
340
  return value.toString();
179
341
  }
@@ -486,8 +648,8 @@ function getErrorMap() {
486
648
 
487
649
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
488
650
  var makeIssue = (params) => {
489
- const { data, path: path2, errorMaps, issueData } = params;
490
- const fullPath = [...path2, ...issueData.path || []];
651
+ const { data, path: path5, errorMaps, issueData } = params;
652
+ const fullPath = [...path5, ...issueData.path || []];
491
653
  const fullIssue = {
492
654
  ...issueData,
493
655
  path: fullPath
@@ -526,7 +688,7 @@ function addIssueToContext(ctx, issueData) {
526
688
  // then global override map
527
689
  overrideMap === en_default ? void 0 : en_default
528
690
  // then global default map
529
- ].filter((x) => !!x)
691
+ ].filter((x3) => !!x3)
530
692
  });
531
693
  ctx.common.issues.push(issue);
532
694
  }
@@ -589,10 +751,10 @@ var INVALID = Object.freeze({
589
751
  });
590
752
  var DIRTY = (value) => ({ status: "dirty", value });
591
753
  var OK = (value) => ({ status: "valid", value });
592
- var isAborted = (x) => x.status === "aborted";
593
- var isDirty = (x) => x.status === "dirty";
594
- var isValid = (x) => x.status === "valid";
595
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
754
+ var isAborted = (x3) => x3.status === "aborted";
755
+ var isDirty = (x3) => x3.status === "dirty";
756
+ var isValid = (x3) => x3.status === "valid";
757
+ var isAsync = (x3) => typeof Promise !== "undefined" && x3 instanceof Promise;
596
758
 
597
759
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
598
760
  var errorUtil;
@@ -603,11 +765,11 @@ var errorUtil;
603
765
 
604
766
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
605
767
  var ParseInputLazyPath = class {
606
- constructor(parent, value, path2, key) {
768
+ constructor(parent, value, path5, key) {
607
769
  this._cachedPath = [];
608
770
  this.parent = parent;
609
771
  this.data = value;
610
- this._path = path2;
772
+ this._path = path5;
611
773
  this._key = key;
612
774
  }
613
775
  get path() {
@@ -667,41 +829,41 @@ var ZodType = class {
667
829
  get description() {
668
830
  return this._def.description;
669
831
  }
670
- _getType(input) {
671
- return getParsedType(input.data);
832
+ _getType(input2) {
833
+ return getParsedType(input2.data);
672
834
  }
673
- _getOrReturnCtx(input, ctx) {
835
+ _getOrReturnCtx(input2, ctx) {
674
836
  return ctx || {
675
- common: input.parent.common,
676
- data: input.data,
677
- parsedType: getParsedType(input.data),
837
+ common: input2.parent.common,
838
+ data: input2.data,
839
+ parsedType: getParsedType(input2.data),
678
840
  schemaErrorMap: this._def.errorMap,
679
- path: input.path,
680
- parent: input.parent
841
+ path: input2.path,
842
+ parent: input2.parent
681
843
  };
682
844
  }
683
- _processInputParams(input) {
845
+ _processInputParams(input2) {
684
846
  return {
685
847
  status: new ParseStatus(),
686
848
  ctx: {
687
- common: input.parent.common,
688
- data: input.data,
689
- parsedType: getParsedType(input.data),
849
+ common: input2.parent.common,
850
+ data: input2.data,
851
+ parsedType: getParsedType(input2.data),
690
852
  schemaErrorMap: this._def.errorMap,
691
- path: input.path,
692
- parent: input.parent
853
+ path: input2.path,
854
+ parent: input2.parent
693
855
  }
694
856
  };
695
857
  }
696
- _parseSync(input) {
697
- const result = this._parse(input);
858
+ _parseSync(input2) {
859
+ const result = this._parse(input2);
698
860
  if (isAsync(result)) {
699
861
  throw new Error("Synchronous parse encountered promise.");
700
862
  }
701
863
  return result;
702
864
  }
703
- _parseAsync(input) {
704
- const result = this._parse(input);
865
+ _parseAsync(input2) {
866
+ const result = this._parse(input2);
705
867
  return Promise.resolve(result);
706
868
  }
707
869
  parse(data, params) {
@@ -1027,13 +1189,13 @@ function isValidCidr(ip, version) {
1027
1189
  return false;
1028
1190
  }
1029
1191
  var ZodString = class _ZodString extends ZodType {
1030
- _parse(input) {
1192
+ _parse(input2) {
1031
1193
  if (this._def.coerce) {
1032
- input.data = String(input.data);
1194
+ input2.data = String(input2.data);
1033
1195
  }
1034
- const parsedType = this._getType(input);
1196
+ const parsedType = this._getType(input2);
1035
1197
  if (parsedType !== ZodParsedType.string) {
1036
- const ctx2 = this._getOrReturnCtx(input);
1198
+ const ctx2 = this._getOrReturnCtx(input2);
1037
1199
  addIssueToContext(ctx2, {
1038
1200
  code: ZodIssueCode.invalid_type,
1039
1201
  expected: ZodParsedType.string,
@@ -1045,8 +1207,8 @@ var ZodString = class _ZodString extends ZodType {
1045
1207
  let ctx = void 0;
1046
1208
  for (const check of this._def.checks) {
1047
1209
  if (check.kind === "min") {
1048
- if (input.data.length < check.value) {
1049
- ctx = this._getOrReturnCtx(input, ctx);
1210
+ if (input2.data.length < check.value) {
1211
+ ctx = this._getOrReturnCtx(input2, ctx);
1050
1212
  addIssueToContext(ctx, {
1051
1213
  code: ZodIssueCode.too_small,
1052
1214
  minimum: check.value,
@@ -1058,8 +1220,8 @@ var ZodString = class _ZodString extends ZodType {
1058
1220
  status.dirty();
1059
1221
  }
1060
1222
  } else if (check.kind === "max") {
1061
- if (input.data.length > check.value) {
1062
- ctx = this._getOrReturnCtx(input, ctx);
1223
+ if (input2.data.length > check.value) {
1224
+ ctx = this._getOrReturnCtx(input2, ctx);
1063
1225
  addIssueToContext(ctx, {
1064
1226
  code: ZodIssueCode.too_big,
1065
1227
  maximum: check.value,
@@ -1071,10 +1233,10 @@ var ZodString = class _ZodString extends ZodType {
1071
1233
  status.dirty();
1072
1234
  }
1073
1235
  } else if (check.kind === "length") {
1074
- const tooBig = input.data.length > check.value;
1075
- const tooSmall = input.data.length < check.value;
1236
+ const tooBig = input2.data.length > check.value;
1237
+ const tooSmall = input2.data.length < check.value;
1076
1238
  if (tooBig || tooSmall) {
1077
- ctx = this._getOrReturnCtx(input, ctx);
1239
+ ctx = this._getOrReturnCtx(input2, ctx);
1078
1240
  if (tooBig) {
1079
1241
  addIssueToContext(ctx, {
1080
1242
  code: ZodIssueCode.too_big,
@@ -1097,8 +1259,8 @@ var ZodString = class _ZodString extends ZodType {
1097
1259
  status.dirty();
1098
1260
  }
1099
1261
  } else if (check.kind === "email") {
1100
- if (!emailRegex.test(input.data)) {
1101
- ctx = this._getOrReturnCtx(input, ctx);
1262
+ if (!emailRegex.test(input2.data)) {
1263
+ ctx = this._getOrReturnCtx(input2, ctx);
1102
1264
  addIssueToContext(ctx, {
1103
1265
  validation: "email",
1104
1266
  code: ZodIssueCode.invalid_string,
@@ -1110,8 +1272,8 @@ var ZodString = class _ZodString extends ZodType {
1110
1272
  if (!emojiRegex) {
1111
1273
  emojiRegex = new RegExp(_emojiRegex, "u");
1112
1274
  }
1113
- if (!emojiRegex.test(input.data)) {
1114
- ctx = this._getOrReturnCtx(input, ctx);
1275
+ if (!emojiRegex.test(input2.data)) {
1276
+ ctx = this._getOrReturnCtx(input2, ctx);
1115
1277
  addIssueToContext(ctx, {
1116
1278
  validation: "emoji",
1117
1279
  code: ZodIssueCode.invalid_string,
@@ -1120,8 +1282,8 @@ var ZodString = class _ZodString extends ZodType {
1120
1282
  status.dirty();
1121
1283
  }
1122
1284
  } else if (check.kind === "uuid") {
1123
- if (!uuidRegex.test(input.data)) {
1124
- ctx = this._getOrReturnCtx(input, ctx);
1285
+ if (!uuidRegex.test(input2.data)) {
1286
+ ctx = this._getOrReturnCtx(input2, ctx);
1125
1287
  addIssueToContext(ctx, {
1126
1288
  validation: "uuid",
1127
1289
  code: ZodIssueCode.invalid_string,
@@ -1130,8 +1292,8 @@ var ZodString = class _ZodString extends ZodType {
1130
1292
  status.dirty();
1131
1293
  }
1132
1294
  } else if (check.kind === "nanoid") {
1133
- if (!nanoidRegex.test(input.data)) {
1134
- ctx = this._getOrReturnCtx(input, ctx);
1295
+ if (!nanoidRegex.test(input2.data)) {
1296
+ ctx = this._getOrReturnCtx(input2, ctx);
1135
1297
  addIssueToContext(ctx, {
1136
1298
  validation: "nanoid",
1137
1299
  code: ZodIssueCode.invalid_string,
@@ -1140,8 +1302,8 @@ var ZodString = class _ZodString extends ZodType {
1140
1302
  status.dirty();
1141
1303
  }
1142
1304
  } else if (check.kind === "cuid") {
1143
- if (!cuidRegex.test(input.data)) {
1144
- ctx = this._getOrReturnCtx(input, ctx);
1305
+ if (!cuidRegex.test(input2.data)) {
1306
+ ctx = this._getOrReturnCtx(input2, ctx);
1145
1307
  addIssueToContext(ctx, {
1146
1308
  validation: "cuid",
1147
1309
  code: ZodIssueCode.invalid_string,
@@ -1150,8 +1312,8 @@ var ZodString = class _ZodString extends ZodType {
1150
1312
  status.dirty();
1151
1313
  }
1152
1314
  } else if (check.kind === "cuid2") {
1153
- if (!cuid2Regex.test(input.data)) {
1154
- ctx = this._getOrReturnCtx(input, ctx);
1315
+ if (!cuid2Regex.test(input2.data)) {
1316
+ ctx = this._getOrReturnCtx(input2, ctx);
1155
1317
  addIssueToContext(ctx, {
1156
1318
  validation: "cuid2",
1157
1319
  code: ZodIssueCode.invalid_string,
@@ -1160,8 +1322,8 @@ var ZodString = class _ZodString extends ZodType {
1160
1322
  status.dirty();
1161
1323
  }
1162
1324
  } else if (check.kind === "ulid") {
1163
- if (!ulidRegex.test(input.data)) {
1164
- ctx = this._getOrReturnCtx(input, ctx);
1325
+ if (!ulidRegex.test(input2.data)) {
1326
+ ctx = this._getOrReturnCtx(input2, ctx);
1165
1327
  addIssueToContext(ctx, {
1166
1328
  validation: "ulid",
1167
1329
  code: ZodIssueCode.invalid_string,
@@ -1171,9 +1333,9 @@ var ZodString = class _ZodString extends ZodType {
1171
1333
  }
1172
1334
  } else if (check.kind === "url") {
1173
1335
  try {
1174
- new URL(input.data);
1336
+ new URL(input2.data);
1175
1337
  } catch {
1176
- ctx = this._getOrReturnCtx(input, ctx);
1338
+ ctx = this._getOrReturnCtx(input2, ctx);
1177
1339
  addIssueToContext(ctx, {
1178
1340
  validation: "url",
1179
1341
  code: ZodIssueCode.invalid_string,
@@ -1183,9 +1345,9 @@ var ZodString = class _ZodString extends ZodType {
1183
1345
  }
1184
1346
  } else if (check.kind === "regex") {
1185
1347
  check.regex.lastIndex = 0;
1186
- const testResult = check.regex.test(input.data);
1348
+ const testResult = check.regex.test(input2.data);
1187
1349
  if (!testResult) {
1188
- ctx = this._getOrReturnCtx(input, ctx);
1350
+ ctx = this._getOrReturnCtx(input2, ctx);
1189
1351
  addIssueToContext(ctx, {
1190
1352
  validation: "regex",
1191
1353
  code: ZodIssueCode.invalid_string,
@@ -1194,10 +1356,10 @@ var ZodString = class _ZodString extends ZodType {
1194
1356
  status.dirty();
1195
1357
  }
1196
1358
  } else if (check.kind === "trim") {
1197
- input.data = input.data.trim();
1359
+ input2.data = input2.data.trim();
1198
1360
  } else if (check.kind === "includes") {
1199
- if (!input.data.includes(check.value, check.position)) {
1200
- ctx = this._getOrReturnCtx(input, ctx);
1361
+ if (!input2.data.includes(check.value, check.position)) {
1362
+ ctx = this._getOrReturnCtx(input2, ctx);
1201
1363
  addIssueToContext(ctx, {
1202
1364
  code: ZodIssueCode.invalid_string,
1203
1365
  validation: { includes: check.value, position: check.position },
@@ -1206,12 +1368,12 @@ var ZodString = class _ZodString extends ZodType {
1206
1368
  status.dirty();
1207
1369
  }
1208
1370
  } else if (check.kind === "toLowerCase") {
1209
- input.data = input.data.toLowerCase();
1371
+ input2.data = input2.data.toLowerCase();
1210
1372
  } else if (check.kind === "toUpperCase") {
1211
- input.data = input.data.toUpperCase();
1373
+ input2.data = input2.data.toUpperCase();
1212
1374
  } else if (check.kind === "startsWith") {
1213
- if (!input.data.startsWith(check.value)) {
1214
- ctx = this._getOrReturnCtx(input, ctx);
1375
+ if (!input2.data.startsWith(check.value)) {
1376
+ ctx = this._getOrReturnCtx(input2, ctx);
1215
1377
  addIssueToContext(ctx, {
1216
1378
  code: ZodIssueCode.invalid_string,
1217
1379
  validation: { startsWith: check.value },
@@ -1220,8 +1382,8 @@ var ZodString = class _ZodString extends ZodType {
1220
1382
  status.dirty();
1221
1383
  }
1222
1384
  } else if (check.kind === "endsWith") {
1223
- if (!input.data.endsWith(check.value)) {
1224
- ctx = this._getOrReturnCtx(input, ctx);
1385
+ if (!input2.data.endsWith(check.value)) {
1386
+ ctx = this._getOrReturnCtx(input2, ctx);
1225
1387
  addIssueToContext(ctx, {
1226
1388
  code: ZodIssueCode.invalid_string,
1227
1389
  validation: { endsWith: check.value },
@@ -1231,8 +1393,8 @@ var ZodString = class _ZodString extends ZodType {
1231
1393
  }
1232
1394
  } else if (check.kind === "datetime") {
1233
1395
  const regex = datetimeRegex(check);
1234
- if (!regex.test(input.data)) {
1235
- ctx = this._getOrReturnCtx(input, ctx);
1396
+ if (!regex.test(input2.data)) {
1397
+ ctx = this._getOrReturnCtx(input2, ctx);
1236
1398
  addIssueToContext(ctx, {
1237
1399
  code: ZodIssueCode.invalid_string,
1238
1400
  validation: "datetime",
@@ -1242,8 +1404,8 @@ var ZodString = class _ZodString extends ZodType {
1242
1404
  }
1243
1405
  } else if (check.kind === "date") {
1244
1406
  const regex = dateRegex;
1245
- if (!regex.test(input.data)) {
1246
- ctx = this._getOrReturnCtx(input, ctx);
1407
+ if (!regex.test(input2.data)) {
1408
+ ctx = this._getOrReturnCtx(input2, ctx);
1247
1409
  addIssueToContext(ctx, {
1248
1410
  code: ZodIssueCode.invalid_string,
1249
1411
  validation: "date",
@@ -1253,8 +1415,8 @@ var ZodString = class _ZodString extends ZodType {
1253
1415
  }
1254
1416
  } else if (check.kind === "time") {
1255
1417
  const regex = timeRegex(check);
1256
- if (!regex.test(input.data)) {
1257
- ctx = this._getOrReturnCtx(input, ctx);
1418
+ if (!regex.test(input2.data)) {
1419
+ ctx = this._getOrReturnCtx(input2, ctx);
1258
1420
  addIssueToContext(ctx, {
1259
1421
  code: ZodIssueCode.invalid_string,
1260
1422
  validation: "time",
@@ -1263,8 +1425,8 @@ var ZodString = class _ZodString extends ZodType {
1263
1425
  status.dirty();
1264
1426
  }
1265
1427
  } else if (check.kind === "duration") {
1266
- if (!durationRegex.test(input.data)) {
1267
- ctx = this._getOrReturnCtx(input, ctx);
1428
+ if (!durationRegex.test(input2.data)) {
1429
+ ctx = this._getOrReturnCtx(input2, ctx);
1268
1430
  addIssueToContext(ctx, {
1269
1431
  validation: "duration",
1270
1432
  code: ZodIssueCode.invalid_string,
@@ -1273,8 +1435,8 @@ var ZodString = class _ZodString extends ZodType {
1273
1435
  status.dirty();
1274
1436
  }
1275
1437
  } else if (check.kind === "ip") {
1276
- if (!isValidIP(input.data, check.version)) {
1277
- ctx = this._getOrReturnCtx(input, ctx);
1438
+ if (!isValidIP(input2.data, check.version)) {
1439
+ ctx = this._getOrReturnCtx(input2, ctx);
1278
1440
  addIssueToContext(ctx, {
1279
1441
  validation: "ip",
1280
1442
  code: ZodIssueCode.invalid_string,
@@ -1283,8 +1445,8 @@ var ZodString = class _ZodString extends ZodType {
1283
1445
  status.dirty();
1284
1446
  }
1285
1447
  } else if (check.kind === "jwt") {
1286
- if (!isValidJWT(input.data, check.alg)) {
1287
- ctx = this._getOrReturnCtx(input, ctx);
1448
+ if (!isValidJWT(input2.data, check.alg)) {
1449
+ ctx = this._getOrReturnCtx(input2, ctx);
1288
1450
  addIssueToContext(ctx, {
1289
1451
  validation: "jwt",
1290
1452
  code: ZodIssueCode.invalid_string,
@@ -1293,8 +1455,8 @@ var ZodString = class _ZodString extends ZodType {
1293
1455
  status.dirty();
1294
1456
  }
1295
1457
  } else if (check.kind === "cidr") {
1296
- if (!isValidCidr(input.data, check.version)) {
1297
- ctx = this._getOrReturnCtx(input, ctx);
1458
+ if (!isValidCidr(input2.data, check.version)) {
1459
+ ctx = this._getOrReturnCtx(input2, ctx);
1298
1460
  addIssueToContext(ctx, {
1299
1461
  validation: "cidr",
1300
1462
  code: ZodIssueCode.invalid_string,
@@ -1303,8 +1465,8 @@ var ZodString = class _ZodString extends ZodType {
1303
1465
  status.dirty();
1304
1466
  }
1305
1467
  } else if (check.kind === "base64") {
1306
- if (!base64Regex.test(input.data)) {
1307
- ctx = this._getOrReturnCtx(input, ctx);
1468
+ if (!base64Regex.test(input2.data)) {
1469
+ ctx = this._getOrReturnCtx(input2, ctx);
1308
1470
  addIssueToContext(ctx, {
1309
1471
  validation: "base64",
1310
1472
  code: ZodIssueCode.invalid_string,
@@ -1313,8 +1475,8 @@ var ZodString = class _ZodString extends ZodType {
1313
1475
  status.dirty();
1314
1476
  }
1315
1477
  } else if (check.kind === "base64url") {
1316
- if (!base64urlRegex.test(input.data)) {
1317
- ctx = this._getOrReturnCtx(input, ctx);
1478
+ if (!base64urlRegex.test(input2.data)) {
1479
+ ctx = this._getOrReturnCtx(input2, ctx);
1318
1480
  addIssueToContext(ctx, {
1319
1481
  validation: "base64url",
1320
1482
  code: ZodIssueCode.invalid_string,
@@ -1326,7 +1488,7 @@ var ZodString = class _ZodString extends ZodType {
1326
1488
  util.assertNever(check);
1327
1489
  }
1328
1490
  }
1329
- return { status: status.value, value: input.data };
1491
+ return { status: status.value, value: input2.data };
1330
1492
  }
1331
1493
  _regex(regex, validation, message) {
1332
1494
  return this.refinement((data) => regex.test(data), {
@@ -1587,13 +1749,13 @@ var ZodNumber = class _ZodNumber extends ZodType {
1587
1749
  this.max = this.lte;
1588
1750
  this.step = this.multipleOf;
1589
1751
  }
1590
- _parse(input) {
1752
+ _parse(input2) {
1591
1753
  if (this._def.coerce) {
1592
- input.data = Number(input.data);
1754
+ input2.data = Number(input2.data);
1593
1755
  }
1594
- const parsedType = this._getType(input);
1756
+ const parsedType = this._getType(input2);
1595
1757
  if (parsedType !== ZodParsedType.number) {
1596
- const ctx2 = this._getOrReturnCtx(input);
1758
+ const ctx2 = this._getOrReturnCtx(input2);
1597
1759
  addIssueToContext(ctx2, {
1598
1760
  code: ZodIssueCode.invalid_type,
1599
1761
  expected: ZodParsedType.number,
@@ -1605,8 +1767,8 @@ var ZodNumber = class _ZodNumber extends ZodType {
1605
1767
  const status = new ParseStatus();
1606
1768
  for (const check of this._def.checks) {
1607
1769
  if (check.kind === "int") {
1608
- if (!util.isInteger(input.data)) {
1609
- ctx = this._getOrReturnCtx(input, ctx);
1770
+ if (!util.isInteger(input2.data)) {
1771
+ ctx = this._getOrReturnCtx(input2, ctx);
1610
1772
  addIssueToContext(ctx, {
1611
1773
  code: ZodIssueCode.invalid_type,
1612
1774
  expected: "integer",
@@ -1616,9 +1778,9 @@ var ZodNumber = class _ZodNumber extends ZodType {
1616
1778
  status.dirty();
1617
1779
  }
1618
1780
  } else if (check.kind === "min") {
1619
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1781
+ const tooSmall = check.inclusive ? input2.data < check.value : input2.data <= check.value;
1620
1782
  if (tooSmall) {
1621
- ctx = this._getOrReturnCtx(input, ctx);
1783
+ ctx = this._getOrReturnCtx(input2, ctx);
1622
1784
  addIssueToContext(ctx, {
1623
1785
  code: ZodIssueCode.too_small,
1624
1786
  minimum: check.value,
@@ -1630,9 +1792,9 @@ var ZodNumber = class _ZodNumber extends ZodType {
1630
1792
  status.dirty();
1631
1793
  }
1632
1794
  } else if (check.kind === "max") {
1633
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1795
+ const tooBig = check.inclusive ? input2.data > check.value : input2.data >= check.value;
1634
1796
  if (tooBig) {
1635
- ctx = this._getOrReturnCtx(input, ctx);
1797
+ ctx = this._getOrReturnCtx(input2, ctx);
1636
1798
  addIssueToContext(ctx, {
1637
1799
  code: ZodIssueCode.too_big,
1638
1800
  maximum: check.value,
@@ -1644,8 +1806,8 @@ var ZodNumber = class _ZodNumber extends ZodType {
1644
1806
  status.dirty();
1645
1807
  }
1646
1808
  } else if (check.kind === "multipleOf") {
1647
- if (floatSafeRemainder(input.data, check.value) !== 0) {
1648
- ctx = this._getOrReturnCtx(input, ctx);
1809
+ if (floatSafeRemainder(input2.data, check.value) !== 0) {
1810
+ ctx = this._getOrReturnCtx(input2, ctx);
1649
1811
  addIssueToContext(ctx, {
1650
1812
  code: ZodIssueCode.not_multiple_of,
1651
1813
  multipleOf: check.value,
@@ -1654,8 +1816,8 @@ var ZodNumber = class _ZodNumber extends ZodType {
1654
1816
  status.dirty();
1655
1817
  }
1656
1818
  } else if (check.kind === "finite") {
1657
- if (!Number.isFinite(input.data)) {
1658
- ctx = this._getOrReturnCtx(input, ctx);
1819
+ if (!Number.isFinite(input2.data)) {
1820
+ ctx = this._getOrReturnCtx(input2, ctx);
1659
1821
  addIssueToContext(ctx, {
1660
1822
  code: ZodIssueCode.not_finite,
1661
1823
  message: check.message
@@ -1666,7 +1828,7 @@ var ZodNumber = class _ZodNumber extends ZodType {
1666
1828
  util.assertNever(check);
1667
1829
  }
1668
1830
  }
1669
- return { status: status.value, value: input.data };
1831
+ return { status: status.value, value: input2.data };
1670
1832
  }
1671
1833
  gte(value, message) {
1672
1834
  return this.setLimit("min", value, true, errorUtil.toString(message));
@@ -1818,25 +1980,25 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
1818
1980
  this.min = this.gte;
1819
1981
  this.max = this.lte;
1820
1982
  }
1821
- _parse(input) {
1983
+ _parse(input2) {
1822
1984
  if (this._def.coerce) {
1823
1985
  try {
1824
- input.data = BigInt(input.data);
1986
+ input2.data = BigInt(input2.data);
1825
1987
  } catch {
1826
- return this._getInvalidInput(input);
1988
+ return this._getInvalidInput(input2);
1827
1989
  }
1828
1990
  }
1829
- const parsedType = this._getType(input);
1991
+ const parsedType = this._getType(input2);
1830
1992
  if (parsedType !== ZodParsedType.bigint) {
1831
- return this._getInvalidInput(input);
1993
+ return this._getInvalidInput(input2);
1832
1994
  }
1833
1995
  let ctx = void 0;
1834
1996
  const status = new ParseStatus();
1835
1997
  for (const check of this._def.checks) {
1836
1998
  if (check.kind === "min") {
1837
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1999
+ const tooSmall = check.inclusive ? input2.data < check.value : input2.data <= check.value;
1838
2000
  if (tooSmall) {
1839
- ctx = this._getOrReturnCtx(input, ctx);
2001
+ ctx = this._getOrReturnCtx(input2, ctx);
1840
2002
  addIssueToContext(ctx, {
1841
2003
  code: ZodIssueCode.too_small,
1842
2004
  type: "bigint",
@@ -1847,9 +2009,9 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
1847
2009
  status.dirty();
1848
2010
  }
1849
2011
  } else if (check.kind === "max") {
1850
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2012
+ const tooBig = check.inclusive ? input2.data > check.value : input2.data >= check.value;
1851
2013
  if (tooBig) {
1852
- ctx = this._getOrReturnCtx(input, ctx);
2014
+ ctx = this._getOrReturnCtx(input2, ctx);
1853
2015
  addIssueToContext(ctx, {
1854
2016
  code: ZodIssueCode.too_big,
1855
2017
  type: "bigint",
@@ -1860,8 +2022,8 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
1860
2022
  status.dirty();
1861
2023
  }
1862
2024
  } else if (check.kind === "multipleOf") {
1863
- if (input.data % check.value !== BigInt(0)) {
1864
- ctx = this._getOrReturnCtx(input, ctx);
2025
+ if (input2.data % check.value !== BigInt(0)) {
2026
+ ctx = this._getOrReturnCtx(input2, ctx);
1865
2027
  addIssueToContext(ctx, {
1866
2028
  code: ZodIssueCode.not_multiple_of,
1867
2029
  multipleOf: check.value,
@@ -1873,10 +2035,10 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
1873
2035
  util.assertNever(check);
1874
2036
  }
1875
2037
  }
1876
- return { status: status.value, value: input.data };
2038
+ return { status: status.value, value: input2.data };
1877
2039
  }
1878
- _getInvalidInput(input) {
1879
- const ctx = this._getOrReturnCtx(input);
2040
+ _getInvalidInput(input2) {
2041
+ const ctx = this._getOrReturnCtx(input2);
1880
2042
  addIssueToContext(ctx, {
1881
2043
  code: ZodIssueCode.invalid_type,
1882
2044
  expected: ZodParsedType.bigint,
@@ -1985,13 +2147,13 @@ ZodBigInt.create = (params) => {
1985
2147
  });
1986
2148
  };
1987
2149
  var ZodBoolean = class extends ZodType {
1988
- _parse(input) {
2150
+ _parse(input2) {
1989
2151
  if (this._def.coerce) {
1990
- input.data = Boolean(input.data);
2152
+ input2.data = Boolean(input2.data);
1991
2153
  }
1992
- const parsedType = this._getType(input);
2154
+ const parsedType = this._getType(input2);
1993
2155
  if (parsedType !== ZodParsedType.boolean) {
1994
- const ctx = this._getOrReturnCtx(input);
2156
+ const ctx = this._getOrReturnCtx(input2);
1995
2157
  addIssueToContext(ctx, {
1996
2158
  code: ZodIssueCode.invalid_type,
1997
2159
  expected: ZodParsedType.boolean,
@@ -1999,7 +2161,7 @@ var ZodBoolean = class extends ZodType {
1999
2161
  });
2000
2162
  return INVALID;
2001
2163
  }
2002
- return OK(input.data);
2164
+ return OK(input2.data);
2003
2165
  }
2004
2166
  };
2005
2167
  ZodBoolean.create = (params) => {
@@ -2010,13 +2172,13 @@ ZodBoolean.create = (params) => {
2010
2172
  });
2011
2173
  };
2012
2174
  var ZodDate = class _ZodDate extends ZodType {
2013
- _parse(input) {
2175
+ _parse(input2) {
2014
2176
  if (this._def.coerce) {
2015
- input.data = new Date(input.data);
2177
+ input2.data = new Date(input2.data);
2016
2178
  }
2017
- const parsedType = this._getType(input);
2179
+ const parsedType = this._getType(input2);
2018
2180
  if (parsedType !== ZodParsedType.date) {
2019
- const ctx2 = this._getOrReturnCtx(input);
2181
+ const ctx2 = this._getOrReturnCtx(input2);
2020
2182
  addIssueToContext(ctx2, {
2021
2183
  code: ZodIssueCode.invalid_type,
2022
2184
  expected: ZodParsedType.date,
@@ -2024,8 +2186,8 @@ var ZodDate = class _ZodDate extends ZodType {
2024
2186
  });
2025
2187
  return INVALID;
2026
2188
  }
2027
- if (Number.isNaN(input.data.getTime())) {
2028
- const ctx2 = this._getOrReturnCtx(input);
2189
+ if (Number.isNaN(input2.data.getTime())) {
2190
+ const ctx2 = this._getOrReturnCtx(input2);
2029
2191
  addIssueToContext(ctx2, {
2030
2192
  code: ZodIssueCode.invalid_date
2031
2193
  });
@@ -2035,8 +2197,8 @@ var ZodDate = class _ZodDate extends ZodType {
2035
2197
  let ctx = void 0;
2036
2198
  for (const check of this._def.checks) {
2037
2199
  if (check.kind === "min") {
2038
- if (input.data.getTime() < check.value) {
2039
- ctx = this._getOrReturnCtx(input, ctx);
2200
+ if (input2.data.getTime() < check.value) {
2201
+ ctx = this._getOrReturnCtx(input2, ctx);
2040
2202
  addIssueToContext(ctx, {
2041
2203
  code: ZodIssueCode.too_small,
2042
2204
  message: check.message,
@@ -2048,8 +2210,8 @@ var ZodDate = class _ZodDate extends ZodType {
2048
2210
  status.dirty();
2049
2211
  }
2050
2212
  } else if (check.kind === "max") {
2051
- if (input.data.getTime() > check.value) {
2052
- ctx = this._getOrReturnCtx(input, ctx);
2213
+ if (input2.data.getTime() > check.value) {
2214
+ ctx = this._getOrReturnCtx(input2, ctx);
2053
2215
  addIssueToContext(ctx, {
2054
2216
  code: ZodIssueCode.too_big,
2055
2217
  message: check.message,
@@ -2066,7 +2228,7 @@ var ZodDate = class _ZodDate extends ZodType {
2066
2228
  }
2067
2229
  return {
2068
2230
  status: status.value,
2069
- value: new Date(input.data.getTime())
2231
+ value: new Date(input2.data.getTime())
2070
2232
  };
2071
2233
  }
2072
2234
  _addCheck(check) {
@@ -2119,10 +2281,10 @@ ZodDate.create = (params) => {
2119
2281
  });
2120
2282
  };
2121
2283
  var ZodSymbol = class extends ZodType {
2122
- _parse(input) {
2123
- const parsedType = this._getType(input);
2284
+ _parse(input2) {
2285
+ const parsedType = this._getType(input2);
2124
2286
  if (parsedType !== ZodParsedType.symbol) {
2125
- const ctx = this._getOrReturnCtx(input);
2287
+ const ctx = this._getOrReturnCtx(input2);
2126
2288
  addIssueToContext(ctx, {
2127
2289
  code: ZodIssueCode.invalid_type,
2128
2290
  expected: ZodParsedType.symbol,
@@ -2130,7 +2292,7 @@ var ZodSymbol = class extends ZodType {
2130
2292
  });
2131
2293
  return INVALID;
2132
2294
  }
2133
- return OK(input.data);
2295
+ return OK(input2.data);
2134
2296
  }
2135
2297
  };
2136
2298
  ZodSymbol.create = (params) => {
@@ -2140,10 +2302,10 @@ ZodSymbol.create = (params) => {
2140
2302
  });
2141
2303
  };
2142
2304
  var ZodUndefined = class extends ZodType {
2143
- _parse(input) {
2144
- const parsedType = this._getType(input);
2305
+ _parse(input2) {
2306
+ const parsedType = this._getType(input2);
2145
2307
  if (parsedType !== ZodParsedType.undefined) {
2146
- const ctx = this._getOrReturnCtx(input);
2308
+ const ctx = this._getOrReturnCtx(input2);
2147
2309
  addIssueToContext(ctx, {
2148
2310
  code: ZodIssueCode.invalid_type,
2149
2311
  expected: ZodParsedType.undefined,
@@ -2151,7 +2313,7 @@ var ZodUndefined = class extends ZodType {
2151
2313
  });
2152
2314
  return INVALID;
2153
2315
  }
2154
- return OK(input.data);
2316
+ return OK(input2.data);
2155
2317
  }
2156
2318
  };
2157
2319
  ZodUndefined.create = (params) => {
@@ -2161,10 +2323,10 @@ ZodUndefined.create = (params) => {
2161
2323
  });
2162
2324
  };
2163
2325
  var ZodNull = class extends ZodType {
2164
- _parse(input) {
2165
- const parsedType = this._getType(input);
2326
+ _parse(input2) {
2327
+ const parsedType = this._getType(input2);
2166
2328
  if (parsedType !== ZodParsedType.null) {
2167
- const ctx = this._getOrReturnCtx(input);
2329
+ const ctx = this._getOrReturnCtx(input2);
2168
2330
  addIssueToContext(ctx, {
2169
2331
  code: ZodIssueCode.invalid_type,
2170
2332
  expected: ZodParsedType.null,
@@ -2172,7 +2334,7 @@ var ZodNull = class extends ZodType {
2172
2334
  });
2173
2335
  return INVALID;
2174
2336
  }
2175
- return OK(input.data);
2337
+ return OK(input2.data);
2176
2338
  }
2177
2339
  };
2178
2340
  ZodNull.create = (params) => {
@@ -2186,8 +2348,8 @@ var ZodAny = class extends ZodType {
2186
2348
  super(...arguments);
2187
2349
  this._any = true;
2188
2350
  }
2189
- _parse(input) {
2190
- return OK(input.data);
2351
+ _parse(input2) {
2352
+ return OK(input2.data);
2191
2353
  }
2192
2354
  };
2193
2355
  ZodAny.create = (params) => {
@@ -2201,8 +2363,8 @@ var ZodUnknown = class extends ZodType {
2201
2363
  super(...arguments);
2202
2364
  this._unknown = true;
2203
2365
  }
2204
- _parse(input) {
2205
- return OK(input.data);
2366
+ _parse(input2) {
2367
+ return OK(input2.data);
2206
2368
  }
2207
2369
  };
2208
2370
  ZodUnknown.create = (params) => {
@@ -2212,8 +2374,8 @@ ZodUnknown.create = (params) => {
2212
2374
  });
2213
2375
  };
2214
2376
  var ZodNever = class extends ZodType {
2215
- _parse(input) {
2216
- const ctx = this._getOrReturnCtx(input);
2377
+ _parse(input2) {
2378
+ const ctx = this._getOrReturnCtx(input2);
2217
2379
  addIssueToContext(ctx, {
2218
2380
  code: ZodIssueCode.invalid_type,
2219
2381
  expected: ZodParsedType.never,
@@ -2229,10 +2391,10 @@ ZodNever.create = (params) => {
2229
2391
  });
2230
2392
  };
2231
2393
  var ZodVoid = class extends ZodType {
2232
- _parse(input) {
2233
- const parsedType = this._getType(input);
2394
+ _parse(input2) {
2395
+ const parsedType = this._getType(input2);
2234
2396
  if (parsedType !== ZodParsedType.undefined) {
2235
- const ctx = this._getOrReturnCtx(input);
2397
+ const ctx = this._getOrReturnCtx(input2);
2236
2398
  addIssueToContext(ctx, {
2237
2399
  code: ZodIssueCode.invalid_type,
2238
2400
  expected: ZodParsedType.void,
@@ -2240,7 +2402,7 @@ var ZodVoid = class extends ZodType {
2240
2402
  });
2241
2403
  return INVALID;
2242
2404
  }
2243
- return OK(input.data);
2405
+ return OK(input2.data);
2244
2406
  }
2245
2407
  };
2246
2408
  ZodVoid.create = (params) => {
@@ -2250,8 +2412,8 @@ ZodVoid.create = (params) => {
2250
2412
  });
2251
2413
  };
2252
2414
  var ZodArray = class _ZodArray extends ZodType {
2253
- _parse(input) {
2254
- const { ctx, status } = this._processInputParams(input);
2415
+ _parse(input2) {
2416
+ const { ctx, status } = this._processInputParams(input2);
2255
2417
  const def = this._def;
2256
2418
  if (ctx.parsedType !== ZodParsedType.array) {
2257
2419
  addIssueToContext(ctx, {
@@ -2391,10 +2553,10 @@ var ZodObject = class _ZodObject extends ZodType {
2391
2553
  this._cached = { shape, keys };
2392
2554
  return this._cached;
2393
2555
  }
2394
- _parse(input) {
2395
- const parsedType = this._getType(input);
2556
+ _parse(input2) {
2557
+ const parsedType = this._getType(input2);
2396
2558
  if (parsedType !== ZodParsedType.object) {
2397
- const ctx2 = this._getOrReturnCtx(input);
2559
+ const ctx2 = this._getOrReturnCtx(input2);
2398
2560
  addIssueToContext(ctx2, {
2399
2561
  code: ZodIssueCode.invalid_type,
2400
2562
  expected: ZodParsedType.object,
@@ -2402,7 +2564,7 @@ var ZodObject = class _ZodObject extends ZodType {
2402
2564
  });
2403
2565
  return INVALID;
2404
2566
  }
2405
- const { status, ctx } = this._processInputParams(input);
2567
+ const { status, ctx } = this._processInputParams(input2);
2406
2568
  const { shape, keys: shapeKeys } = this._getCached();
2407
2569
  const extraKeys = [];
2408
2570
  if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
@@ -2714,8 +2876,8 @@ ZodObject.lazycreate = (shape, params) => {
2714
2876
  });
2715
2877
  };
2716
2878
  var ZodUnion = class extends ZodType {
2717
- _parse(input) {
2718
- const { ctx } = this._processInputParams(input);
2879
+ _parse(input2) {
2880
+ const { ctx } = this._processInputParams(input2);
2719
2881
  const options = this._def.options;
2720
2882
  function handleResults(results) {
2721
2883
  for (const result of results) {
@@ -2836,8 +2998,8 @@ var getDiscriminator = (type) => {
2836
2998
  }
2837
2999
  };
2838
3000
  var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
2839
- _parse(input) {
2840
- const { ctx } = this._processInputParams(input);
3001
+ _parse(input2) {
3002
+ const { ctx } = this._processInputParams(input2);
2841
3003
  if (ctx.parsedType !== ZodParsedType.object) {
2842
3004
  addIssueToContext(ctx, {
2843
3005
  code: ZodIssueCode.invalid_type,
@@ -2950,8 +3112,8 @@ function mergeValues(a, b) {
2950
3112
  }
2951
3113
  }
2952
3114
  var ZodIntersection = class extends ZodType {
2953
- _parse(input) {
2954
- const { status, ctx } = this._processInputParams(input);
3115
+ _parse(input2) {
3116
+ const { status, ctx } = this._processInputParams(input2);
2955
3117
  const handleParsed = (parsedLeft, parsedRight) => {
2956
3118
  if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2957
3119
  return INVALID;
@@ -3003,8 +3165,8 @@ ZodIntersection.create = (left, right, params) => {
3003
3165
  });
3004
3166
  };
3005
3167
  var ZodTuple = class _ZodTuple extends ZodType {
3006
- _parse(input) {
3007
- const { status, ctx } = this._processInputParams(input);
3168
+ _parse(input2) {
3169
+ const { status, ctx } = this._processInputParams(input2);
3008
3170
  if (ctx.parsedType !== ZodParsedType.array) {
3009
3171
  addIssueToContext(ctx, {
3010
3172
  code: ZodIssueCode.invalid_type,
@@ -3039,7 +3201,7 @@ var ZodTuple = class _ZodTuple extends ZodType {
3039
3201
  if (!schema)
3040
3202
  return null;
3041
3203
  return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3042
- }).filter((x) => !!x);
3204
+ }).filter((x3) => !!x3);
3043
3205
  if (ctx.common.async) {
3044
3206
  return Promise.all(items).then((results) => {
3045
3207
  return ParseStatus.mergeArray(status, results);
@@ -3076,8 +3238,8 @@ var ZodRecord = class _ZodRecord extends ZodType {
3076
3238
  get valueSchema() {
3077
3239
  return this._def.valueType;
3078
3240
  }
3079
- _parse(input) {
3080
- const { status, ctx } = this._processInputParams(input);
3241
+ _parse(input2) {
3242
+ const { status, ctx } = this._processInputParams(input2);
3081
3243
  if (ctx.parsedType !== ZodParsedType.object) {
3082
3244
  addIssueToContext(ctx, {
3083
3245
  code: ZodIssueCode.invalid_type,
@@ -3129,8 +3291,8 @@ var ZodMap = class extends ZodType {
3129
3291
  get valueSchema() {
3130
3292
  return this._def.valueType;
3131
3293
  }
3132
- _parse(input) {
3133
- const { status, ctx } = this._processInputParams(input);
3294
+ _parse(input2) {
3295
+ const { status, ctx } = this._processInputParams(input2);
3134
3296
  if (ctx.parsedType !== ZodParsedType.map) {
3135
3297
  addIssueToContext(ctx, {
3136
3298
  code: ZodIssueCode.invalid_type,
@@ -3189,8 +3351,8 @@ ZodMap.create = (keyType, valueType, params) => {
3189
3351
  });
3190
3352
  };
3191
3353
  var ZodSet = class _ZodSet extends ZodType {
3192
- _parse(input) {
3193
- const { status, ctx } = this._processInputParams(input);
3354
+ _parse(input2) {
3355
+ const { status, ctx } = this._processInputParams(input2);
3194
3356
  if (ctx.parsedType !== ZodParsedType.set) {
3195
3357
  addIssueToContext(ctx, {
3196
3358
  code: ZodIssueCode.invalid_type,
@@ -3278,8 +3440,8 @@ var ZodFunction = class _ZodFunction extends ZodType {
3278
3440
  super(...arguments);
3279
3441
  this.validate = this.implement;
3280
3442
  }
3281
- _parse(input) {
3282
- const { ctx } = this._processInputParams(input);
3443
+ _parse(input2) {
3444
+ const { ctx } = this._processInputParams(input2);
3283
3445
  if (ctx.parsedType !== ZodParsedType.function) {
3284
3446
  addIssueToContext(ctx, {
3285
3447
  code: ZodIssueCode.invalid_type,
@@ -3292,7 +3454,7 @@ var ZodFunction = class _ZodFunction extends ZodType {
3292
3454
  return makeIssue({
3293
3455
  data: args,
3294
3456
  path: ctx.path,
3295
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3457
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x3) => !!x3),
3296
3458
  issueData: {
3297
3459
  code: ZodIssueCode.invalid_arguments,
3298
3460
  argumentsError: error
@@ -3303,7 +3465,7 @@ var ZodFunction = class _ZodFunction extends ZodType {
3303
3465
  return makeIssue({
3304
3466
  data: returns,
3305
3467
  path: ctx.path,
3306
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3468
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x3) => !!x3),
3307
3469
  issueData: {
3308
3470
  code: ZodIssueCode.invalid_return_type,
3309
3471
  returnTypeError: error
@@ -3313,29 +3475,29 @@ var ZodFunction = class _ZodFunction extends ZodType {
3313
3475
  const params = { errorMap: ctx.common.contextualErrorMap };
3314
3476
  const fn = ctx.data;
3315
3477
  if (this._def.returns instanceof ZodPromise) {
3316
- const me = this;
3478
+ const me2 = this;
3317
3479
  return OK(async function(...args) {
3318
3480
  const error = new ZodError([]);
3319
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3320
- error.addIssue(makeArgsIssue(args, e));
3481
+ const parsedArgs = await me2._def.args.parseAsync(args, params).catch((e2) => {
3482
+ error.addIssue(makeArgsIssue(args, e2));
3321
3483
  throw error;
3322
3484
  });
3323
3485
  const result = await Reflect.apply(fn, this, parsedArgs);
3324
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3325
- error.addIssue(makeReturnsIssue(result, e));
3486
+ const parsedReturns = await me2._def.returns._def.type.parseAsync(result, params).catch((e2) => {
3487
+ error.addIssue(makeReturnsIssue(result, e2));
3326
3488
  throw error;
3327
3489
  });
3328
3490
  return parsedReturns;
3329
3491
  });
3330
3492
  } else {
3331
- const me = this;
3493
+ const me2 = this;
3332
3494
  return OK(function(...args) {
3333
- const parsedArgs = me._def.args.safeParse(args, params);
3495
+ const parsedArgs = me2._def.args.safeParse(args, params);
3334
3496
  if (!parsedArgs.success) {
3335
3497
  throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3336
3498
  }
3337
3499
  const result = Reflect.apply(fn, this, parsedArgs.data);
3338
- const parsedReturns = me._def.returns.safeParse(result, params);
3500
+ const parsedReturns = me2._def.returns.safeParse(result, params);
3339
3501
  if (!parsedReturns.success) {
3340
3502
  throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3341
3503
  }
@@ -3382,8 +3544,8 @@ var ZodLazy = class extends ZodType {
3382
3544
  get schema() {
3383
3545
  return this._def.getter();
3384
3546
  }
3385
- _parse(input) {
3386
- const { ctx } = this._processInputParams(input);
3547
+ _parse(input2) {
3548
+ const { ctx } = this._processInputParams(input2);
3387
3549
  const lazySchema = this._def.getter();
3388
3550
  return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3389
3551
  }
@@ -3396,9 +3558,9 @@ ZodLazy.create = (getter, params) => {
3396
3558
  });
3397
3559
  };
3398
3560
  var ZodLiteral = class extends ZodType {
3399
- _parse(input) {
3400
- if (input.data !== this._def.value) {
3401
- const ctx = this._getOrReturnCtx(input);
3561
+ _parse(input2) {
3562
+ if (input2.data !== this._def.value) {
3563
+ const ctx = this._getOrReturnCtx(input2);
3402
3564
  addIssueToContext(ctx, {
3403
3565
  received: ctx.data,
3404
3566
  code: ZodIssueCode.invalid_literal,
@@ -3406,7 +3568,7 @@ var ZodLiteral = class extends ZodType {
3406
3568
  });
3407
3569
  return INVALID;
3408
3570
  }
3409
- return { status: "valid", value: input.data };
3571
+ return { status: "valid", value: input2.data };
3410
3572
  }
3411
3573
  get value() {
3412
3574
  return this._def.value;
@@ -3427,9 +3589,9 @@ function createZodEnum(values, params) {
3427
3589
  });
3428
3590
  }
3429
3591
  var ZodEnum = class _ZodEnum extends ZodType {
3430
- _parse(input) {
3431
- if (typeof input.data !== "string") {
3432
- const ctx = this._getOrReturnCtx(input);
3592
+ _parse(input2) {
3593
+ if (typeof input2.data !== "string") {
3594
+ const ctx = this._getOrReturnCtx(input2);
3433
3595
  const expectedValues = this._def.values;
3434
3596
  addIssueToContext(ctx, {
3435
3597
  expected: util.joinValues(expectedValues),
@@ -3441,8 +3603,8 @@ var ZodEnum = class _ZodEnum extends ZodType {
3441
3603
  if (!this._cache) {
3442
3604
  this._cache = new Set(this._def.values);
3443
3605
  }
3444
- if (!this._cache.has(input.data)) {
3445
- const ctx = this._getOrReturnCtx(input);
3606
+ if (!this._cache.has(input2.data)) {
3607
+ const ctx = this._getOrReturnCtx(input2);
3446
3608
  const expectedValues = this._def.values;
3447
3609
  addIssueToContext(ctx, {
3448
3610
  received: ctx.data,
@@ -3451,7 +3613,7 @@ var ZodEnum = class _ZodEnum extends ZodType {
3451
3613
  });
3452
3614
  return INVALID;
3453
3615
  }
3454
- return OK(input.data);
3616
+ return OK(input2.data);
3455
3617
  }
3456
3618
  get options() {
3457
3619
  return this._def.values;
@@ -3492,9 +3654,9 @@ var ZodEnum = class _ZodEnum extends ZodType {
3492
3654
  };
3493
3655
  ZodEnum.create = createZodEnum;
3494
3656
  var ZodNativeEnum = class extends ZodType {
3495
- _parse(input) {
3657
+ _parse(input2) {
3496
3658
  const nativeEnumValues = util.getValidEnumValues(this._def.values);
3497
- const ctx = this._getOrReturnCtx(input);
3659
+ const ctx = this._getOrReturnCtx(input2);
3498
3660
  if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3499
3661
  const expectedValues = util.objectValues(nativeEnumValues);
3500
3662
  addIssueToContext(ctx, {
@@ -3507,7 +3669,7 @@ var ZodNativeEnum = class extends ZodType {
3507
3669
  if (!this._cache) {
3508
3670
  this._cache = new Set(util.getValidEnumValues(this._def.values));
3509
3671
  }
3510
- if (!this._cache.has(input.data)) {
3672
+ if (!this._cache.has(input2.data)) {
3511
3673
  const expectedValues = util.objectValues(nativeEnumValues);
3512
3674
  addIssueToContext(ctx, {
3513
3675
  received: ctx.data,
@@ -3516,7 +3678,7 @@ var ZodNativeEnum = class extends ZodType {
3516
3678
  });
3517
3679
  return INVALID;
3518
3680
  }
3519
- return OK(input.data);
3681
+ return OK(input2.data);
3520
3682
  }
3521
3683
  get enum() {
3522
3684
  return this._def.values;
@@ -3533,8 +3695,8 @@ var ZodPromise = class extends ZodType {
3533
3695
  unwrap() {
3534
3696
  return this._def.type;
3535
3697
  }
3536
- _parse(input) {
3537
- const { ctx } = this._processInputParams(input);
3698
+ _parse(input2) {
3699
+ const { ctx } = this._processInputParams(input2);
3538
3700
  if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3539
3701
  addIssueToContext(ctx, {
3540
3702
  code: ZodIssueCode.invalid_type,
@@ -3566,8 +3728,8 @@ var ZodEffects = class extends ZodType {
3566
3728
  sourceType() {
3567
3729
  return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3568
3730
  }
3569
- _parse(input) {
3570
- const { status, ctx } = this._processInputParams(input);
3731
+ _parse(input2) {
3732
+ const { status, ctx } = this._processInputParams(input2);
3571
3733
  const effect = this._def.effect || null;
3572
3734
  const checkCtx = {
3573
3735
  addIssue: (arg) => {
@@ -3699,12 +3861,12 @@ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3699
3861
  });
3700
3862
  };
3701
3863
  var ZodOptional = class extends ZodType {
3702
- _parse(input) {
3703
- const parsedType = this._getType(input);
3864
+ _parse(input2) {
3865
+ const parsedType = this._getType(input2);
3704
3866
  if (parsedType === ZodParsedType.undefined) {
3705
3867
  return OK(void 0);
3706
3868
  }
3707
- return this._def.innerType._parse(input);
3869
+ return this._def.innerType._parse(input2);
3708
3870
  }
3709
3871
  unwrap() {
3710
3872
  return this._def.innerType;
@@ -3718,12 +3880,12 @@ ZodOptional.create = (type, params) => {
3718
3880
  });
3719
3881
  };
3720
3882
  var ZodNullable = class extends ZodType {
3721
- _parse(input) {
3722
- const parsedType = this._getType(input);
3883
+ _parse(input2) {
3884
+ const parsedType = this._getType(input2);
3723
3885
  if (parsedType === ZodParsedType.null) {
3724
3886
  return OK(null);
3725
3887
  }
3726
- return this._def.innerType._parse(input);
3888
+ return this._def.innerType._parse(input2);
3727
3889
  }
3728
3890
  unwrap() {
3729
3891
  return this._def.innerType;
@@ -3737,8 +3899,8 @@ ZodNullable.create = (type, params) => {
3737
3899
  });
3738
3900
  };
3739
3901
  var ZodDefault = class extends ZodType {
3740
- _parse(input) {
3741
- const { ctx } = this._processInputParams(input);
3902
+ _parse(input2) {
3903
+ const { ctx } = this._processInputParams(input2);
3742
3904
  let data = ctx.data;
3743
3905
  if (ctx.parsedType === ZodParsedType.undefined) {
3744
3906
  data = this._def.defaultValue();
@@ -3762,8 +3924,8 @@ ZodDefault.create = (type, params) => {
3762
3924
  });
3763
3925
  };
3764
3926
  var ZodCatch = class extends ZodType {
3765
- _parse(input) {
3766
- const { ctx } = this._processInputParams(input);
3927
+ _parse(input2) {
3928
+ const { ctx } = this._processInputParams(input2);
3767
3929
  const newCtx = {
3768
3930
  ...ctx,
3769
3931
  common: {
@@ -3815,10 +3977,10 @@ ZodCatch.create = (type, params) => {
3815
3977
  });
3816
3978
  };
3817
3979
  var ZodNaN = class extends ZodType {
3818
- _parse(input) {
3819
- const parsedType = this._getType(input);
3980
+ _parse(input2) {
3981
+ const parsedType = this._getType(input2);
3820
3982
  if (parsedType !== ZodParsedType.nan) {
3821
- const ctx = this._getOrReturnCtx(input);
3983
+ const ctx = this._getOrReturnCtx(input2);
3822
3984
  addIssueToContext(ctx, {
3823
3985
  code: ZodIssueCode.invalid_type,
3824
3986
  expected: ZodParsedType.nan,
@@ -3826,7 +3988,7 @@ var ZodNaN = class extends ZodType {
3826
3988
  });
3827
3989
  return INVALID;
3828
3990
  }
3829
- return { status: "valid", value: input.data };
3991
+ return { status: "valid", value: input2.data };
3830
3992
  }
3831
3993
  };
3832
3994
  ZodNaN.create = (params) => {
@@ -3837,8 +3999,8 @@ ZodNaN.create = (params) => {
3837
3999
  };
3838
4000
  var BRAND = /* @__PURE__ */ Symbol("zod_brand");
3839
4001
  var ZodBranded = class extends ZodType {
3840
- _parse(input) {
3841
- const { ctx } = this._processInputParams(input);
4002
+ _parse(input2) {
4003
+ const { ctx } = this._processInputParams(input2);
3842
4004
  const data = ctx.data;
3843
4005
  return this._def.type._parse({
3844
4006
  data,
@@ -3851,8 +4013,8 @@ var ZodBranded = class extends ZodType {
3851
4013
  }
3852
4014
  };
3853
4015
  var ZodPipeline = class _ZodPipeline extends ZodType {
3854
- _parse(input) {
3855
- const { status, ctx } = this._processInputParams(input);
4016
+ _parse(input2) {
4017
+ const { status, ctx } = this._processInputParams(input2);
3856
4018
  if (ctx.common.async) {
3857
4019
  const handleAsync = async () => {
3858
4020
  const inResult = await this._def.in._parseAsync({
@@ -3906,8 +4068,8 @@ var ZodPipeline = class _ZodPipeline extends ZodType {
3906
4068
  }
3907
4069
  };
3908
4070
  var ZodReadonly = class extends ZodType {
3909
- _parse(input) {
3910
- const result = this._def.innerType._parse(input);
4071
+ _parse(input2) {
4072
+ const result = this._def.innerType._parse(input2);
3911
4073
  const freeze = (data) => {
3912
4074
  if (isValid(data)) {
3913
4075
  data.value = Object.freeze(data.value);
@@ -4212,7 +4374,7 @@ function checkDmPolicy(params) {
4212
4374
 
4213
4375
  // ../../packages/shared/src/policy/group-policy.ts
4214
4376
  function checkGroupPolicy(params) {
4215
- const { groupPolicy, conversationId, groupAllowFrom = []} = params;
4377
+ const { groupPolicy, conversationId, groupAllowFrom = [], requireMention, mentionedBot } = params;
4216
4378
  switch (groupPolicy) {
4217
4379
  case "disabled":
4218
4380
  return {
@@ -4228,6 +4390,12 @@ function checkGroupPolicy(params) {
4228
4390
  }
4229
4391
  break;
4230
4392
  }
4393
+ if (requireMention && !mentionedBot) {
4394
+ return {
4395
+ allowed: false,
4396
+ reason: "message did not mention bot"
4397
+ };
4398
+ }
4231
4399
  return { allowed: true };
4232
4400
  }
4233
4401
 
@@ -4294,8 +4462,20 @@ function resolveExtension(contentType, fileName) {
4294
4462
  }
4295
4463
  return ".bin";
4296
4464
  }
4297
-
4298
- // ../../packages/shared/src/media/media-parser.ts
4465
+ var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
4466
+ "png",
4467
+ "jpg",
4468
+ "jpeg",
4469
+ "gif",
4470
+ "webp",
4471
+ "bmp",
4472
+ "tiff",
4473
+ "tif",
4474
+ "heic",
4475
+ "heif",
4476
+ "svg",
4477
+ "ico"
4478
+ ]);
4299
4479
  var AUDIO_EXTENSIONS = /* @__PURE__ */ new Set([
4300
4480
  "mp3",
4301
4481
  "wav",
@@ -4349,217 +4529,2233 @@ var NON_IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
4349
4529
  "yaml",
4350
4530
  "yml"
4351
4531
  ]);
4352
- Array.from(NON_IMAGE_EXTENSIONS).join("|");
4353
- function decodeEncodingAESKey(encodingAESKey) {
4354
- const trimmed = encodingAESKey.trim();
4355
- if (!trimmed) throw new Error("encodingAESKey missing");
4356
- const withPadding = trimmed.endsWith("=") ? trimmed : `${trimmed}=`;
4357
- const key = Buffer.from(withPadding, "base64");
4358
- if (key.length !== 32) {
4359
- throw new Error(`invalid encodingAESKey (expected 32 bytes after base64 decode, got ${key.length})`);
4360
- }
4361
- return key;
4532
+ var MARKDOWN_IMAGE_RE = /!\[([^\]]*)\]\(([^)]+)\)/g;
4533
+ var MARKDOWN_LINKED_IMAGE_RE = /\[!\[([^\]]*)\]\(([^)]+)\)\]\(([^)]+)\)/g;
4534
+ var HTML_IMAGE_RE = /<img\b[^>]*\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))[^>]*>/gi;
4535
+ var MARKDOWN_LINK_RE = /\[([^\]]*)\]\(([^)]+)\)/g;
4536
+ var BARE_IMAGE_PATH_RE = /`?((?:\/(?:tmp|var|private|Users|home|root)\/[^\s`'",)]+|[A-Za-z]:[\\/][^\s`'",)]+)\.(?:png|jpg|jpeg|gif|bmp|webp|svg|ico))`?/gi;
4537
+ var NON_IMAGE_EXT_PATTERN = Array.from(NON_IMAGE_EXTENSIONS).join("|");
4538
+ var WINDOWS_PATH_SEP = String.raw`(?:\\\\|\\)`;
4539
+ var WINDOWS_FILE_PATH = String.raw`[A-Za-z]:${WINDOWS_PATH_SEP}(?:[^\\/:*?"<>|\r\n]+${WINDOWS_PATH_SEP})*[^\\/:*?"<>|\r\n]+`;
4540
+ var UNIX_FILE_PATH = String.raw`\/(?:tmp|var|private|Users|home|root)\/[^\s'",)]+`;
4541
+ var BARE_FILE_PATH_RE = new RegExp(
4542
+ String.raw`\`?((?:${UNIX_FILE_PATH}|${WINDOWS_FILE_PATH})\.(?:${NON_IMAGE_EXT_PATTERN}))\`?`,
4543
+ "gi"
4544
+ );
4545
+ var MEDIA_LINE_PREFIX = "MEDIA:";
4546
+ function unwrapMediaLinePayload(value) {
4547
+ const trimmed = value.trim();
4548
+ if (trimmed.length < 2) return void 0;
4549
+ const first = trimmed[0];
4550
+ const last = trimmed[trimmed.length - 1];
4551
+ if (first !== last) return void 0;
4552
+ if (first !== `"` && first !== "'" && first !== "`") return void 0;
4553
+ return trimmed.slice(1, -1).trim();
4362
4554
  }
4363
- var WECOM_PKCS7_BLOCK_SIZE = 32;
4364
- function pkcs7Pad(buf, blockSize) {
4365
- const mod = buf.length % blockSize;
4366
- const pad = mod === 0 ? blockSize : blockSize - mod;
4367
- return Buffer.concat([buf, Buffer.alloc(pad, pad)]);
4555
+ function cleanMediaLineCandidate(value) {
4556
+ return value.replace(/^[`"'[{(<]+/, "").replace(/[`"'\])}>.,;]+$/, "");
4368
4557
  }
4369
- function pkcs7Unpad(buf, blockSize) {
4370
- if (buf.length === 0) throw new Error("invalid pkcs7 payload");
4371
- const pad = buf[buf.length - 1];
4372
- if (!pad || pad < 1 || pad > blockSize || pad > buf.length) {
4373
- throw new Error("invalid pkcs7 padding");
4374
- }
4375
- for (let i = 1; i <= pad; i += 1) {
4376
- if (buf[buf.length - i] !== pad) {
4377
- throw new Error("invalid pkcs7 padding");
4378
- }
4379
- }
4380
- return buf.subarray(0, buf.length - pad);
4558
+ function splitMediaLineCandidates(payload) {
4559
+ const unwrapped = unwrapMediaLinePayload(payload);
4560
+ if (unwrapped) return [unwrapped];
4561
+ return payload.split(/\s+/).filter(Boolean);
4381
4562
  }
4382
- function sha1Hex(input) {
4383
- return crypto.createHash("sha1").update(input).digest("hex");
4563
+ function isHttpUrl(value) {
4564
+ return /^https?:\/\//i.test(value);
4384
4565
  }
4385
- function computeWecomMsgSignature(params) {
4386
- const parts = [params.token, params.timestamp, params.nonce, params.encrypt].map((value) => String(value ?? "")).sort();
4387
- return sha1Hex(parts.join(""));
4566
+ function isFileUrl(value) {
4567
+ return /^file:\/\//i.test(value);
4388
4568
  }
4389
- function verifyWecomSignature(params) {
4390
- const expected = computeWecomMsgSignature({
4391
- token: params.token,
4392
- timestamp: params.timestamp,
4393
- nonce: params.nonce,
4394
- encrypt: params.encrypt
4395
- });
4396
- return expected === params.signature;
4569
+ function isLocalReference(raw) {
4570
+ if (isHttpUrl(raw)) return false;
4571
+ return raw.startsWith("file://") || raw.startsWith("MEDIA:") || raw.startsWith("attachment://") || raw.startsWith("/") || raw.startsWith("~") || /^[a-zA-Z]:[\\/]/.test(raw);
4397
4572
  }
4398
- function decryptWecomEncrypted(params) {
4399
- const aesKey = decodeEncodingAESKey(params.encodingAESKey);
4400
- const iv = aesKey.subarray(0, 16);
4401
- const decipher = crypto.createDecipheriv("aes-256-cbc", aesKey, iv);
4402
- decipher.setAutoPadding(false);
4403
- const decryptedPadded = Buffer.concat([
4404
- decipher.update(Buffer.from(params.encrypt, "base64")),
4405
- decipher.final()
4406
- ]);
4407
- const decrypted = pkcs7Unpad(decryptedPadded, WECOM_PKCS7_BLOCK_SIZE);
4408
- if (decrypted.length < 20) {
4409
- throw new Error(`invalid decrypted payload (expected at least 20 bytes, got ${decrypted.length})`);
4410
- }
4411
- const msgLen = decrypted.readUInt32BE(16);
4412
- const msgStart = 20;
4413
- const msgEnd = msgStart + msgLen;
4414
- if (msgEnd > decrypted.length) {
4415
- throw new Error(`invalid decrypted msg length (msgEnd=${msgEnd}, payloadLength=${decrypted.length})`);
4416
- }
4417
- const msg = decrypted.subarray(msgStart, msgEnd).toString("utf8");
4418
- const receiveId = params.receiveId ?? "";
4419
- if (receiveId) {
4420
- const trailing = decrypted.subarray(msgEnd).toString("utf8");
4421
- if (trailing !== receiveId) {
4422
- throw new Error(`receiveId mismatch (expected "${receiveId}", got "${trailing}")`);
4573
+ function normalizeLocalPath(raw) {
4574
+ let p = raw.trim();
4575
+ if (isFileUrl(p)) {
4576
+ try {
4577
+ return fileURLToPath(p);
4578
+ } catch {
4579
+ p = p.replace(/^file:\/\/\/?/i, "");
4423
4580
  }
4424
4581
  }
4425
- return msg;
4426
- }
4427
- function encryptWecomPlaintext(params) {
4428
- const aesKey = decodeEncodingAESKey(params.encodingAESKey);
4429
- const iv = aesKey.subarray(0, 16);
4430
- const random16 = crypto.randomBytes(16);
4431
- const msg = Buffer.from(params.plaintext ?? "", "utf8");
4432
- const msgLen = Buffer.alloc(4);
4433
- msgLen.writeUInt32BE(msg.length, 0);
4434
- const receiveId = Buffer.from(params.receiveId ?? "", "utf8");
4435
- const raw = Buffer.concat([random16, msgLen, msg, receiveId]);
4436
- const padded = pkcs7Pad(raw, WECOM_PKCS7_BLOCK_SIZE);
4437
- const cipher = crypto.createCipheriv("aes-256-cbc", aesKey, iv);
4438
- cipher.setAutoPadding(false);
4439
- const encrypted = Buffer.concat([cipher.update(padded), cipher.final()]);
4440
- return encrypted.toString("base64");
4441
- }
4442
- function decryptWecomMedia(params) {
4443
- const { encryptedBuffer, encodingAESKey } = params;
4444
- if (!encryptedBuffer || encryptedBuffer.length === 0) {
4445
- throw new Error("encryptedBuffer cannot be empty");
4582
+ if (p.startsWith("MEDIA:")) {
4583
+ p = p.replace(/^MEDIA:/i, "");
4584
+ } else if (p.startsWith("attachment://")) {
4585
+ p = p.replace(/^attachment:\/\//i, "");
4446
4586
  }
4447
- const aesKey = decodeEncodingAESKey(encodingAESKey);
4448
- const iv = aesKey.subarray(0, 16);
4449
- const decipher = crypto.createDecipheriv("aes-256-cbc", aesKey, iv);
4450
- decipher.setAutoPadding(false);
4587
+ p = p.replace(/\\ /g, " ");
4451
4588
  try {
4452
- const decryptedPadded = Buffer.concat([
4453
- decipher.update(encryptedBuffer),
4454
- decipher.final()
4455
- ]);
4456
- const decrypted = pkcs7Unpad(decryptedPadded, WECOM_PKCS7_BLOCK_SIZE);
4457
- return decrypted;
4458
- } catch (err) {
4459
- throw new Error(
4460
- `Failed to decrypt media: ${err instanceof Error ? err.message : String(err)}`
4461
- );
4462
- }
4463
- }
4464
- function extractWecomContent(msg) {
4465
- const msgtype = String(msg.msgtype ?? "").toLowerCase();
4466
- if (msgtype === "text") {
4467
- const content = msg.text?.content;
4468
- return typeof content === "string" ? content : "";
4469
- }
4470
- if (msgtype === "voice") {
4471
- const content = msg.voice?.content;
4472
- return typeof content === "string" ? content : "[voice]";
4473
- }
4474
- if (msgtype === "mixed") {
4475
- const items = msg.mixed?.msg_item;
4476
- if (Array.isArray(items)) {
4477
- return items.map((item) => {
4478
- if (!item || typeof item !== "object") return "";
4479
- const typed = item;
4480
- const t = String(typed.msgtype ?? "").toLowerCase();
4481
- if (t === "text") return String(typed.text?.content ?? "");
4482
- if (t === "image") return `[image] ${String(typed.image?.url ?? "").trim()}`.trim();
4483
- return t ? `[${t}]` : "";
4484
- }).filter((part) => Boolean(part && part.trim())).join("\n");
4485
- }
4486
- return "[mixed]";
4487
- }
4488
- if (msgtype === "image") {
4489
- const url = String(msg.image?.url ?? "").trim();
4490
- return url ? `[image] ${url}` : "[image]";
4491
- }
4492
- if (msgtype === "file") {
4493
- const url = String(msg.file?.url ?? "").trim();
4494
- return url ? `[file] ${url}` : "[file]";
4495
- }
4496
- if (msgtype === "event") {
4497
- const eventtype = String(msg.event?.eventtype ?? "").trim();
4498
- return eventtype ? `[event] ${eventtype}` : "[event]";
4589
+ p = decodeURIComponent(p);
4590
+ } catch {
4499
4591
  }
4500
- if (msgtype === "stream") {
4501
- const id = String(msg.stream?.id ?? "").trim();
4502
- return id ? `[stream_refresh] ${id}` : "[stream_refresh]";
4592
+ if (p.startsWith("~/") || p === "~") {
4593
+ p = path3.join(os2.homedir(), p.slice(1));
4594
+ } else if (p.startsWith("~")) ;
4595
+ if (!path3.isAbsolute(p)) {
4596
+ p = path3.resolve(process.cwd(), p);
4503
4597
  }
4504
- return msgtype ? `[${msgtype}]` : "";
4598
+ return p;
4505
4599
  }
4506
- function resolveSenderId(msg) {
4507
- const userid = msg.from?.userid?.trim();
4508
- return userid || "unknown";
4600
+ function stripTitleFromUrl(value) {
4601
+ const trimmed = value.trim();
4602
+ const match = trimmed.match(/^(\S+)\s+["'][^"']*["']\s*$/);
4603
+ return match ? match[1] : trimmed;
4509
4604
  }
4510
- function resolveChatType(msg) {
4511
- return msg.chattype === "group" ? "group" : "direct";
4605
+ function getExtension(filePath) {
4606
+ const ext = path3.extname(filePath).toLowerCase();
4607
+ return ext.startsWith(".") ? ext.slice(1) : ext;
4512
4608
  }
4513
- function resolveChatId(msg, senderId, chatType) {
4514
- if (chatType === "group") {
4515
- return msg.chatid?.trim() || "unknown";
4609
+ function isNonImageFilePath(filePath) {
4610
+ const ext = getExtension(filePath);
4611
+ return ext ? NON_IMAGE_EXTENSIONS.has(ext) : false;
4612
+ }
4613
+ function detectMediaType(filePath) {
4614
+ const ext = getExtension(filePath);
4615
+ if (IMAGE_EXTENSIONS.has(ext)) return "image";
4616
+ if (AUDIO_EXTENSIONS.has(ext)) return "audio";
4617
+ if (VIDEO_EXTENSIONS.has(ext)) return "video";
4618
+ return "file";
4619
+ }
4620
+ function createExtractedMedia(source, sourceKind, options) {
4621
+ const isHttp = isHttpUrl(source);
4622
+ const isLocal = !isHttp && isLocalReference(source);
4623
+ const cleanSource = stripTitleFromUrl(source);
4624
+ let localPath;
4625
+ let fileName;
4626
+ if (isLocal) {
4627
+ localPath = normalizeLocalPath(cleanSource);
4628
+ fileName = path3.basename(localPath);
4629
+ } else if (isHttp) {
4630
+ try {
4631
+ const url = new URL(cleanSource);
4632
+ fileName = path3.basename(url.pathname) || void 0;
4633
+ } catch {
4634
+ }
4516
4635
  }
4517
- return senderId;
4636
+ const type = detectMediaType(fileName || cleanSource);
4637
+ return {
4638
+ source: cleanSource,
4639
+ localPath,
4640
+ type,
4641
+ isLocal,
4642
+ isHttp,
4643
+ fileName,
4644
+ sourceKind
4645
+ };
4518
4646
  }
4519
- async function dispatchWecomMessage(params) {
4520
- const { cfg, account, msg, core, hooks } = params;
4521
- const safeCfg = cfg ?? {};
4522
- const logger = createLogger("wecom", { log: params.log, error: params.error });
4523
- const chatType = resolveChatType(msg);
4524
- const senderId = resolveSenderId(msg);
4525
- const chatId = resolveChatId(msg, senderId, chatType);
4526
- const accountConfig = account?.config ?? {};
4527
- if (chatType === "group") {
4528
- const groupPolicy = resolveGroupPolicy(accountConfig);
4529
- const groupAllowFrom = resolveGroupAllowFrom(accountConfig);
4530
- resolveRequireMention(accountConfig);
4531
- const policyResult = checkGroupPolicy({
4532
- groupPolicy,
4533
- conversationId: chatId,
4534
- groupAllowFrom});
4535
- if (!policyResult.allowed) {
4536
- logger.debug(`policy rejected: ${policyResult.reason}`);
4537
- return;
4647
+ function extractMediaFromText(text, options = {}) {
4648
+ const {
4649
+ removeFromText = true,
4650
+ checkExists = false,
4651
+ existsSync: existsSync4,
4652
+ parseMediaLines = false,
4653
+ parseMarkdownImages = true,
4654
+ parseHtmlImages = true,
4655
+ parseBarePaths = true,
4656
+ parseMarkdownLinks = true
4657
+ } = options;
4658
+ const images = [];
4659
+ const files = [];
4660
+ const seenSources = /* @__PURE__ */ new Set();
4661
+ let result = text;
4662
+ const addMedia = (media) => {
4663
+ const key = media.localPath || media.source;
4664
+ if (seenSources.has(key)) return false;
4665
+ if (checkExists && media.isLocal && media.localPath) {
4666
+ const exists = existsSync4 ? existsSync4(media.localPath) : fs3.existsSync(media.localPath);
4667
+ if (!exists) return false;
4668
+ }
4669
+ seenSources.add(key);
4670
+ if (media.type === "image") {
4671
+ images.push(media);
4672
+ } else {
4673
+ files.push(media);
4538
4674
  }
4539
- } else {
4540
- const dmPolicyRaw = accountConfig.dmPolicy ?? "pairing";
4541
- if (dmPolicyRaw === "disabled") {
4542
- logger.debug("dmPolicy=disabled, skipping dispatch");
4543
- return;
4675
+ return true;
4676
+ };
4677
+ if (parseMediaLines) {
4678
+ const lines = result.split("\n");
4679
+ const keptLines = [];
4680
+ for (const line of lines) {
4681
+ const trimmedStart = line.trimStart();
4682
+ if (!trimmedStart.startsWith(MEDIA_LINE_PREFIX)) {
4683
+ keptLines.push(line);
4684
+ continue;
4685
+ }
4686
+ const payload = trimmedStart.slice(MEDIA_LINE_PREFIX.length).trim();
4687
+ if (!payload) {
4688
+ keptLines.push(line);
4689
+ continue;
4690
+ }
4691
+ const candidates = splitMediaLineCandidates(payload);
4692
+ let addedAny = false;
4693
+ for (const raw of candidates) {
4694
+ const candidate = stripTitleFromUrl(cleanMediaLineCandidate(raw));
4695
+ if (!candidate) continue;
4696
+ if (!isHttpUrl(candidate) && !isLocalReference(candidate)) {
4697
+ continue;
4698
+ }
4699
+ const media = createExtractedMedia(candidate, "bare");
4700
+ if (addMedia(media)) {
4701
+ addedAny = true;
4702
+ }
4703
+ }
4704
+ if (!addedAny || !removeFromText) {
4705
+ keptLines.push(line);
4706
+ }
4544
4707
  }
4545
- const allowFrom = resolveAllowFrom(accountConfig);
4546
- const policyResult = checkDmPolicy({
4547
- dmPolicy: dmPolicyRaw,
4548
- senderId,
4549
- allowFrom
4708
+ if (removeFromText) {
4709
+ result = keptLines.join("\n");
4710
+ }
4711
+ }
4712
+ const replacements = [];
4713
+ const applyReplacements = () => {
4714
+ if (replacements.length === 0) return;
4715
+ replacements.sort((a, b) => b.start - a.start);
4716
+ for (const { start, end, replacement } of replacements) {
4717
+ result = result.slice(0, start) + replacement + result.slice(end);
4718
+ }
4719
+ replacements.length = 0;
4720
+ };
4721
+ if (parseMarkdownImages) {
4722
+ const linkedMatches = [...text.matchAll(MARKDOWN_LINKED_IMAGE_RE)];
4723
+ for (const match of linkedMatches) {
4724
+ const [fullMatch, _alt, imgSrc] = match;
4725
+ const media = createExtractedMedia(imgSrc, "markdown");
4726
+ if (media.type === "image") {
4727
+ addMedia(media);
4728
+ if (removeFromText && match.index !== void 0) {
4729
+ replacements.push({
4730
+ start: match.index,
4731
+ end: match.index + fullMatch.length,
4732
+ replacement: ""
4733
+ });
4734
+ }
4735
+ }
4736
+ }
4737
+ applyReplacements();
4738
+ }
4739
+ if (parseMarkdownImages) {
4740
+ const mdMatches = [...result.matchAll(MARKDOWN_IMAGE_RE)];
4741
+ for (const match of mdMatches) {
4742
+ const [fullMatch, _alt, src] = match;
4743
+ const media = createExtractedMedia(src, "markdown");
4744
+ if (media.type === "image") {
4745
+ addMedia(media);
4746
+ if (removeFromText && match.index !== void 0) {
4747
+ replacements.push({
4748
+ start: match.index,
4749
+ end: match.index + fullMatch.length,
4750
+ replacement: ""
4751
+ });
4752
+ }
4753
+ }
4754
+ }
4755
+ applyReplacements();
4756
+ }
4757
+ if (parseHtmlImages) {
4758
+ const htmlMatches = [...result.matchAll(HTML_IMAGE_RE)];
4759
+ for (const match of htmlMatches) {
4760
+ const [fullMatch, src1, src2, src3] = match;
4761
+ const src = src1 || src2 || src3;
4762
+ if (src) {
4763
+ const media = createExtractedMedia(src, "html");
4764
+ if (media.type === "image") {
4765
+ addMedia(media);
4766
+ if (removeFromText && match.index !== void 0) {
4767
+ replacements.push({
4768
+ start: match.index,
4769
+ end: match.index + fullMatch.length,
4770
+ replacement: ""
4771
+ });
4772
+ }
4773
+ }
4774
+ }
4775
+ }
4776
+ applyReplacements();
4777
+ }
4778
+ if (parseMarkdownLinks) {
4779
+ MARKDOWN_LINK_RE.lastIndex = 0;
4780
+ const linkMatches = [...result.matchAll(MARKDOWN_LINK_RE)];
4781
+ for (const match of linkMatches) {
4782
+ const [fullMatch, _label, rawPath] = match;
4783
+ const idx = match.index ?? 0;
4784
+ if (idx > 0 && result[idx - 1] === "!") continue;
4785
+ if (!isLocalReference(rawPath)) continue;
4786
+ const media = createExtractedMedia(rawPath, "markdown");
4787
+ if (media.type !== "image" && isNonImageFilePath(media.localPath || rawPath)) {
4788
+ if (addMedia(media)) {
4789
+ if (removeFromText && match.index !== void 0) {
4790
+ const fileName = media.fileName || path3.basename(rawPath);
4791
+ replacements.push({
4792
+ start: match.index,
4793
+ end: match.index + fullMatch.length,
4794
+ replacement: `[\u6587\u4EF6: ${fileName}]`
4795
+ });
4796
+ }
4797
+ }
4798
+ }
4799
+ }
4800
+ applyReplacements();
4801
+ }
4802
+ if (parseBarePaths && parseMarkdownImages) {
4803
+ BARE_IMAGE_PATH_RE.lastIndex = 0;
4804
+ const bareImageMatches = [...result.matchAll(BARE_IMAGE_PATH_RE)];
4805
+ const newBareImageMatches = bareImageMatches.filter((m) => {
4806
+ const idx = m.index ?? 0;
4807
+ const before = result.slice(Math.max(0, idx - 10), idx);
4808
+ return !before.includes("](");
4550
4809
  });
4551
- if (!policyResult.allowed) {
4552
- logger.debug(`policy rejected: ${policyResult.reason}`);
4553
- return;
4810
+ for (const match of newBareImageMatches) {
4811
+ const [fullMatch, rawPath] = match;
4812
+ const media = createExtractedMedia(rawPath, "bare");
4813
+ if (media.type === "image") {
4814
+ addMedia(media);
4815
+ if (removeFromText && match.index !== void 0) {
4816
+ replacements.push({
4817
+ start: match.index,
4818
+ end: match.index + fullMatch.length,
4819
+ replacement: ""
4820
+ });
4821
+ }
4822
+ }
4823
+ }
4824
+ applyReplacements();
4825
+ }
4826
+ if (parseBarePaths && parseMarkdownLinks) {
4827
+ BARE_FILE_PATH_RE.lastIndex = 0;
4828
+ const bareFileMatches = [...result.matchAll(BARE_FILE_PATH_RE)];
4829
+ for (const match of bareFileMatches) {
4830
+ const [fullMatch, rawPath] = match;
4831
+ const media = createExtractedMedia(rawPath, "bare");
4832
+ if (media.type !== "image") {
4833
+ if (addMedia(media)) {
4834
+ if (removeFromText && match.index !== void 0) {
4835
+ const fileName = media.fileName || path3.basename(rawPath);
4836
+ replacements.push({
4837
+ start: match.index,
4838
+ end: match.index + fullMatch.length,
4839
+ replacement: `[\u6587\u4EF6: ${fileName}]`
4840
+ });
4841
+ }
4842
+ }
4843
+ }
4554
4844
  }
4845
+ applyReplacements();
4555
4846
  }
4556
- const channel = core.channel;
4557
- if (!channel?.routing?.resolveAgentRoute || !channel.reply?.dispatchReplyWithBufferedBlockDispatcher) {
4558
- logger.debug("core routing or buffered dispatcher missing, skipping dispatch");
4559
- return;
4847
+ if (removeFromText) {
4848
+ result = result.replace(/\n{3,}/g, "\n\n").trim();
4560
4849
  }
4561
- const route = channel.routing.resolveAgentRoute({
4562
- cfg: safeCfg,
4850
+ return {
4851
+ text: result,
4852
+ images,
4853
+ files,
4854
+ all: [...images, ...files]
4855
+ };
4856
+ }
4857
+
4858
+ // ../../node_modules/.pnpm/@clack+core@1.0.1/node_modules/@clack/core/dist/index.mjs
4859
+ var import_picocolors = __toESM(require_picocolors());
4860
+ var import_sisteransi = __toESM(require_src());
4861
+ function B(t, e2, s) {
4862
+ if (!s.some((u) => !u.disabled)) return t;
4863
+ const i = t + e2, r = Math.max(s.length - 1, 0), n = i < 0 ? r : i > r ? 0 : i;
4864
+ return s[n].disabled ? B(n, e2 < 0 ? -1 : 1, s) : n;
4865
+ }
4866
+ var at = (t) => t === 161 || t === 164 || t === 167 || t === 168 || t === 170 || t === 173 || t === 174 || t >= 176 && t <= 180 || t >= 182 && t <= 186 || t >= 188 && t <= 191 || t === 198 || t === 208 || t === 215 || t === 216 || t >= 222 && t <= 225 || t === 230 || t >= 232 && t <= 234 || t === 236 || t === 237 || t === 240 || t === 242 || t === 243 || t >= 247 && t <= 250 || t === 252 || t === 254 || t === 257 || t === 273 || t === 275 || t === 283 || t === 294 || t === 295 || t === 299 || t >= 305 && t <= 307 || t === 312 || t >= 319 && t <= 322 || t === 324 || t >= 328 && t <= 331 || t === 333 || t === 338 || t === 339 || t === 358 || t === 359 || t === 363 || t === 462 || t === 464 || t === 466 || t === 468 || t === 470 || t === 472 || t === 474 || t === 476 || t === 593 || t === 609 || t === 708 || t === 711 || t >= 713 && t <= 715 || t === 717 || t === 720 || t >= 728 && t <= 731 || t === 733 || t === 735 || t >= 768 && t <= 879 || t >= 913 && t <= 929 || t >= 931 && t <= 937 || t >= 945 && t <= 961 || t >= 963 && t <= 969 || t === 1025 || t >= 1040 && t <= 1103 || t === 1105 || t === 8208 || t >= 8211 && t <= 8214 || t === 8216 || t === 8217 || t === 8220 || t === 8221 || t >= 8224 && t <= 8226 || t >= 8228 && t <= 8231 || t === 8240 || t === 8242 || t === 8243 || t === 8245 || t === 8251 || t === 8254 || t === 8308 || t === 8319 || t >= 8321 && t <= 8324 || t === 8364 || t === 8451 || t === 8453 || t === 8457 || t === 8467 || t === 8470 || t === 8481 || t === 8482 || t === 8486 || t === 8491 || t === 8531 || t === 8532 || t >= 8539 && t <= 8542 || t >= 8544 && t <= 8555 || t >= 8560 && t <= 8569 || t === 8585 || t >= 8592 && t <= 8601 || t === 8632 || t === 8633 || t === 8658 || t === 8660 || t === 8679 || t === 8704 || t === 8706 || t === 8707 || t === 8711 || t === 8712 || t === 8715 || t === 8719 || t === 8721 || t === 8725 || t === 8730 || t >= 8733 && t <= 8736 || t === 8739 || t === 8741 || t >= 8743 && t <= 8748 || t === 8750 || t >= 8756 && t <= 8759 || t === 8764 || t === 8765 || t === 8776 || t === 8780 || t === 8786 || t === 8800 || t === 8801 || t >= 8804 && t <= 8807 || t === 8810 || t === 8811 || t === 8814 || t === 8815 || t === 8834 || t === 8835 || t === 8838 || t === 8839 || t === 8853 || t === 8857 || t === 8869 || t === 8895 || t === 8978 || t >= 9312 && t <= 9449 || t >= 9451 && t <= 9547 || t >= 9552 && t <= 9587 || t >= 9600 && t <= 9615 || t >= 9618 && t <= 9621 || t === 9632 || t === 9633 || t >= 9635 && t <= 9641 || t === 9650 || t === 9651 || t === 9654 || t === 9655 || t === 9660 || t === 9661 || t === 9664 || t === 9665 || t >= 9670 && t <= 9672 || t === 9675 || t >= 9678 && t <= 9681 || t >= 9698 && t <= 9701 || t === 9711 || t === 9733 || t === 9734 || t === 9737 || t === 9742 || t === 9743 || t === 9756 || t === 9758 || t === 9792 || t === 9794 || t === 9824 || t === 9825 || t >= 9827 && t <= 9829 || t >= 9831 && t <= 9834 || t === 9836 || t === 9837 || t === 9839 || t === 9886 || t === 9887 || t === 9919 || t >= 9926 && t <= 9933 || t >= 9935 && t <= 9939 || t >= 9941 && t <= 9953 || t === 9955 || t === 9960 || t === 9961 || t >= 9963 && t <= 9969 || t === 9972 || t >= 9974 && t <= 9977 || t === 9979 || t === 9980 || t === 9982 || t === 9983 || t === 10045 || t >= 10102 && t <= 10111 || t >= 11094 && t <= 11097 || t >= 12872 && t <= 12879 || t >= 57344 && t <= 63743 || t >= 65024 && t <= 65039 || t === 65533 || t >= 127232 && t <= 127242 || t >= 127248 && t <= 127277 || t >= 127280 && t <= 127337 || t >= 127344 && t <= 127373 || t === 127375 || t === 127376 || t >= 127387 && t <= 127404 || t >= 917760 && t <= 917999 || t >= 983040 && t <= 1048573 || t >= 1048576 && t <= 1114109;
4867
+ var lt = (t) => t === 12288 || t >= 65281 && t <= 65376 || t >= 65504 && t <= 65510;
4868
+ var ht = (t) => t >= 4352 && t <= 4447 || t === 8986 || t === 8987 || t === 9001 || t === 9002 || t >= 9193 && t <= 9196 || t === 9200 || t === 9203 || t === 9725 || t === 9726 || t === 9748 || t === 9749 || t >= 9800 && t <= 9811 || t === 9855 || t === 9875 || t === 9889 || t === 9898 || t === 9899 || t === 9917 || t === 9918 || t === 9924 || t === 9925 || t === 9934 || t === 9940 || t === 9962 || t === 9970 || t === 9971 || t === 9973 || t === 9978 || t === 9981 || t === 9989 || t === 9994 || t === 9995 || t === 10024 || t === 10060 || t === 10062 || t >= 10067 && t <= 10069 || t === 10071 || t >= 10133 && t <= 10135 || t === 10160 || t === 10175 || t === 11035 || t === 11036 || t === 11088 || t === 11093 || t >= 11904 && t <= 11929 || t >= 11931 && t <= 12019 || t >= 12032 && t <= 12245 || t >= 12272 && t <= 12287 || t >= 12289 && t <= 12350 || t >= 12353 && t <= 12438 || t >= 12441 && t <= 12543 || t >= 12549 && t <= 12591 || t >= 12593 && t <= 12686 || t >= 12688 && t <= 12771 || t >= 12783 && t <= 12830 || t >= 12832 && t <= 12871 || t >= 12880 && t <= 19903 || t >= 19968 && t <= 42124 || t >= 42128 && t <= 42182 || t >= 43360 && t <= 43388 || t >= 44032 && t <= 55203 || t >= 63744 && t <= 64255 || t >= 65040 && t <= 65049 || t >= 65072 && t <= 65106 || t >= 65108 && t <= 65126 || t >= 65128 && t <= 65131 || t >= 94176 && t <= 94180 || t === 94192 || t === 94193 || t >= 94208 && t <= 100343 || t >= 100352 && t <= 101589 || t >= 101632 && t <= 101640 || t >= 110576 && t <= 110579 || t >= 110581 && t <= 110587 || t === 110589 || t === 110590 || t >= 110592 && t <= 110882 || t === 110898 || t >= 110928 && t <= 110930 || t === 110933 || t >= 110948 && t <= 110951 || t >= 110960 && t <= 111355 || t === 126980 || t === 127183 || t === 127374 || t >= 127377 && t <= 127386 || t >= 127488 && t <= 127490 || t >= 127504 && t <= 127547 || t >= 127552 && t <= 127560 || t === 127568 || t === 127569 || t >= 127584 && t <= 127589 || t >= 127744 && t <= 127776 || t >= 127789 && t <= 127797 || t >= 127799 && t <= 127868 || t >= 127870 && t <= 127891 || t >= 127904 && t <= 127946 || t >= 127951 && t <= 127955 || t >= 127968 && t <= 127984 || t === 127988 || t >= 127992 && t <= 128062 || t === 128064 || t >= 128066 && t <= 128252 || t >= 128255 && t <= 128317 || t >= 128331 && t <= 128334 || t >= 128336 && t <= 128359 || t === 128378 || t === 128405 || t === 128406 || t === 128420 || t >= 128507 && t <= 128591 || t >= 128640 && t <= 128709 || t === 128716 || t >= 128720 && t <= 128722 || t >= 128725 && t <= 128727 || t >= 128732 && t <= 128735 || t === 128747 || t === 128748 || t >= 128756 && t <= 128764 || t >= 128992 && t <= 129003 || t === 129008 || t >= 129292 && t <= 129338 || t >= 129340 && t <= 129349 || t >= 129351 && t <= 129535 || t >= 129648 && t <= 129660 || t >= 129664 && t <= 129672 || t >= 129680 && t <= 129725 || t >= 129727 && t <= 129733 || t >= 129742 && t <= 129755 || t >= 129760 && t <= 129768 || t >= 129776 && t <= 129784 || t >= 131072 && t <= 196605 || t >= 196608 && t <= 262141;
4869
+ var O = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y;
4870
+ var y = /[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y;
4871
+ var L = /\t{1,1000}/y;
4872
+ var P = /[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu;
4873
+ var M = /(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y;
4874
+ var ct = /\p{M}+/gu;
4875
+ var ft = { limit: 1 / 0, ellipsis: "" };
4876
+ var X = (t, e2 = {}, s = {}) => {
4877
+ const i = e2.limit ?? 1 / 0, r = e2.ellipsis ?? "", n = e2?.ellipsisWidth ?? (r ? X(r, ft, s).width : 0), u = s.ansiWidth ?? 0, a = s.controlWidth ?? 0, l = s.tabWidth ?? 8, E = s.ambiguousWidth ?? 1, g = s.emojiWidth ?? 2, m = s.fullWidthWidth ?? 2, A = s.regularWidth ?? 1, V2 = s.wideWidth ?? 2;
4878
+ let h = 0, o = 0, p = t.length, v = 0, F = false, d2 = p, b = Math.max(0, i - n), C2 = 0, w = 0, c = 0, f = 0;
4879
+ t: for (; ; ) {
4880
+ if (w > C2 || o >= p && o > h) {
4881
+ const ut2 = t.slice(C2, w) || t.slice(h, o);
4882
+ v = 0;
4883
+ for (const Y of ut2.replaceAll(ct, "")) {
4884
+ const $ = Y.codePointAt(0) || 0;
4885
+ if (lt($) ? f = m : ht($) ? f = V2 : E !== A && at($) ? f = E : f = A, c + f > b && (d2 = Math.min(d2, Math.max(C2, h) + v)), c + f > i) {
4886
+ F = true;
4887
+ break t;
4888
+ }
4889
+ v += Y.length, c += f;
4890
+ }
4891
+ C2 = w = 0;
4892
+ }
4893
+ if (o >= p) break;
4894
+ if (M.lastIndex = o, M.test(t)) {
4895
+ if (v = M.lastIndex - o, f = v * A, c + f > b && (d2 = Math.min(d2, o + Math.floor((b - c) / A))), c + f > i) {
4896
+ F = true;
4897
+ break;
4898
+ }
4899
+ c += f, C2 = h, w = o, o = h = M.lastIndex;
4900
+ continue;
4901
+ }
4902
+ if (O.lastIndex = o, O.test(t)) {
4903
+ if (c + u > b && (d2 = Math.min(d2, o)), c + u > i) {
4904
+ F = true;
4905
+ break;
4906
+ }
4907
+ c += u, C2 = h, w = o, o = h = O.lastIndex;
4908
+ continue;
4909
+ }
4910
+ if (y.lastIndex = o, y.test(t)) {
4911
+ if (v = y.lastIndex - o, f = v * a, c + f > b && (d2 = Math.min(d2, o + Math.floor((b - c) / a))), c + f > i) {
4912
+ F = true;
4913
+ break;
4914
+ }
4915
+ c += f, C2 = h, w = o, o = h = y.lastIndex;
4916
+ continue;
4917
+ }
4918
+ if (L.lastIndex = o, L.test(t)) {
4919
+ if (v = L.lastIndex - o, f = v * l, c + f > b && (d2 = Math.min(d2, o + Math.floor((b - c) / l))), c + f > i) {
4920
+ F = true;
4921
+ break;
4922
+ }
4923
+ c += f, C2 = h, w = o, o = h = L.lastIndex;
4924
+ continue;
4925
+ }
4926
+ if (P.lastIndex = o, P.test(t)) {
4927
+ if (c + g > b && (d2 = Math.min(d2, o)), c + g > i) {
4928
+ F = true;
4929
+ break;
4930
+ }
4931
+ c += g, C2 = h, w = o, o = h = P.lastIndex;
4932
+ continue;
4933
+ }
4934
+ o += 1;
4935
+ }
4936
+ return { width: F ? b : c, index: F ? d2 : p, truncated: F, ellipsed: F && i >= n };
4937
+ };
4938
+ var pt = { limit: 1 / 0, ellipsis: "", ellipsisWidth: 0 };
4939
+ var S = (t, e2 = {}) => X(t, pt, e2).width;
4940
+ var W = "\x1B";
4941
+ var Z = "\x9B";
4942
+ var Ft = 39;
4943
+ var j = "\x07";
4944
+ var Q = "[";
4945
+ var dt = "]";
4946
+ var tt = "m";
4947
+ var U = `${dt}8;;`;
4948
+ var et = new RegExp(`(?:\\${Q}(?<code>\\d+)m|\\${U}(?<uri>.*)${j})`, "y");
4949
+ var mt = (t) => {
4950
+ if (t >= 30 && t <= 37 || t >= 90 && t <= 97) return 39;
4951
+ if (t >= 40 && t <= 47 || t >= 100 && t <= 107) return 49;
4952
+ if (t === 1 || t === 2) return 22;
4953
+ if (t === 3) return 23;
4954
+ if (t === 4) return 24;
4955
+ if (t === 7) return 27;
4956
+ if (t === 8) return 28;
4957
+ if (t === 9) return 29;
4958
+ if (t === 0) return 0;
4959
+ };
4960
+ var st = (t) => `${W}${Q}${t}${tt}`;
4961
+ var it = (t) => `${W}${U}${t}${j}`;
4962
+ var gt = (t) => t.map((e2) => S(e2));
4963
+ var G = (t, e2, s) => {
4964
+ const i = e2[Symbol.iterator]();
4965
+ let r = false, n = false, u = t.at(-1), a = u === void 0 ? 0 : S(u), l = i.next(), E = i.next(), g = 0;
4966
+ for (; !l.done; ) {
4967
+ const m = l.value, A = S(m);
4968
+ a + A <= s ? t[t.length - 1] += m : (t.push(m), a = 0), (m === W || m === Z) && (r = true, n = e2.startsWith(U, g + 1)), r ? n ? m === j && (r = false, n = false) : m === tt && (r = false) : (a += A, a === s && !E.done && (t.push(""), a = 0)), l = E, E = i.next(), g += m.length;
4969
+ }
4970
+ u = t.at(-1), !a && u !== void 0 && u.length > 0 && t.length > 1 && (t[t.length - 2] += t.pop());
4971
+ };
4972
+ var vt = (t) => {
4973
+ const e2 = t.split(" ");
4974
+ let s = e2.length;
4975
+ for (; s > 0 && !(S(e2[s - 1]) > 0); ) s--;
4976
+ return s === e2.length ? t : e2.slice(0, s).join(" ") + e2.slice(s).join("");
4977
+ };
4978
+ var Et = (t, e2, s = {}) => {
4979
+ if (s.trim !== false && t.trim() === "") return "";
4980
+ let i = "", r, n;
4981
+ const u = t.split(" "), a = gt(u);
4982
+ let l = [""];
4983
+ for (const [h, o] of u.entries()) {
4984
+ s.trim !== false && (l[l.length - 1] = (l.at(-1) ?? "").trimStart());
4985
+ let p = S(l.at(-1) ?? "");
4986
+ if (h !== 0 && (p >= e2 && (s.wordWrap === false || s.trim === false) && (l.push(""), p = 0), (p > 0 || s.trim === false) && (l[l.length - 1] += " ", p++)), s.hard && a[h] > e2) {
4987
+ const v = e2 - p, F = 1 + Math.floor((a[h] - v - 1) / e2);
4988
+ Math.floor((a[h] - 1) / e2) < F && l.push(""), G(l, o, e2);
4989
+ continue;
4990
+ }
4991
+ if (p + a[h] > e2 && p > 0 && a[h] > 0) {
4992
+ if (s.wordWrap === false && p < e2) {
4993
+ G(l, o, e2);
4994
+ continue;
4995
+ }
4996
+ l.push("");
4997
+ }
4998
+ if (p + a[h] > e2 && s.wordWrap === false) {
4999
+ G(l, o, e2);
5000
+ continue;
5001
+ }
5002
+ l[l.length - 1] += o;
5003
+ }
5004
+ s.trim !== false && (l = l.map((h) => vt(h)));
5005
+ const E = l.join(`
5006
+ `), g = E[Symbol.iterator]();
5007
+ let m = g.next(), A = g.next(), V2 = 0;
5008
+ for (; !m.done; ) {
5009
+ const h = m.value, o = A.value;
5010
+ if (i += h, h === W || h === Z) {
5011
+ et.lastIndex = V2 + 1;
5012
+ const F = et.exec(E)?.groups;
5013
+ if (F?.code !== void 0) {
5014
+ const d2 = Number.parseFloat(F.code);
5015
+ r = d2 === Ft ? void 0 : d2;
5016
+ } else F?.uri !== void 0 && (n = F.uri.length === 0 ? void 0 : F.uri);
5017
+ }
5018
+ const p = r ? mt(r) : void 0;
5019
+ o === `
5020
+ ` ? (n && (i += it("")), r && p && (i += st(p))) : h === `
5021
+ ` && (r && p && (i += st(r)), n && (i += it(n))), V2 += h.length, m = A, A = g.next();
5022
+ }
5023
+ return i;
5024
+ };
5025
+ function K(t, e2, s) {
5026
+ return String(t).normalize().replaceAll(`\r
5027
+ `, `
5028
+ `).split(`
5029
+ `).map((i) => Et(i, e2, s)).join(`
5030
+ `);
5031
+ }
5032
+ var At = ["up", "down", "left", "right", "space", "enter", "cancel"];
5033
+ var _ = { actions: new Set(At), aliases: /* @__PURE__ */ new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["", "cancel"], ["escape", "cancel"]]), withGuide: true };
5034
+ function H(t, e2) {
5035
+ if (typeof t == "string") return _.aliases.get(t) === e2;
5036
+ for (const s of t) if (s !== void 0 && H(s, e2)) return true;
5037
+ return false;
5038
+ }
5039
+ function _t(t, e2) {
5040
+ if (t === e2) return;
5041
+ const s = t.split(`
5042
+ `), i = e2.split(`
5043
+ `), r = Math.max(s.length, i.length), n = [];
5044
+ for (let u = 0; u < r; u++) s[u] !== i[u] && n.push(u);
5045
+ return { lines: n, numLinesBefore: s.length, numLinesAfter: i.length, numLines: r };
5046
+ }
5047
+ globalThis.process.platform.startsWith("win");
5048
+ var z = /* @__PURE__ */ Symbol("clack:cancel");
5049
+ function Ct(t) {
5050
+ return t === z;
5051
+ }
5052
+ function T(t, e2) {
5053
+ const s = t;
5054
+ s.isTTY && s.setRawMode(e2);
5055
+ }
5056
+ var rt = (t) => "columns" in t && typeof t.columns == "number" ? t.columns : 80;
5057
+ var nt = (t) => "rows" in t && typeof t.rows == "number" ? t.rows : 20;
5058
+ function xt(t, e2, s, i = s) {
5059
+ const r = rt(t ?? stdout);
5060
+ return K(e2, r - s.length, { hard: true, trim: false }).split(`
5061
+ `).map((n, u) => `${u === 0 ? i : s}${n}`).join(`
5062
+ `);
5063
+ }
5064
+ var x = class {
5065
+ input;
5066
+ output;
5067
+ _abortSignal;
5068
+ rl;
5069
+ opts;
5070
+ _render;
5071
+ _track = false;
5072
+ _prevFrame = "";
5073
+ _subscribers = /* @__PURE__ */ new Map();
5074
+ _cursor = 0;
5075
+ state = "initial";
5076
+ error = "";
5077
+ value;
5078
+ userInput = "";
5079
+ constructor(e2, s = true) {
5080
+ const { input: i = stdin, output: r = stdout, render: n, signal: u, ...a } = e2;
5081
+ this.opts = a, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = n.bind(this), this._track = s, this._abortSignal = u, this.input = i, this.output = r;
5082
+ }
5083
+ unsubscribe() {
5084
+ this._subscribers.clear();
5085
+ }
5086
+ setSubscriber(e2, s) {
5087
+ const i = this._subscribers.get(e2) ?? [];
5088
+ i.push(s), this._subscribers.set(e2, i);
5089
+ }
5090
+ on(e2, s) {
5091
+ this.setSubscriber(e2, { cb: s });
5092
+ }
5093
+ once(e2, s) {
5094
+ this.setSubscriber(e2, { cb: s, once: true });
5095
+ }
5096
+ emit(e2, ...s) {
5097
+ const i = this._subscribers.get(e2) ?? [], r = [];
5098
+ for (const n of i) n.cb(...s), n.once && r.push(() => i.splice(i.indexOf(n), 1));
5099
+ for (const n of r) n();
5100
+ }
5101
+ prompt() {
5102
+ return new Promise((e2) => {
5103
+ if (this._abortSignal) {
5104
+ if (this._abortSignal.aborted) return this.state = "cancel", this.close(), e2(z);
5105
+ this._abortSignal.addEventListener("abort", () => {
5106
+ this.state = "cancel", this.close();
5107
+ }, { once: true });
5108
+ }
5109
+ this.rl = ot.createInterface({ input: this.input, tabSize: 2, prompt: "", escapeCodeTimeout: 50, terminal: true }), this.rl.prompt(), this.opts.initialUserInput !== void 0 && this._setUserInput(this.opts.initialUserInput, true), this.input.on("keypress", this.onKeypress), T(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
5110
+ this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), T(this.input, false), e2(this.value);
5111
+ }), this.once("cancel", () => {
5112
+ this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), T(this.input, false), e2(z);
5113
+ });
5114
+ });
5115
+ }
5116
+ _isActionKey(e2, s) {
5117
+ return e2 === " ";
5118
+ }
5119
+ _setValue(e2) {
5120
+ this.value = e2, this.emit("value", this.value);
5121
+ }
5122
+ _setUserInput(e2, s) {
5123
+ this.userInput = e2 ?? "", this.emit("userInput", this.userInput), s && this._track && this.rl && (this.rl.write(this.userInput), this._cursor = this.rl.cursor);
5124
+ }
5125
+ _clearUserInput() {
5126
+ this.rl?.write(null, { ctrl: true, name: "u" }), this._setUserInput("");
5127
+ }
5128
+ onKeypress(e2, s) {
5129
+ if (this._track && s.name !== "return" && (s.name && this._isActionKey(e2, s) && this.rl?.write(null, { ctrl: true, name: "h" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), s?.name && (!this._track && _.aliases.has(s.name) && this.emit("cursor", _.aliases.get(s.name)), _.actions.has(s.name) && this.emit("cursor", s.name)), e2 && (e2.toLowerCase() === "y" || e2.toLowerCase() === "n") && this.emit("confirm", e2.toLowerCase() === "y"), this.emit("key", e2?.toLowerCase(), s), s?.name === "return") {
5130
+ if (this.opts.validate) {
5131
+ const i = this.opts.validate(this.value);
5132
+ i && (this.error = i instanceof Error ? i.message : i, this.state = "error", this.rl?.write(this.userInput));
5133
+ }
5134
+ this.state !== "error" && (this.state = "submit");
5135
+ }
5136
+ H([e2, s?.name, s?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
5137
+ }
5138
+ close() {
5139
+ this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
5140
+ `), T(this.input, false), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();
5141
+ }
5142
+ restoreCursor() {
5143
+ const e2 = K(this._prevFrame, process.stdout.columns, { hard: true, trim: false }).split(`
5144
+ `).length - 1;
5145
+ this.output.write(import_sisteransi.cursor.move(-999, e2 * -1));
5146
+ }
5147
+ render() {
5148
+ const e2 = K(this._render(this) ?? "", process.stdout.columns, { hard: true, trim: false });
5149
+ if (e2 !== this._prevFrame) {
5150
+ if (this.state === "initial") this.output.write(import_sisteransi.cursor.hide);
5151
+ else {
5152
+ const s = _t(this._prevFrame, e2), i = nt(this.output);
5153
+ if (this.restoreCursor(), s) {
5154
+ const r = Math.max(0, s.numLinesAfter - i), n = Math.max(0, s.numLinesBefore - i);
5155
+ let u = s.lines.find((a) => a >= r);
5156
+ if (u === void 0) {
5157
+ this._prevFrame = e2;
5158
+ return;
5159
+ }
5160
+ if (s.lines.length === 1) {
5161
+ this.output.write(import_sisteransi.cursor.move(0, u - n)), this.output.write(import_sisteransi.erase.lines(1));
5162
+ const a = e2.split(`
5163
+ `);
5164
+ this.output.write(a[u]), this._prevFrame = e2, this.output.write(import_sisteransi.cursor.move(0, a.length - u - 1));
5165
+ return;
5166
+ } else if (s.lines.length > 1) {
5167
+ if (r < n) u = r;
5168
+ else {
5169
+ const l = u - n;
5170
+ l > 0 && this.output.write(import_sisteransi.cursor.move(0, l));
5171
+ }
5172
+ this.output.write(import_sisteransi.erase.down());
5173
+ const a = e2.split(`
5174
+ `).slice(u);
5175
+ this.output.write(a.join(`
5176
+ `)), this._prevFrame = e2;
5177
+ return;
5178
+ }
5179
+ }
5180
+ this.output.write(import_sisteransi.erase.down());
5181
+ }
5182
+ this.output.write(e2), this.state === "initial" && (this.state = "active"), this._prevFrame = e2;
5183
+ }
5184
+ }
5185
+ };
5186
+ var kt = class extends x {
5187
+ get cursor() {
5188
+ return this.value ? 0 : 1;
5189
+ }
5190
+ get _value() {
5191
+ return this.cursor === 0;
5192
+ }
5193
+ constructor(e2) {
5194
+ super(e2, false), this.value = !!e2.initialValue, this.on("userInput", () => {
5195
+ this.value = this._value;
5196
+ }), this.on("confirm", (s) => {
5197
+ this.output.write(import_sisteransi.cursor.move(0, -1)), this.value = s, this.state = "submit", this.close();
5198
+ }), this.on("cursor", () => {
5199
+ this.value = !this.value;
5200
+ });
5201
+ }
5202
+ };
5203
+ var Wt = class extends x {
5204
+ options;
5205
+ cursor = 0;
5206
+ get _selectedValue() {
5207
+ return this.options[this.cursor];
5208
+ }
5209
+ changeValue() {
5210
+ this.value = this._selectedValue.value;
5211
+ }
5212
+ constructor(e2) {
5213
+ super(e2, false), this.options = e2.options;
5214
+ const s = this.options.findIndex(({ value: r }) => r === e2.initialValue), i = s === -1 ? 0 : s;
5215
+ this.cursor = this.options[i].disabled ? B(i, 1, this.options) : i, this.changeValue(), this.on("cursor", (r) => {
5216
+ switch (r) {
5217
+ case "left":
5218
+ case "up":
5219
+ this.cursor = B(this.cursor, -1, this.options);
5220
+ break;
5221
+ case "down":
5222
+ case "right":
5223
+ this.cursor = B(this.cursor, 1, this.options);
5224
+ break;
5225
+ }
5226
+ this.changeValue();
5227
+ });
5228
+ }
5229
+ };
5230
+ var $t = class extends x {
5231
+ get userInputWithCursor() {
5232
+ if (this.state === "submit") return this.userInput;
5233
+ const e2 = this.userInput;
5234
+ if (this.cursor >= e2.length) return `${this.userInput}\u2588`;
5235
+ const s = e2.slice(0, this.cursor), [i, ...r] = e2.slice(this.cursor);
5236
+ return `${s}${import_picocolors.default.inverse(i)}${r.join("")}`;
5237
+ }
5238
+ get cursor() {
5239
+ return this._cursor;
5240
+ }
5241
+ constructor(e2) {
5242
+ super({ ...e2, initialUserInput: e2.initialUserInput ?? e2.initialValue }), this.on("userInput", (s) => {
5243
+ this._setValue(s);
5244
+ }), this.on("finalize", () => {
5245
+ this.value || (this.value = e2.defaultValue), this.value === void 0 && (this.value = "");
5246
+ });
5247
+ }
5248
+ };
5249
+
5250
+ // ../../node_modules/.pnpm/@clack+prompts@1.0.1/node_modules/@clack/prompts/dist/index.mjs
5251
+ var import_picocolors2 = __toESM(require_picocolors());
5252
+ __toESM(require_src());
5253
+ function me() {
5254
+ return N2.platform !== "win32" ? N2.env.TERM !== "linux" : !!N2.env.CI || !!N2.env.WT_SESSION || !!N2.env.TERMINUS_SUBLIME || N2.env.ConEmuTask === "{cmd::Cmder}" || N2.env.TERM_PROGRAM === "Terminus-Sublime" || N2.env.TERM_PROGRAM === "vscode" || N2.env.TERM === "xterm-256color" || N2.env.TERM === "alacritty" || N2.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
5255
+ }
5256
+ var et2 = me();
5257
+ var C = (t, r) => et2 ? t : r;
5258
+ var Rt = C("\u25C6", "*");
5259
+ var dt2 = C("\u25A0", "x");
5260
+ var $t2 = C("\u25B2", "x");
5261
+ var V = C("\u25C7", "o");
5262
+ var ht2 = C("\u250C", "T");
5263
+ var d = C("\u2502", "|");
5264
+ var x2 = C("\u2514", "\u2014");
5265
+ var Q2 = C("\u25CF", ">");
5266
+ var H2 = C("\u25CB", " ");
5267
+ var rt2 = C("\u2500", "-");
5268
+ var mt2 = C("\u256E", "+");
5269
+ var Wt2 = C("\u251C", "+");
5270
+ var pt2 = C("\u256F", "+");
5271
+ var W2 = (t) => {
5272
+ switch (t) {
5273
+ case "initial":
5274
+ case "active":
5275
+ return import_picocolors2.default.cyan(Rt);
5276
+ case "cancel":
5277
+ return import_picocolors2.default.red(dt2);
5278
+ case "error":
5279
+ return import_picocolors2.default.yellow($t2);
5280
+ case "submit":
5281
+ return import_picocolors2.default.green(V);
5282
+ }
5283
+ };
5284
+ var vt2 = (t) => {
5285
+ switch (t) {
5286
+ case "initial":
5287
+ case "active":
5288
+ return import_picocolors2.default.cyan(d);
5289
+ case "cancel":
5290
+ return import_picocolors2.default.red(d);
5291
+ case "error":
5292
+ return import_picocolors2.default.yellow(d);
5293
+ case "submit":
5294
+ return import_picocolors2.default.green(d);
5295
+ }
5296
+ };
5297
+ var pe = (t) => t === 161 || t === 164 || t === 167 || t === 168 || t === 170 || t === 173 || t === 174 || t >= 176 && t <= 180 || t >= 182 && t <= 186 || t >= 188 && t <= 191 || t === 198 || t === 208 || t === 215 || t === 216 || t >= 222 && t <= 225 || t === 230 || t >= 232 && t <= 234 || t === 236 || t === 237 || t === 240 || t === 242 || t === 243 || t >= 247 && t <= 250 || t === 252 || t === 254 || t === 257 || t === 273 || t === 275 || t === 283 || t === 294 || t === 295 || t === 299 || t >= 305 && t <= 307 || t === 312 || t >= 319 && t <= 322 || t === 324 || t >= 328 && t <= 331 || t === 333 || t === 338 || t === 339 || t === 358 || t === 359 || t === 363 || t === 462 || t === 464 || t === 466 || t === 468 || t === 470 || t === 472 || t === 474 || t === 476 || t === 593 || t === 609 || t === 708 || t === 711 || t >= 713 && t <= 715 || t === 717 || t === 720 || t >= 728 && t <= 731 || t === 733 || t === 735 || t >= 768 && t <= 879 || t >= 913 && t <= 929 || t >= 931 && t <= 937 || t >= 945 && t <= 961 || t >= 963 && t <= 969 || t === 1025 || t >= 1040 && t <= 1103 || t === 1105 || t === 8208 || t >= 8211 && t <= 8214 || t === 8216 || t === 8217 || t === 8220 || t === 8221 || t >= 8224 && t <= 8226 || t >= 8228 && t <= 8231 || t === 8240 || t === 8242 || t === 8243 || t === 8245 || t === 8251 || t === 8254 || t === 8308 || t === 8319 || t >= 8321 && t <= 8324 || t === 8364 || t === 8451 || t === 8453 || t === 8457 || t === 8467 || t === 8470 || t === 8481 || t === 8482 || t === 8486 || t === 8491 || t === 8531 || t === 8532 || t >= 8539 && t <= 8542 || t >= 8544 && t <= 8555 || t >= 8560 && t <= 8569 || t === 8585 || t >= 8592 && t <= 8601 || t === 8632 || t === 8633 || t === 8658 || t === 8660 || t === 8679 || t === 8704 || t === 8706 || t === 8707 || t === 8711 || t === 8712 || t === 8715 || t === 8719 || t === 8721 || t === 8725 || t === 8730 || t >= 8733 && t <= 8736 || t === 8739 || t === 8741 || t >= 8743 && t <= 8748 || t === 8750 || t >= 8756 && t <= 8759 || t === 8764 || t === 8765 || t === 8776 || t === 8780 || t === 8786 || t === 8800 || t === 8801 || t >= 8804 && t <= 8807 || t === 8810 || t === 8811 || t === 8814 || t === 8815 || t === 8834 || t === 8835 || t === 8838 || t === 8839 || t === 8853 || t === 8857 || t === 8869 || t === 8895 || t === 8978 || t >= 9312 && t <= 9449 || t >= 9451 && t <= 9547 || t >= 9552 && t <= 9587 || t >= 9600 && t <= 9615 || t >= 9618 && t <= 9621 || t === 9632 || t === 9633 || t >= 9635 && t <= 9641 || t === 9650 || t === 9651 || t === 9654 || t === 9655 || t === 9660 || t === 9661 || t === 9664 || t === 9665 || t >= 9670 && t <= 9672 || t === 9675 || t >= 9678 && t <= 9681 || t >= 9698 && t <= 9701 || t === 9711 || t === 9733 || t === 9734 || t === 9737 || t === 9742 || t === 9743 || t === 9756 || t === 9758 || t === 9792 || t === 9794 || t === 9824 || t === 9825 || t >= 9827 && t <= 9829 || t >= 9831 && t <= 9834 || t === 9836 || t === 9837 || t === 9839 || t === 9886 || t === 9887 || t === 9919 || t >= 9926 && t <= 9933 || t >= 9935 && t <= 9939 || t >= 9941 && t <= 9953 || t === 9955 || t === 9960 || t === 9961 || t >= 9963 && t <= 9969 || t === 9972 || t >= 9974 && t <= 9977 || t === 9979 || t === 9980 || t === 9982 || t === 9983 || t === 10045 || t >= 10102 && t <= 10111 || t >= 11094 && t <= 11097 || t >= 12872 && t <= 12879 || t >= 57344 && t <= 63743 || t >= 65024 && t <= 65039 || t === 65533 || t >= 127232 && t <= 127242 || t >= 127248 && t <= 127277 || t >= 127280 && t <= 127337 || t >= 127344 && t <= 127373 || t === 127375 || t === 127376 || t >= 127387 && t <= 127404 || t >= 917760 && t <= 917999 || t >= 983040 && t <= 1048573 || t >= 1048576 && t <= 1114109;
5298
+ var ge = (t) => t === 12288 || t >= 65281 && t <= 65376 || t >= 65504 && t <= 65510;
5299
+ var fe = (t) => t >= 4352 && t <= 4447 || t === 8986 || t === 8987 || t === 9001 || t === 9002 || t >= 9193 && t <= 9196 || t === 9200 || t === 9203 || t === 9725 || t === 9726 || t === 9748 || t === 9749 || t >= 9800 && t <= 9811 || t === 9855 || t === 9875 || t === 9889 || t === 9898 || t === 9899 || t === 9917 || t === 9918 || t === 9924 || t === 9925 || t === 9934 || t === 9940 || t === 9962 || t === 9970 || t === 9971 || t === 9973 || t === 9978 || t === 9981 || t === 9989 || t === 9994 || t === 9995 || t === 10024 || t === 10060 || t === 10062 || t >= 10067 && t <= 10069 || t === 10071 || t >= 10133 && t <= 10135 || t === 10160 || t === 10175 || t === 11035 || t === 11036 || t === 11088 || t === 11093 || t >= 11904 && t <= 11929 || t >= 11931 && t <= 12019 || t >= 12032 && t <= 12245 || t >= 12272 && t <= 12287 || t >= 12289 && t <= 12350 || t >= 12353 && t <= 12438 || t >= 12441 && t <= 12543 || t >= 12549 && t <= 12591 || t >= 12593 && t <= 12686 || t >= 12688 && t <= 12771 || t >= 12783 && t <= 12830 || t >= 12832 && t <= 12871 || t >= 12880 && t <= 19903 || t >= 19968 && t <= 42124 || t >= 42128 && t <= 42182 || t >= 43360 && t <= 43388 || t >= 44032 && t <= 55203 || t >= 63744 && t <= 64255 || t >= 65040 && t <= 65049 || t >= 65072 && t <= 65106 || t >= 65108 && t <= 65126 || t >= 65128 && t <= 65131 || t >= 94176 && t <= 94180 || t === 94192 || t === 94193 || t >= 94208 && t <= 100343 || t >= 100352 && t <= 101589 || t >= 101632 && t <= 101640 || t >= 110576 && t <= 110579 || t >= 110581 && t <= 110587 || t === 110589 || t === 110590 || t >= 110592 && t <= 110882 || t === 110898 || t >= 110928 && t <= 110930 || t === 110933 || t >= 110948 && t <= 110951 || t >= 110960 && t <= 111355 || t === 126980 || t === 127183 || t === 127374 || t >= 127377 && t <= 127386 || t >= 127488 && t <= 127490 || t >= 127504 && t <= 127547 || t >= 127552 && t <= 127560 || t === 127568 || t === 127569 || t >= 127584 && t <= 127589 || t >= 127744 && t <= 127776 || t >= 127789 && t <= 127797 || t >= 127799 && t <= 127868 || t >= 127870 && t <= 127891 || t >= 127904 && t <= 127946 || t >= 127951 && t <= 127955 || t >= 127968 && t <= 127984 || t === 127988 || t >= 127992 && t <= 128062 || t === 128064 || t >= 128066 && t <= 128252 || t >= 128255 && t <= 128317 || t >= 128331 && t <= 128334 || t >= 128336 && t <= 128359 || t === 128378 || t === 128405 || t === 128406 || t === 128420 || t >= 128507 && t <= 128591 || t >= 128640 && t <= 128709 || t === 128716 || t >= 128720 && t <= 128722 || t >= 128725 && t <= 128727 || t >= 128732 && t <= 128735 || t === 128747 || t === 128748 || t >= 128756 && t <= 128764 || t >= 128992 && t <= 129003 || t === 129008 || t >= 129292 && t <= 129338 || t >= 129340 && t <= 129349 || t >= 129351 && t <= 129535 || t >= 129648 && t <= 129660 || t >= 129664 && t <= 129672 || t >= 129680 && t <= 129725 || t >= 129727 && t <= 129733 || t >= 129742 && t <= 129755 || t >= 129760 && t <= 129768 || t >= 129776 && t <= 129784 || t >= 131072 && t <= 196605 || t >= 196608 && t <= 262141;
5300
+ var At2 = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y;
5301
+ var it2 = /[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y;
5302
+ var nt2 = /\t{1,1000}/y;
5303
+ var wt = /[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu;
5304
+ var at2 = /(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y;
5305
+ var Fe = /\p{M}+/gu;
5306
+ var ye = { limit: 1 / 0, ellipsis: "" };
5307
+ var jt = (t, r = {}, s = {}) => {
5308
+ const i = r.limit ?? 1 / 0, a = r.ellipsis ?? "", o = r?.ellipsisWidth ?? (a ? jt(a, ye, s).width : 0), u = s.ansiWidth ?? 0, l = s.controlWidth ?? 0, n = s.tabWidth ?? 8, c = s.ambiguousWidth ?? 1, g = s.emojiWidth ?? 2, F = s.fullWidthWidth ?? 2, p = s.regularWidth ?? 1, E = s.wideWidth ?? 2;
5309
+ let $ = 0, m = 0, h = t.length, y2 = 0, f = false, v = h, S2 = Math.max(0, i - o), I2 = 0, B2 = 0, A = 0, w = 0;
5310
+ t: for (; ; ) {
5311
+ if (B2 > I2 || m >= h && m > $) {
5312
+ const _2 = t.slice(I2, B2) || t.slice($, m);
5313
+ y2 = 0;
5314
+ for (const D2 of _2.replaceAll(Fe, "")) {
5315
+ const T2 = D2.codePointAt(0) || 0;
5316
+ if (ge(T2) ? w = F : fe(T2) ? w = E : c !== p && pe(T2) ? w = c : w = p, A + w > S2 && (v = Math.min(v, Math.max(I2, $) + y2)), A + w > i) {
5317
+ f = true;
5318
+ break t;
5319
+ }
5320
+ y2 += D2.length, A += w;
5321
+ }
5322
+ I2 = B2 = 0;
5323
+ }
5324
+ if (m >= h) break;
5325
+ if (at2.lastIndex = m, at2.test(t)) {
5326
+ if (y2 = at2.lastIndex - m, w = y2 * p, A + w > S2 && (v = Math.min(v, m + Math.floor((S2 - A) / p))), A + w > i) {
5327
+ f = true;
5328
+ break;
5329
+ }
5330
+ A += w, I2 = $, B2 = m, m = $ = at2.lastIndex;
5331
+ continue;
5332
+ }
5333
+ if (At2.lastIndex = m, At2.test(t)) {
5334
+ if (A + u > S2 && (v = Math.min(v, m)), A + u > i) {
5335
+ f = true;
5336
+ break;
5337
+ }
5338
+ A += u, I2 = $, B2 = m, m = $ = At2.lastIndex;
5339
+ continue;
5340
+ }
5341
+ if (it2.lastIndex = m, it2.test(t)) {
5342
+ if (y2 = it2.lastIndex - m, w = y2 * l, A + w > S2 && (v = Math.min(v, m + Math.floor((S2 - A) / l))), A + w > i) {
5343
+ f = true;
5344
+ break;
5345
+ }
5346
+ A += w, I2 = $, B2 = m, m = $ = it2.lastIndex;
5347
+ continue;
5348
+ }
5349
+ if (nt2.lastIndex = m, nt2.test(t)) {
5350
+ if (y2 = nt2.lastIndex - m, w = y2 * n, A + w > S2 && (v = Math.min(v, m + Math.floor((S2 - A) / n))), A + w > i) {
5351
+ f = true;
5352
+ break;
5353
+ }
5354
+ A += w, I2 = $, B2 = m, m = $ = nt2.lastIndex;
5355
+ continue;
5356
+ }
5357
+ if (wt.lastIndex = m, wt.test(t)) {
5358
+ if (A + g > S2 && (v = Math.min(v, m)), A + g > i) {
5359
+ f = true;
5360
+ break;
5361
+ }
5362
+ A += g, I2 = $, B2 = m, m = $ = wt.lastIndex;
5363
+ continue;
5364
+ }
5365
+ m += 1;
5366
+ }
5367
+ return { width: f ? S2 : A, index: f ? v : h, truncated: f, ellipsed: f && i >= o };
5368
+ };
5369
+ var Ee = { limit: 1 / 0, ellipsis: "", ellipsisWidth: 0 };
5370
+ var M2 = (t, r = {}) => jt(t, Ee, r).width;
5371
+ var ot2 = "\x1B";
5372
+ var Gt = "\x9B";
5373
+ var ve = 39;
5374
+ var Ct2 = "\x07";
5375
+ var kt2 = "[";
5376
+ var Ae = "]";
5377
+ var Vt2 = "m";
5378
+ var St = `${Ae}8;;`;
5379
+ var Ht = new RegExp(`(?:\\${kt2}(?<code>\\d+)m|\\${St}(?<uri>.*)${Ct2})`, "y");
5380
+ var we = (t) => {
5381
+ if (t >= 30 && t <= 37 || t >= 90 && t <= 97) return 39;
5382
+ if (t >= 40 && t <= 47 || t >= 100 && t <= 107) return 49;
5383
+ if (t === 1 || t === 2) return 22;
5384
+ if (t === 3) return 23;
5385
+ if (t === 4) return 24;
5386
+ if (t === 7) return 27;
5387
+ if (t === 8) return 28;
5388
+ if (t === 9) return 29;
5389
+ if (t === 0) return 0;
5390
+ };
5391
+ var Ut = (t) => `${ot2}${kt2}${t}${Vt2}`;
5392
+ var Kt = (t) => `${ot2}${St}${t}${Ct2}`;
5393
+ var Ce = (t) => t.map((r) => M2(r));
5394
+ var It2 = (t, r, s) => {
5395
+ const i = r[Symbol.iterator]();
5396
+ let a = false, o = false, u = t.at(-1), l = u === void 0 ? 0 : M2(u), n = i.next(), c = i.next(), g = 0;
5397
+ for (; !n.done; ) {
5398
+ const F = n.value, p = M2(F);
5399
+ l + p <= s ? t[t.length - 1] += F : (t.push(F), l = 0), (F === ot2 || F === Gt) && (a = true, o = r.startsWith(St, g + 1)), a ? o ? F === Ct2 && (a = false, o = false) : F === Vt2 && (a = false) : (l += p, l === s && !c.done && (t.push(""), l = 0)), n = c, c = i.next(), g += F.length;
5400
+ }
5401
+ u = t.at(-1), !l && u !== void 0 && u.length > 0 && t.length > 1 && (t[t.length - 2] += t.pop());
5402
+ };
5403
+ var Se = (t) => {
5404
+ const r = t.split(" ");
5405
+ let s = r.length;
5406
+ for (; s > 0 && !(M2(r[s - 1]) > 0); ) s--;
5407
+ return s === r.length ? t : r.slice(0, s).join(" ") + r.slice(s).join("");
5408
+ };
5409
+ var Ie = (t, r, s = {}) => {
5410
+ if (s.trim !== false && t.trim() === "") return "";
5411
+ let i = "", a, o;
5412
+ const u = t.split(" "), l = Ce(u);
5413
+ let n = [""];
5414
+ for (const [$, m] of u.entries()) {
5415
+ s.trim !== false && (n[n.length - 1] = (n.at(-1) ?? "").trimStart());
5416
+ let h = M2(n.at(-1) ?? "");
5417
+ if ($ !== 0 && (h >= r && (s.wordWrap === false || s.trim === false) && (n.push(""), h = 0), (h > 0 || s.trim === false) && (n[n.length - 1] += " ", h++)), s.hard && l[$] > r) {
5418
+ const y2 = r - h, f = 1 + Math.floor((l[$] - y2 - 1) / r);
5419
+ Math.floor((l[$] - 1) / r) < f && n.push(""), It2(n, m, r);
5420
+ continue;
5421
+ }
5422
+ if (h + l[$] > r && h > 0 && l[$] > 0) {
5423
+ if (s.wordWrap === false && h < r) {
5424
+ It2(n, m, r);
5425
+ continue;
5426
+ }
5427
+ n.push("");
5428
+ }
5429
+ if (h + l[$] > r && s.wordWrap === false) {
5430
+ It2(n, m, r);
5431
+ continue;
5432
+ }
5433
+ n[n.length - 1] += m;
5434
+ }
5435
+ s.trim !== false && (n = n.map(($) => Se($)));
5436
+ const c = n.join(`
5437
+ `), g = c[Symbol.iterator]();
5438
+ let F = g.next(), p = g.next(), E = 0;
5439
+ for (; !F.done; ) {
5440
+ const $ = F.value, m = p.value;
5441
+ if (i += $, $ === ot2 || $ === Gt) {
5442
+ Ht.lastIndex = E + 1;
5443
+ const f = Ht.exec(c)?.groups;
5444
+ if (f?.code !== void 0) {
5445
+ const v = Number.parseFloat(f.code);
5446
+ a = v === ve ? void 0 : v;
5447
+ } else f?.uri !== void 0 && (o = f.uri.length === 0 ? void 0 : f.uri);
5448
+ }
5449
+ const h = a ? we(a) : void 0;
5450
+ m === `
5451
+ ` ? (o && (i += Kt("")), a && h && (i += Ut(h))) : $ === `
5452
+ ` && (a && h && (i += Ut(a)), o && (i += Kt(o))), E += $.length, F = p, p = g.next();
5453
+ }
5454
+ return i;
5455
+ };
5456
+ function J2(t, r, s) {
5457
+ return String(t).normalize().replaceAll(`\r
5458
+ `, `
5459
+ `).split(`
5460
+ `).map((i) => Ie(i, r, s)).join(`
5461
+ `);
5462
+ }
5463
+ var be = (t, r, s, i, a) => {
5464
+ let o = r, u = 0;
5465
+ for (let l = s; l < i; l++) {
5466
+ const n = t[l];
5467
+ if (o = o - n.length, u++, o <= a) break;
5468
+ }
5469
+ return { lineCount: o, removals: u };
5470
+ };
5471
+ var X2 = (t) => {
5472
+ const { cursor: r, options: s, style: i } = t, a = t.output ?? process.stdout, o = rt(a), u = t.columnPadding ?? 0, l = t.rowPadding ?? 4, n = o - u, c = nt(a), g = import_picocolors2.default.dim("..."), F = t.maxItems ?? Number.POSITIVE_INFINITY, p = Math.max(c - l, 0), E = Math.max(Math.min(F, p), 5);
5473
+ let $ = 0;
5474
+ r >= E - 3 && ($ = Math.max(Math.min(r - E + 3, s.length - E), 0));
5475
+ let m = E < s.length && $ > 0, h = E < s.length && $ + E < s.length;
5476
+ const y2 = Math.min($ + E, s.length), f = [];
5477
+ let v = 0;
5478
+ m && v++, h && v++;
5479
+ const S2 = $ + (m ? 1 : 0), I2 = y2 - (h ? 1 : 0);
5480
+ for (let A = S2; A < I2; A++) {
5481
+ const w = J2(i(s[A], A === r), n, { hard: true, trim: false }).split(`
5482
+ `);
5483
+ f.push(w), v += w.length;
5484
+ }
5485
+ if (v > p) {
5486
+ let A = 0, w = 0, _2 = v;
5487
+ const D2 = r - S2, T2 = (Y, L2) => be(f, _2, Y, L2, p);
5488
+ m ? ({ lineCount: _2, removals: A } = T2(0, D2), _2 > p && ({ lineCount: _2, removals: w } = T2(D2 + 1, f.length))) : ({ lineCount: _2, removals: w } = T2(D2 + 1, f.length), _2 > p && ({ lineCount: _2, removals: A } = T2(0, D2))), A > 0 && (m = true, f.splice(0, A)), w > 0 && (h = true, f.splice(f.length - w, w));
5489
+ }
5490
+ const B2 = [];
5491
+ m && B2.push(g);
5492
+ for (const A of f) for (const w of A) B2.push(w);
5493
+ return h && B2.push(g), B2;
5494
+ };
5495
+ var Re = (t) => {
5496
+ const r = t.active ?? "Yes", s = t.inactive ?? "No";
5497
+ return new kt({ active: r, inactive: s, signal: t.signal, input: t.input, output: t.output, initialValue: t.initialValue ?? true, render() {
5498
+ const i = t.withGuide ?? _.withGuide, a = `${i ? `${import_picocolors2.default.gray(d)}
5499
+ ` : ""}${W2(this.state)} ${t.message}
5500
+ `, o = this.value ? r : s;
5501
+ switch (this.state) {
5502
+ case "submit": {
5503
+ const u = i ? `${import_picocolors2.default.gray(d)} ` : "";
5504
+ return `${a}${u}${import_picocolors2.default.dim(o)}`;
5505
+ }
5506
+ case "cancel": {
5507
+ const u = i ? `${import_picocolors2.default.gray(d)} ` : "";
5508
+ return `${a}${u}${import_picocolors2.default.strikethrough(import_picocolors2.default.dim(o))}${i ? `
5509
+ ${import_picocolors2.default.gray(d)}` : ""}`;
5510
+ }
5511
+ default: {
5512
+ const u = i ? `${import_picocolors2.default.cyan(d)} ` : "", l = i ? import_picocolors2.default.cyan(x2) : "";
5513
+ return `${a}${u}${this.value ? `${import_picocolors2.default.green(Q2)} ${r}` : `${import_picocolors2.default.dim(H2)} ${import_picocolors2.default.dim(r)}`}${t.vertical ? i ? `
5514
+ ${import_picocolors2.default.cyan(d)} ` : `
5515
+ ` : ` ${import_picocolors2.default.dim("/")} `}${this.value ? `${import_picocolors2.default.dim(H2)} ${import_picocolors2.default.dim(s)}` : `${import_picocolors2.default.green(Q2)} ${s}`}
5516
+ ${l}
5517
+ `;
5518
+ }
5519
+ }
5520
+ } }).prompt();
5521
+ };
5522
+ var Ne = (t = "", r) => {
5523
+ (process.stdout).write(`${import_picocolors2.default.gray(x2)} ${import_picocolors2.default.red(t)}
5524
+
5525
+ `);
5526
+ };
5527
+ var We = (t = "", r) => {
5528
+ (process.stdout).write(`${import_picocolors2.default.gray(ht2)} ${t}
5529
+ `);
5530
+ };
5531
+ var Le = (t = "", r) => {
5532
+ (process.stdout).write(`${import_picocolors2.default.gray(d)}
5533
+ ${import_picocolors2.default.gray(x2)} ${t}
5534
+
5535
+ `);
5536
+ };
5537
+ var Ge = (t) => import_picocolors2.default.dim(t);
5538
+ var ke = (t, r, s) => {
5539
+ const i = { hard: true, trim: false }, a = J2(t, r, i).split(`
5540
+ `), o = a.reduce((n, c) => Math.max(M2(c), n), 0), u = a.map(s).reduce((n, c) => Math.max(M2(c), n), 0), l = r - (u - o);
5541
+ return J2(t, l, i);
5542
+ };
5543
+ var Ve = (t = "", r = "", s) => {
5544
+ const i = N2.stdout, o = Ge, u = ["", ...ke(t, rt(i) - 6, o).split(`
5545
+ `).map(o), ""], l = M2(r), n = Math.max(u.reduce((p, E) => {
5546
+ const $ = M2(E);
5547
+ return $ > p ? $ : p;
5548
+ }, 0), l) + 2, c = u.map((p) => `${import_picocolors2.default.gray(d)} ${p}${" ".repeat(n - M2(p))}${import_picocolors2.default.gray(d)}`).join(`
5549
+ `), g = `${import_picocolors2.default.gray(d)}
5550
+ ` , F = Wt2 ;
5551
+ i.write(`${g}${import_picocolors2.default.green(V)} ${import_picocolors2.default.reset(r)} ${import_picocolors2.default.gray(rt2.repeat(Math.max(n - l - 1, 1)) + mt2)}
5552
+ ${c}
5553
+ ${import_picocolors2.default.gray(F + rt2.repeat(n + 2) + pt2)}
5554
+ `);
5555
+ };
5556
+ import_picocolors2.default.magenta;
5557
+ var lt2 = (t, r) => t.includes(`
5558
+ `) ? t.split(`
5559
+ `).map((s) => r(s)).join(`
5560
+ `) : r(t);
5561
+ var Je = (t) => {
5562
+ const r = (s, i) => {
5563
+ const a = s.label ?? String(s.value);
5564
+ switch (i) {
5565
+ case "disabled":
5566
+ return `${import_picocolors2.default.gray(H2)} ${lt2(a, import_picocolors2.default.gray)}${s.hint ? ` ${import_picocolors2.default.dim(`(${s.hint ?? "disabled"})`)}` : ""}`;
5567
+ case "selected":
5568
+ return `${lt2(a, import_picocolors2.default.dim)}`;
5569
+ case "active":
5570
+ return `${import_picocolors2.default.green(Q2)} ${a}${s.hint ? ` ${import_picocolors2.default.dim(`(${s.hint})`)}` : ""}`;
5571
+ case "cancelled":
5572
+ return `${lt2(a, (o) => import_picocolors2.default.strikethrough(import_picocolors2.default.dim(o)))}`;
5573
+ default:
5574
+ return `${import_picocolors2.default.dim(H2)} ${lt2(a, import_picocolors2.default.dim)}`;
5575
+ }
5576
+ };
5577
+ return new Wt({ options: t.options, signal: t.signal, input: t.input, output: t.output, initialValue: t.initialValue, render() {
5578
+ const s = t.withGuide ?? _.withGuide, i = `${W2(this.state)} `, a = `${vt2(this.state)} `, o = xt(t.output, t.message, a, i), u = `${s ? `${import_picocolors2.default.gray(d)}
5579
+ ` : ""}${o}
5580
+ `;
5581
+ switch (this.state) {
5582
+ case "submit": {
5583
+ const l = s ? `${import_picocolors2.default.gray(d)} ` : "", n = xt(t.output, r(this.options[this.cursor], "selected"), l);
5584
+ return `${u}${n}`;
5585
+ }
5586
+ case "cancel": {
5587
+ const l = s ? `${import_picocolors2.default.gray(d)} ` : "", n = xt(t.output, r(this.options[this.cursor], "cancelled"), l);
5588
+ return `${u}${n}${s ? `
5589
+ ${import_picocolors2.default.gray(d)}` : ""}`;
5590
+ }
5591
+ default: {
5592
+ const l = s ? `${import_picocolors2.default.cyan(d)} ` : "", n = s ? import_picocolors2.default.cyan(x2) : "", c = u.split(`
5593
+ `).length, g = s ? 2 : 1;
5594
+ return `${u}${l}${X2({ output: t.output, cursor: this.cursor, options: this.options, maxItems: t.maxItems, columnPadding: l.length, rowPadding: c + g, style: (F, p) => r(F, F.disabled ? "disabled" : p ? "active" : "inactive") }).join(`
5595
+ ${l}`)}
5596
+ ${n}
5597
+ `;
5598
+ }
5599
+ }
5600
+ } }).prompt();
5601
+ };
5602
+ `${import_picocolors2.default.gray(d)} `;
5603
+ var Ze = (t) => new $t({ validate: t.validate, placeholder: t.placeholder, defaultValue: t.defaultValue, initialValue: t.initialValue, output: t.output, signal: t.signal, input: t.input, render() {
5604
+ const r = t?.withGuide ?? _.withGuide, s = `${`${r ? `${import_picocolors2.default.gray(d)}
5605
+ ` : ""}${W2(this.state)} `}${t.message}
5606
+ `, i = t.placeholder ? import_picocolors2.default.inverse(t.placeholder[0]) + import_picocolors2.default.dim(t.placeholder.slice(1)) : import_picocolors2.default.inverse(import_picocolors2.default.hidden("_")), a = this.userInput ? this.userInputWithCursor : i, o = this.value ?? "";
5607
+ switch (this.state) {
5608
+ case "error": {
5609
+ const u = this.error ? ` ${import_picocolors2.default.yellow(this.error)}` : "", l = r ? `${import_picocolors2.default.yellow(d)} ` : "", n = r ? import_picocolors2.default.yellow(x2) : "";
5610
+ return `${s.trim()}
5611
+ ${l}${a}
5612
+ ${n}${u}
5613
+ `;
5614
+ }
5615
+ case "submit": {
5616
+ const u = o ? ` ${import_picocolors2.default.dim(o)}` : "", l = r ? import_picocolors2.default.gray(d) : "";
5617
+ return `${s}${l}${u}`;
5618
+ }
5619
+ case "cancel": {
5620
+ const u = o ? ` ${import_picocolors2.default.strikethrough(import_picocolors2.default.dim(o))}` : "", l = r ? import_picocolors2.default.gray(d) : "";
5621
+ return `${s}${l}${u}${o.trim() ? `
5622
+ ${l}` : ""}`;
5623
+ }
5624
+ default: {
5625
+ const u = r ? `${import_picocolors2.default.cyan(d)} ` : "", l = r ? import_picocolors2.default.cyan(x2) : "";
5626
+ return `${s}${u}${a}
5627
+ ${l}
5628
+ `;
5629
+ }
5630
+ }
5631
+ } }).prompt();
5632
+ var PROJECT_REPO = "https://github.com/BytePioneer-AI/moltbot-china";
5633
+ var GUIDES_BASE = "https://github.com/BytePioneer-AI/openclaw-china/tree/main/doc/guides";
5634
+ var OPENCLAW_HOME = join(homedir(), ".openclaw");
5635
+ var DEFAULT_PLUGIN_PATH = join(OPENCLAW_HOME, "extensions");
5636
+ var LEGACY_PLUGIN_PATH = join(OPENCLAW_HOME, "plugins");
5637
+ var CONFIG_FILE_PATH = join(OPENCLAW_HOME, "openclaw.json");
5638
+ var ANSI_RESET = "\x1B[0m";
5639
+ var ANSI_LINK = "\x1B[1;4;96m";
5640
+ var ANSI_BORDER = "\x1B[92m";
5641
+ var CHANNEL_ORDER = [
5642
+ "dingtalk",
5643
+ "qqbot",
5644
+ "wecom",
5645
+ "wecom-app",
5646
+ "feishu-china"
5647
+ ];
5648
+ var CHANNEL_DISPLAY_LABELS = {
5649
+ dingtalk: "DingTalk\uFF08\u9489\u9489\uFF09",
5650
+ "feishu-china": "Feishu\uFF08\u98DE\u4E66\uFF09",
5651
+ wecom: "WeCom\uFF08\u4F01\u4E1A\u5FAE\u4FE1-\u667A\u80FD\u673A\u5668\u4EBA\uFF09",
5652
+ "wecom-app": "WeCom App\uFF08\u81EA\u5EFA\u5E94\u7528-\u53EF\u63A5\u5165\u5FAE\u4FE1\uFF09",
5653
+ qqbot: "QQBot\uFF08QQ \u673A\u5668\u4EBA\uFF09"
5654
+ };
5655
+ var CHANNEL_GUIDE_LINKS = {
5656
+ dingtalk: `${GUIDES_BASE}/dingtalk/configuration.md`,
5657
+ "feishu-china": "https://github.com/BytePioneer-AI/openclaw-china/blob/main/README.md",
5658
+ wecom: `${GUIDES_BASE}/wecom/configuration.md`,
5659
+ "wecom-app": `${GUIDES_BASE}/wecom-app/configuration.md`,
5660
+ qqbot: `${GUIDES_BASE}/qqbot/configuration.md`
5661
+ };
5662
+ var CHINA_CLI_STATE_KEY = /* @__PURE__ */ Symbol.for("@openclaw-china/china-cli-state");
5663
+ var PromptCancelledError = class extends Error {
5664
+ constructor() {
5665
+ super("prompt-cancelled");
5666
+ }
5667
+ };
5668
+ function isChannelId(value) {
5669
+ return typeof value === "string" && CHANNEL_ORDER.includes(value);
5670
+ }
5671
+ function getChinaCliState() {
5672
+ const root = globalThis;
5673
+ const cached = root[CHINA_CLI_STATE_KEY];
5674
+ if (isRecord(cached)) {
5675
+ const channels = cached.channels;
5676
+ const cliRegistered = cached.cliRegistered;
5677
+ if (channels instanceof Set && typeof cliRegistered === "boolean") {
5678
+ return {
5679
+ channels,
5680
+ cliRegistered
5681
+ };
5682
+ }
5683
+ }
5684
+ const created = {
5685
+ channels: /* @__PURE__ */ new Set(),
5686
+ cliRegistered: false
5687
+ };
5688
+ root[CHINA_CLI_STATE_KEY] = created;
5689
+ return created;
5690
+ }
5691
+ function normalizeChannels(channels) {
5692
+ const selected = channels && channels.length > 0 ? channels : CHANNEL_ORDER;
5693
+ const unique = /* @__PURE__ */ new Set();
5694
+ for (const channelId of selected) {
5695
+ if (isChannelId(channelId)) {
5696
+ unique.add(channelId);
5697
+ }
5698
+ }
5699
+ return CHANNEL_ORDER.filter((channelId) => unique.has(channelId));
5700
+ }
5701
+ function getInstalledChannels(state) {
5702
+ return CHANNEL_ORDER.filter((channelId) => state.channels.has(channelId));
5703
+ }
5704
+ function guardCancel(value) {
5705
+ if (Ct(value)) {
5706
+ Ne("\u5DF2\u53D6\u6D88\u914D\u7F6E\u3002");
5707
+ throw new PromptCancelledError();
5708
+ }
5709
+ return value;
5710
+ }
5711
+ function warn(text) {
5712
+ stdout.write(`
5713
+ [warn] ${text}
5714
+ `);
5715
+ }
5716
+ function section(title) {
5717
+ stdout.write(`
5718
+ ${title}
5719
+ `);
5720
+ }
5721
+ function resolvePluginPath() {
5722
+ if (existsSync(DEFAULT_PLUGIN_PATH)) {
5723
+ return DEFAULT_PLUGIN_PATH;
5724
+ }
5725
+ if (existsSync(LEGACY_PLUGIN_PATH)) {
5726
+ return LEGACY_PLUGIN_PATH;
5727
+ }
5728
+ return DEFAULT_PLUGIN_PATH;
5729
+ }
5730
+ function renderReadyMessage() {
5731
+ return [
5732
+ `${ANSI_BORDER}\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${ANSI_RESET}`,
5733
+ " OpenClaw China Channels \u5DF2\u5C31\u7EEA!",
5734
+ `${ANSI_BORDER}\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${ANSI_RESET}`,
5735
+ "",
5736
+ "\u63D2\u4EF6\u8DEF\u5F84:",
5737
+ ` ${resolvePluginPath()}`,
5738
+ "",
5739
+ "\u914D\u7F6E\u6587\u4EF6:",
5740
+ ` ${CONFIG_FILE_PATH}`,
5741
+ "",
5742
+ "\u66F4\u65B0\u63D2\u4EF6:",
5743
+ " openclaw plugins update <plugin-id>",
5744
+ "",
5745
+ "\u9879\u76EE\u4ED3\u5E93:",
5746
+ ` ${ANSI_LINK}${PROJECT_REPO}${ANSI_RESET}`,
5747
+ "",
5748
+ "\u2B50 \u5982\u679C\u8FD9\u4E2A\u9879\u76EE\u5BF9\u4F60\u6709\u5E2E\u52A9\uFF0C\u8BF7\u7ED9\u6211\u4EEC\u4E00\u4E2A Star\uFF01\u2B50",
5749
+ "",
5750
+ "\u4E0B\u4E00\u6B65:",
5751
+ " openclaw gateway --port 18789 --verbose",
5752
+ ""
5753
+ ].join("\n");
5754
+ }
5755
+ function showReadyMessage() {
5756
+ stdout.write(`
5757
+ ${renderReadyMessage()}
5758
+ `);
5759
+ }
5760
+ function showGuideLink(channelId) {
5761
+ const url = CHANNEL_GUIDE_LINKS[channelId];
5762
+ Ve(`\u914D\u7F6E\u6587\u6863\uFF1A${url}`, "Docs");
5763
+ }
5764
+ function isRecord(value) {
5765
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5766
+ }
5767
+ function resolveWriteConfig(runtime2) {
5768
+ if (!isRecord(runtime2)) {
5769
+ return void 0;
5770
+ }
5771
+ const config = runtime2.config;
5772
+ if (!isRecord(config)) {
5773
+ return void 0;
5774
+ }
5775
+ if (typeof config.writeConfigFile !== "function") {
5776
+ return void 0;
5777
+ }
5778
+ return config.writeConfigFile;
5779
+ }
5780
+ function isCommandLike(value) {
5781
+ if (!isRecord(value)) {
5782
+ return false;
5783
+ }
5784
+ return typeof value.command === "function" && typeof value.description === "function" && typeof value.action === "function";
5785
+ }
5786
+ function toTrimmedString(value) {
5787
+ if (typeof value !== "string") {
5788
+ return void 0;
5789
+ }
5790
+ const trimmed = value.trim();
5791
+ return trimmed || void 0;
5792
+ }
5793
+ function hasNonEmptyString(value) {
5794
+ return typeof value === "string" && value.trim().length > 0;
5795
+ }
5796
+ function toBoolean(value, fallback) {
5797
+ return typeof value === "boolean" ? value : fallback;
5798
+ }
5799
+ function toNumber(value) {
5800
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
5801
+ }
5802
+ function cloneConfig(cfg) {
5803
+ try {
5804
+ return structuredClone(cfg);
5805
+ } catch {
5806
+ return JSON.parse(JSON.stringify(cfg));
5807
+ }
5808
+ }
5809
+ function getChannelConfig(cfg, channelId) {
5810
+ const channels = isRecord(cfg.channels) ? cfg.channels : {};
5811
+ const existing = channels[channelId];
5812
+ return isRecord(existing) ? existing : {};
5813
+ }
5814
+ function getPreferredAccountConfig(channelCfg) {
5815
+ const accounts = channelCfg.accounts;
5816
+ if (!isRecord(accounts)) {
5817
+ return void 0;
5818
+ }
5819
+ const defaultAccountId = toTrimmedString(channelCfg.defaultAccount);
5820
+ if (defaultAccountId) {
5821
+ const preferred = accounts[defaultAccountId];
5822
+ if (isRecord(preferred)) {
5823
+ return preferred;
5824
+ }
5825
+ }
5826
+ for (const value of Object.values(accounts)) {
5827
+ if (isRecord(value)) {
5828
+ return value;
5829
+ }
5830
+ }
5831
+ return void 0;
5832
+ }
5833
+ function hasTokenPair(channelCfg) {
5834
+ if (hasNonEmptyString(channelCfg.token) && hasNonEmptyString(channelCfg.encodingAESKey)) {
5835
+ return true;
5836
+ }
5837
+ const accountCfg = getPreferredAccountConfig(channelCfg);
5838
+ return Boolean(
5839
+ accountCfg && hasNonEmptyString(accountCfg.token) && hasNonEmptyString(accountCfg.encodingAESKey)
5840
+ );
5841
+ }
5842
+ function isChannelConfigured(cfg, channelId) {
5843
+ const channelCfg = getChannelConfig(cfg, channelId);
5844
+ switch (channelId) {
5845
+ case "dingtalk":
5846
+ return hasNonEmptyString(channelCfg.clientId) && hasNonEmptyString(channelCfg.clientSecret);
5847
+ case "feishu-china":
5848
+ return hasNonEmptyString(channelCfg.appId) && hasNonEmptyString(channelCfg.appSecret);
5849
+ case "qqbot":
5850
+ return hasNonEmptyString(channelCfg.appId) && hasNonEmptyString(channelCfg.clientSecret);
5851
+ case "wecom":
5852
+ case "wecom-app":
5853
+ return hasTokenPair(channelCfg);
5854
+ default:
5855
+ return false;
5856
+ }
5857
+ }
5858
+ function withConfiguredSuffix(cfg, channelId) {
5859
+ const base = CHANNEL_DISPLAY_LABELS[channelId];
5860
+ return isChannelConfigured(cfg, channelId) ? `${base}\uFF08\u5DF2\u914D\u7F6E\uFF09` : base;
5861
+ }
5862
+ function mergeChannelConfig(cfg, channelId, patch) {
5863
+ const channels = isRecord(cfg.channels) ? { ...cfg.channels } : {};
5864
+ const existing = getChannelConfig(cfg, channelId);
5865
+ channels[channelId] = {
5866
+ ...existing,
5867
+ ...patch,
5868
+ enabled: true
5869
+ };
5870
+ return {
5871
+ ...cfg,
5872
+ channels
5873
+ };
5874
+ }
5875
+ var SetupPrompter = class {
5876
+ async askText(params) {
5877
+ const { label, required = false, defaultValue } = params;
5878
+ while (true) {
5879
+ const value = String(
5880
+ guardCancel(
5881
+ await Ze({
5882
+ message: label,
5883
+ initialValue: defaultValue
5884
+ })
5885
+ )
5886
+ ).trim();
5887
+ if (value) {
5888
+ return value;
5889
+ }
5890
+ if (defaultValue) {
5891
+ return defaultValue;
5892
+ }
5893
+ if (!required) {
5894
+ return "";
5895
+ }
5896
+ warn("\u8BE5\u5B57\u6BB5\u4E3A\u5FC5\u586B\u9879\u3002");
5897
+ }
5898
+ }
5899
+ async askSecret(params) {
5900
+ const { label, existingValue, required = true } = params;
5901
+ return this.askText({
5902
+ label,
5903
+ required,
5904
+ defaultValue: existingValue
5905
+ });
5906
+ }
5907
+ async askConfirm(label, defaultValue = true) {
5908
+ return Boolean(
5909
+ guardCancel(
5910
+ await Re({
5911
+ message: label,
5912
+ initialValue: defaultValue
5913
+ })
5914
+ )
5915
+ );
5916
+ }
5917
+ async askNumber(params) {
5918
+ const { label, min, defaultValue } = params;
5919
+ while (true) {
5920
+ const raw = String(
5921
+ guardCancel(
5922
+ await Ze({
5923
+ message: label,
5924
+ initialValue: defaultValue !== void 0 ? String(defaultValue) : void 0
5925
+ })
5926
+ )
5927
+ ).trim();
5928
+ const parsed = Number.parseInt(raw, 10);
5929
+ if (Number.isFinite(parsed) && (min === void 0 || parsed >= min)) {
5930
+ return parsed;
5931
+ }
5932
+ warn(`\u8BF7\u8F93\u5165\u6709\u6548\u6574\u6570${min !== void 0 ? `\uFF08>= ${min}\uFF09` : ""}\u3002`);
5933
+ }
5934
+ }
5935
+ async askSelect(message, options, defaultValue) {
5936
+ const initial = options.some((opt) => opt.value === defaultValue) ? defaultValue : options[0]?.value;
5937
+ const selectOptions = options.map((option) => ({
5938
+ value: option.value,
5939
+ label: option.label
5940
+ }));
5941
+ return guardCancel(
5942
+ await Je({
5943
+ message,
5944
+ options: selectOptions,
5945
+ initialValue: initial
5946
+ })
5947
+ );
5948
+ }
5949
+ };
5950
+ async function configureDingtalk(prompter, cfg) {
5951
+ section("\u914D\u7F6E DingTalk\uFF08\u9489\u9489\uFF09");
5952
+ showGuideLink("dingtalk");
5953
+ const existing = getChannelConfig(cfg, "dingtalk");
5954
+ const clientId = await prompter.askText({
5955
+ label: "DingTalk clientId\uFF08AppKey\uFF09",
5956
+ defaultValue: toTrimmedString(existing.clientId),
5957
+ required: true
5958
+ });
5959
+ const clientSecret = await prompter.askSecret({
5960
+ label: "DingTalk clientSecret\uFF08AppSecret\uFF09",
5961
+ existingValue: toTrimmedString(existing.clientSecret),
5962
+ required: true
5963
+ });
5964
+ const enableAICard = await prompter.askConfirm(
5965
+ "\u542F\u7528 AI Card \u6D41\u5F0F\u56DE\u590D\uFF08\u63A8\u8350\u5173\u95ED\uFF0C\u4F7F\u7528\u975E\u6D41\u5F0F\uFF09",
5966
+ toBoolean(existing.enableAICard, false)
5967
+ );
5968
+ return mergeChannelConfig(cfg, "dingtalk", {
5969
+ clientId,
5970
+ clientSecret,
5971
+ enableAICard
5972
+ });
5973
+ }
5974
+ async function configureFeishu(prompter, cfg) {
5975
+ section("\u914D\u7F6E Feishu\uFF08\u98DE\u4E66\uFF09");
5976
+ showGuideLink("feishu-china");
5977
+ const existing = getChannelConfig(cfg, "feishu-china");
5978
+ const appId = await prompter.askText({
5979
+ label: "Feishu appId",
5980
+ defaultValue: toTrimmedString(existing.appId),
5981
+ required: true
5982
+ });
5983
+ const appSecret = await prompter.askSecret({
5984
+ label: "Feishu appSecret",
5985
+ existingValue: toTrimmedString(existing.appSecret),
5986
+ required: true
5987
+ });
5988
+ const sendMarkdownAsCard = await prompter.askConfirm(
5989
+ "\u4EE5\u5361\u7247\u5F62\u5F0F\u53D1\u9001 Markdown",
5990
+ toBoolean(existing.sendMarkdownAsCard, true)
5991
+ );
5992
+ return mergeChannelConfig(cfg, "feishu-china", {
5993
+ appId,
5994
+ appSecret,
5995
+ sendMarkdownAsCard
5996
+ });
5997
+ }
5998
+ async function configureWecom(prompter, cfg) {
5999
+ section("\u914D\u7F6E WeCom\uFF08\u4F01\u4E1A\u5FAE\u4FE1-\u667A\u80FD\u673A\u5668\u4EBA\uFF09");
6000
+ showGuideLink("wecom");
6001
+ const existing = getChannelConfig(cfg, "wecom");
6002
+ const webhookPath = await prompter.askText({
6003
+ label: "Webhook \u8DEF\u5F84\uFF08\u9700\u4E0E\u4F01\u4E1A\u5FAE\u4FE1\u540E\u53F0\u914D\u7F6E\u4E00\u81F4\uFF0C\u9ED8\u8BA4 /wecom\uFF09",
6004
+ defaultValue: toTrimmedString(existing.webhookPath) ?? "/wecom",
6005
+ required: true
6006
+ });
6007
+ const token = await prompter.askSecret({
6008
+ label: "WeCom token",
6009
+ existingValue: toTrimmedString(existing.token),
6010
+ required: true
6011
+ });
6012
+ const encodingAESKey = await prompter.askSecret({
6013
+ label: "WeCom encodingAESKey",
6014
+ existingValue: toTrimmedString(existing.encodingAESKey),
6015
+ required: true
6016
+ });
6017
+ return mergeChannelConfig(cfg, "wecom", {
6018
+ webhookPath,
6019
+ token,
6020
+ encodingAESKey
6021
+ });
6022
+ }
6023
+ async function configureWecomApp(prompter, cfg) {
6024
+ section("\u914D\u7F6E WeCom App\uFF08\u81EA\u5EFA\u5E94\u7528-\u53EF\u63A5\u5165\u5FAE\u4FE1\uFF09");
6025
+ showGuideLink("wecom-app");
6026
+ const existing = getChannelConfig(cfg, "wecom-app");
6027
+ const webhookPath = await prompter.askText({
6028
+ label: "Webhook \u8DEF\u5F84\uFF08\u9700\u4E0E\u4F01\u4E1A\u5FAE\u4FE1\u540E\u53F0\u914D\u7F6E\u4E00\u81F4\uFF0C\u9ED8\u8BA4 /wecom-app\uFF09",
6029
+ defaultValue: toTrimmedString(existing.webhookPath) ?? "/wecom-app",
6030
+ required: true
6031
+ });
6032
+ const token = await prompter.askSecret({
6033
+ label: "WeCom App token",
6034
+ existingValue: toTrimmedString(existing.token),
6035
+ required: true
6036
+ });
6037
+ const encodingAESKey = await prompter.askSecret({
6038
+ label: "WeCom App encodingAESKey",
6039
+ existingValue: toTrimmedString(existing.encodingAESKey),
6040
+ required: true
6041
+ });
6042
+ const patch = {
6043
+ webhookPath,
6044
+ token,
6045
+ encodingAESKey
6046
+ };
6047
+ const corpId = await prompter.askText({
6048
+ label: "corpId",
6049
+ defaultValue: toTrimmedString(existing.corpId),
6050
+ required: true
6051
+ });
6052
+ const corpSecret = await prompter.askSecret({
6053
+ label: "corpSecret",
6054
+ existingValue: toTrimmedString(existing.corpSecret),
6055
+ required: true
6056
+ });
6057
+ const agentId = await prompter.askNumber({
6058
+ label: "agentId",
6059
+ min: 1,
6060
+ defaultValue: toNumber(existing.agentId)
6061
+ });
6062
+ patch.corpId = corpId;
6063
+ patch.corpSecret = corpSecret;
6064
+ patch.agentId = agentId;
6065
+ return mergeChannelConfig(cfg, "wecom-app", patch);
6066
+ }
6067
+ async function configureQQBot(prompter, cfg) {
6068
+ section("\u914D\u7F6E QQBot\uFF08QQ \u673A\u5668\u4EBA\uFF09");
6069
+ showGuideLink("qqbot");
6070
+ const existing = getChannelConfig(cfg, "qqbot");
6071
+ const appId = await prompter.askText({
6072
+ label: "QQBot appId",
6073
+ defaultValue: toTrimmedString(existing.appId),
6074
+ required: true
6075
+ });
6076
+ const clientSecret = await prompter.askSecret({
6077
+ label: "QQBot clientSecret",
6078
+ existingValue: toTrimmedString(existing.clientSecret),
6079
+ required: true
6080
+ });
6081
+ const markdownSupport = await prompter.askConfirm(
6082
+ "\u542F\u7528 Markdown \u652F\u6301",
6083
+ toBoolean(existing.markdownSupport, false)
6084
+ );
6085
+ const replyFinalOnly = await prompter.askConfirm(
6086
+ "\u4EC5\u53D1\u9001\u6700\u7EC8\u56DE\u590D\uFF08\u5173\u95ED\u6D41\u5F0F\u5206\u7247\uFF09",
6087
+ toBoolean(existing.replyFinalOnly, false)
6088
+ );
6089
+ return mergeChannelConfig(cfg, "qqbot", {
6090
+ appId,
6091
+ clientSecret,
6092
+ markdownSupport,
6093
+ replyFinalOnly
6094
+ });
6095
+ }
6096
+ async function configureSingleChannel(channel, prompter, cfg) {
6097
+ switch (channel) {
6098
+ case "dingtalk":
6099
+ return configureDingtalk(prompter, cfg);
6100
+ case "feishu-china":
6101
+ return configureFeishu(prompter, cfg);
6102
+ case "wecom":
6103
+ return configureWecom(prompter, cfg);
6104
+ case "wecom-app":
6105
+ return configureWecomApp(prompter, cfg);
6106
+ case "qqbot":
6107
+ return configureQQBot(prompter, cfg);
6108
+ default:
6109
+ return cfg;
6110
+ }
6111
+ }
6112
+ async function runChinaSetup(params) {
6113
+ if (!stdin.isTTY || !stdout.isTTY) {
6114
+ params.logger.error?.("\u4EA4\u4E92\u5F0F\u914D\u7F6E\u9700\u8981\u5728 TTY \u7EC8\u7AEF\u4E2D\u8FD0\u884C\u3002");
6115
+ return;
6116
+ }
6117
+ const prompter = new SetupPrompter();
6118
+ const touched = /* @__PURE__ */ new Set();
6119
+ let next = cloneConfig(params.initialConfig);
6120
+ try {
6121
+ We("OpenClaw China \u914D\u7F6E\u5411\u5BFC");
6122
+ Ve(
6123
+ [
6124
+ "\u4F7F\u7528\u65B9\u5411\u952E\u9009\u62E9\uFF0C\u6309 Enter \u786E\u8BA4\u3002",
6125
+ `\u9879\u76EE\u4ED3\u5E93\uFF1A${ANSI_LINK}${PROJECT_REPO}${ANSI_RESET}`
6126
+ ].join("\n"),
6127
+ "\u6B22\u8FCE"
6128
+ );
6129
+ if (params.availableChannels.length === 0) {
6130
+ params.logger.error?.("\u672A\u68C0\u6D4B\u5230\u53EF\u914D\u7F6E\u7684 China \u6E20\u9053\u63D2\u4EF6\u3002");
6131
+ return;
6132
+ }
6133
+ const channelOptions = params.availableChannels.map((channelId, index) => ({
6134
+ key: index === 0 ? "recommended" : "",
6135
+ value: channelId,
6136
+ label: withConfiguredSuffix(next, channelId)
6137
+ }));
6138
+ const defaultChannel = channelOptions[0]?.value ?? "save";
6139
+ let continueLoop = true;
6140
+ while (continueLoop) {
6141
+ const selected = await prompter.askSelect(
6142
+ "\u8BF7\u9009\u62E9\u8981\u914D\u7F6E\u7684\u6E20\u9053",
6143
+ [
6144
+ ...channelOptions,
6145
+ { key: "", value: "save", label: "\u4FDD\u5B58\u5E76\u9000\u51FA" },
6146
+ { key: "", value: "cancel", label: "\u4E0D\u4FDD\u5B58\u5E76\u9000\u51FA" }
6147
+ ],
6148
+ defaultChannel
6149
+ );
6150
+ if (selected === "cancel") {
6151
+ Ne("\u5DF2\u53D6\u6D88\uFF0C\u672A\u5199\u5165\u4EFB\u4F55\u914D\u7F6E\u3002");
6152
+ return;
6153
+ }
6154
+ if (selected === "save") {
6155
+ break;
6156
+ }
6157
+ next = await configureSingleChannel(selected, prompter, next);
6158
+ touched.add(selected);
6159
+ Ve(`\u5DF2\u5B8C\u6210\uFF1A${CHANNEL_DISPLAY_LABELS[selected]}`, "\u5B8C\u6210");
6160
+ continueLoop = await prompter.askConfirm("\u7EE7\u7EED\u914D\u7F6E\u5176\u4ED6\u6E20\u9053", true);
6161
+ }
6162
+ if (touched.size === 0) {
6163
+ Ne("\u672A\u8FDB\u884C\u4EFB\u4F55\u4FEE\u6539\u3002");
6164
+ return;
6165
+ }
6166
+ Ve(
6167
+ `\u5DF2\u914D\u7F6E\u6E20\u9053\uFF1A${Array.from(touched).map((channelId) => CHANNEL_DISPLAY_LABELS[channelId]).join(", ")}`,
6168
+ "\u6458\u8981"
6169
+ );
6170
+ if (!params.writeConfig) {
6171
+ params.logger.error?.("\u65E0\u6CD5\u4FDD\u5B58\u914D\u7F6E\uFF1A\u5F53\u524D\u8FD0\u884C\u65F6\u672A\u63D0\u4F9B\u914D\u7F6E\u5199\u5165\u80FD\u529B\u3002");
6172
+ return;
6173
+ }
6174
+ await params.writeConfig(next);
6175
+ Le("\u914D\u7F6E\u5DF2\u4FDD\u5B58\u3002");
6176
+ showReadyMessage();
6177
+ } catch (err) {
6178
+ if (err instanceof PromptCancelledError) {
6179
+ return;
6180
+ }
6181
+ throw err;
6182
+ }
6183
+ }
6184
+ function registerChinaSetupCli(api, opts) {
6185
+ const state = getChinaCliState();
6186
+ for (const channelId of normalizeChannels(opts?.channels)) {
6187
+ state.channels.add(channelId);
6188
+ }
6189
+ if (state.cliRegistered || typeof api.registerCli !== "function") {
6190
+ return;
6191
+ }
6192
+ state.cliRegistered = true;
6193
+ const writeConfig = resolveWriteConfig(api.runtime);
6194
+ const fallbackLogger = {
6195
+ info: (message) => stdout.write(`${message}
6196
+ `),
6197
+ warn: (message) => warn(message),
6198
+ error: (message) => warn(message)
6199
+ };
6200
+ api.registerCli(
6201
+ (ctx) => {
6202
+ if (!isCommandLike(ctx.program)) {
6203
+ const logger = ctx.logger ?? api.logger ?? fallbackLogger;
6204
+ logger.error?.("\u65E0\u6CD5\u6CE8\u518C china \u547D\u4EE4\uFF1ACLI program \u5B9E\u4F8B\u65E0\u6548\u3002");
6205
+ return;
6206
+ }
6207
+ const root = ctx.program.command("china").description("OpenClaw China \u63D2\u4EF6\u547D\u4EE4");
6208
+ root.command("setup").description("\u4E2D\u56FD\u6E20\u9053\u4EA4\u4E92\u5F0F\u914D\u7F6E\u5411\u5BFC").action(async () => {
6209
+ const logger = ctx.logger ?? api.logger ?? fallbackLogger;
6210
+ const availableChannels = getInstalledChannels(state);
6211
+ await runChinaSetup({
6212
+ initialConfig: isRecord(ctx.config) ? ctx.config : {},
6213
+ writeConfig,
6214
+ logger,
6215
+ availableChannels
6216
+ });
6217
+ });
6218
+ root.command("about").description("\u663E\u793A\u9879\u76EE\u4FE1\u606F").action(() => {
6219
+ const installed = getInstalledChannels(state);
6220
+ We("OpenClaw China \u6E20\u9053\u63D2\u4EF6");
6221
+ Ve(
6222
+ installed.length > 0 ? `\u5F53\u524D\u5DF2\u5B89\u88C5\u6E20\u9053\uFF1A${installed.map((channelId) => CHANNEL_DISPLAY_LABELS[channelId]).join("\u3001")}` : "OpenClaw China \u6E20\u9053\u63D2\u4EF6",
6223
+ "\u5173\u4E8E"
6224
+ );
6225
+ Le(PROJECT_REPO);
6226
+ showReadyMessage();
6227
+ });
6228
+ },
6229
+ { commands: ["china"] }
6230
+ );
6231
+ }
6232
+ function decodeEncodingAESKey(encodingAESKey) {
6233
+ const trimmed = encodingAESKey.trim();
6234
+ if (!trimmed) throw new Error("encodingAESKey missing");
6235
+ const withPadding = trimmed.endsWith("=") ? trimmed : `${trimmed}=`;
6236
+ const key = Buffer.from(withPadding, "base64");
6237
+ if (key.length !== 32) {
6238
+ throw new Error(`invalid encodingAESKey (expected 32 bytes after base64 decode, got ${key.length})`);
6239
+ }
6240
+ return key;
6241
+ }
6242
+ var WECOM_PKCS7_BLOCK_SIZE = 32;
6243
+ function pkcs7Pad(buf, blockSize) {
6244
+ const mod = buf.length % blockSize;
6245
+ const pad = mod === 0 ? blockSize : blockSize - mod;
6246
+ return Buffer.concat([buf, Buffer.alloc(pad, pad)]);
6247
+ }
6248
+ function pkcs7Unpad(buf, blockSize) {
6249
+ if (buf.length === 0) throw new Error("invalid pkcs7 payload");
6250
+ const pad = buf[buf.length - 1];
6251
+ if (!pad || pad < 1 || pad > blockSize || pad > buf.length) {
6252
+ throw new Error("invalid pkcs7 padding");
6253
+ }
6254
+ for (let i = 1; i <= pad; i += 1) {
6255
+ if (buf[buf.length - i] !== pad) {
6256
+ throw new Error("invalid pkcs7 padding");
6257
+ }
6258
+ }
6259
+ return buf.subarray(0, buf.length - pad);
6260
+ }
6261
+ function sha1Hex(input2) {
6262
+ return crypto.createHash("sha1").update(input2).digest("hex");
6263
+ }
6264
+ function computeWecomMsgSignature(params) {
6265
+ const parts = [params.token, params.timestamp, params.nonce, params.encrypt].map((value) => String(value ?? "")).sort();
6266
+ return sha1Hex(parts.join(""));
6267
+ }
6268
+ function verifyWecomSignature(params) {
6269
+ const expected = computeWecomMsgSignature({
6270
+ token: params.token,
6271
+ timestamp: params.timestamp,
6272
+ nonce: params.nonce,
6273
+ encrypt: params.encrypt
6274
+ });
6275
+ return expected === params.signature;
6276
+ }
6277
+ function decryptWecomEncrypted(params) {
6278
+ const aesKey = decodeEncodingAESKey(params.encodingAESKey);
6279
+ const iv = aesKey.subarray(0, 16);
6280
+ const decipher = crypto.createDecipheriv("aes-256-cbc", aesKey, iv);
6281
+ decipher.setAutoPadding(false);
6282
+ const decryptedPadded = Buffer.concat([
6283
+ decipher.update(Buffer.from(params.encrypt, "base64")),
6284
+ decipher.final()
6285
+ ]);
6286
+ const decrypted = pkcs7Unpad(decryptedPadded, WECOM_PKCS7_BLOCK_SIZE);
6287
+ if (decrypted.length < 20) {
6288
+ throw new Error(`invalid decrypted payload (expected at least 20 bytes, got ${decrypted.length})`);
6289
+ }
6290
+ const msgLen = decrypted.readUInt32BE(16);
6291
+ const msgStart = 20;
6292
+ const msgEnd = msgStart + msgLen;
6293
+ if (msgEnd > decrypted.length) {
6294
+ throw new Error(`invalid decrypted msg length (msgEnd=${msgEnd}, payloadLength=${decrypted.length})`);
6295
+ }
6296
+ const msg = decrypted.subarray(msgStart, msgEnd).toString("utf8");
6297
+ const receiveId = params.receiveId ?? "";
6298
+ if (receiveId) {
6299
+ const trailing = decrypted.subarray(msgEnd).toString("utf8");
6300
+ if (trailing !== receiveId) {
6301
+ throw new Error(`receiveId mismatch (expected "${receiveId}", got "${trailing}")`);
6302
+ }
6303
+ }
6304
+ return msg;
6305
+ }
6306
+ function encryptWecomPlaintext(params) {
6307
+ const aesKey = decodeEncodingAESKey(params.encodingAESKey);
6308
+ const iv = aesKey.subarray(0, 16);
6309
+ const random16 = crypto.randomBytes(16);
6310
+ const msg = Buffer.from(params.plaintext ?? "", "utf8");
6311
+ const msgLen = Buffer.alloc(4);
6312
+ msgLen.writeUInt32BE(msg.length, 0);
6313
+ const receiveId = Buffer.from(params.receiveId ?? "", "utf8");
6314
+ const raw = Buffer.concat([random16, msgLen, msg, receiveId]);
6315
+ const padded = pkcs7Pad(raw, WECOM_PKCS7_BLOCK_SIZE);
6316
+ const cipher = crypto.createCipheriv("aes-256-cbc", aesKey, iv);
6317
+ cipher.setAutoPadding(false);
6318
+ const encrypted = Buffer.concat([cipher.update(padded), cipher.final()]);
6319
+ return encrypted.toString("base64");
6320
+ }
6321
+ function decryptWecomMedia(params) {
6322
+ const { encryptedBuffer, encodingAESKey } = params;
6323
+ if (!encryptedBuffer || encryptedBuffer.length === 0) {
6324
+ throw new Error("encryptedBuffer cannot be empty");
6325
+ }
6326
+ const aesKey = decodeEncodingAESKey(encodingAESKey);
6327
+ const iv = aesKey.subarray(0, 16);
6328
+ const decipher = crypto.createDecipheriv("aes-256-cbc", aesKey, iv);
6329
+ decipher.setAutoPadding(false);
6330
+ try {
6331
+ const decryptedPadded = Buffer.concat([
6332
+ decipher.update(encryptedBuffer),
6333
+ decipher.final()
6334
+ ]);
6335
+ const decrypted = pkcs7Unpad(decryptedPadded, WECOM_PKCS7_BLOCK_SIZE);
6336
+ return decrypted;
6337
+ } catch (err) {
6338
+ throw new Error(
6339
+ `Failed to decrypt media: ${err instanceof Error ? err.message : String(err)}`
6340
+ );
6341
+ }
6342
+ }
6343
+ var RESPONSE_URL_TTL_MS = 55 * 60 * 1e3;
6344
+ var TEMP_MEDIA_TTL_MS = 15 * 60 * 1e3;
6345
+ var TEMP_MEDIA_PREFIX = "/wecom-media";
6346
+ var responseEndpoints = /* @__PURE__ */ new Map();
6347
+ var accountPublicBaseUrl = /* @__PURE__ */ new Map();
6348
+ var tempMedia = /* @__PURE__ */ new Map();
6349
+ function endpointKey(accountId, to) {
6350
+ return `${accountId}::${to}`;
6351
+ }
6352
+ function now() {
6353
+ return Date.now();
6354
+ }
6355
+ function normalizeHeaderValue(value) {
6356
+ if (Array.isArray(value)) return value[0] ?? "";
6357
+ return typeof value === "string" ? value : "";
6358
+ }
6359
+ function pickFirstHeaderPart(value) {
6360
+ return value.split(",").map((item) => item.trim()).find(Boolean) ?? "";
6361
+ }
6362
+ function normalizeProto(raw) {
6363
+ const lower = raw.trim().toLowerCase();
6364
+ if (lower === "https" || lower === "http") return lower;
6365
+ return "https";
6366
+ }
6367
+ function guessContentType(fileName) {
6368
+ const ext = path3__default.extname(fileName).toLowerCase();
6369
+ switch (ext) {
6370
+ case ".pdf":
6371
+ return "application/pdf";
6372
+ case ".png":
6373
+ return "image/png";
6374
+ case ".jpg":
6375
+ case ".jpeg":
6376
+ return "image/jpeg";
6377
+ case ".gif":
6378
+ return "image/gif";
6379
+ case ".webp":
6380
+ return "image/webp";
6381
+ case ".txt":
6382
+ return "text/plain; charset=utf-8";
6383
+ case ".json":
6384
+ return "application/json";
6385
+ case ".mp3":
6386
+ return "audio/mpeg";
6387
+ case ".wav":
6388
+ return "audio/wav";
6389
+ default:
6390
+ return "application/octet-stream";
6391
+ }
6392
+ }
6393
+ function pruneExpiredResponseUrls() {
6394
+ const ts = now();
6395
+ for (const [key, list] of responseEndpoints.entries()) {
6396
+ const active = list.filter((entry) => entry.expiresAt > ts);
6397
+ if (active.length > 0) {
6398
+ responseEndpoints.set(key, active);
6399
+ } else {
6400
+ responseEndpoints.delete(key);
6401
+ }
6402
+ }
6403
+ }
6404
+ function pruneExpiredTempMedia() {
6405
+ const ts = now();
6406
+ for (const [id, item] of tempMedia.entries()) {
6407
+ if (item.expiresAt <= ts) {
6408
+ tempMedia.delete(id);
6409
+ }
6410
+ }
6411
+ }
6412
+ function rememberAccountPublicBaseUrl(accountId, req) {
6413
+ const headers = req.headers ?? {};
6414
+ const forwardedHost = pickFirstHeaderPart(normalizeHeaderValue(headers["x-forwarded-host"]));
6415
+ const host = forwardedHost || normalizeHeaderValue(headers.host).trim();
6416
+ if (!host) return;
6417
+ const forwardedProto = pickFirstHeaderPart(normalizeHeaderValue(headers["x-forwarded-proto"]));
6418
+ const encrypted = Boolean(req.socket?.encrypted);
6419
+ const proto = normalizeProto(forwardedProto || (encrypted ? "https" : "http"));
6420
+ accountPublicBaseUrl.set(accountId, `${proto}://${host}`);
6421
+ }
6422
+ function getAccountPublicBaseUrl(accountId) {
6423
+ return accountPublicBaseUrl.get(accountId);
6424
+ }
6425
+ function registerResponseUrl(params) {
6426
+ const accountId = params.accountId.trim();
6427
+ const to = params.to.trim();
6428
+ const responseUrl = params.responseUrl.trim();
6429
+ if (!accountId || !to || !responseUrl) return;
6430
+ pruneExpiredResponseUrls();
6431
+ const key = endpointKey(accountId, to);
6432
+ const list = responseEndpoints.get(key) ?? [];
6433
+ if (list.some((entry) => entry.url === responseUrl)) return;
6434
+ list.push({
6435
+ url: responseUrl,
6436
+ createdAt: now(),
6437
+ expiresAt: now() + RESPONSE_URL_TTL_MS
6438
+ });
6439
+ responseEndpoints.set(key, list);
6440
+ }
6441
+ function consumeResponseUrl(params) {
6442
+ const accountId = params.accountId.trim();
6443
+ const to = params.to.trim();
6444
+ if (!accountId || !to) return null;
6445
+ pruneExpiredResponseUrls();
6446
+ const key = endpointKey(accountId, to);
6447
+ const list = responseEndpoints.get(key) ?? [];
6448
+ if (list.length === 0) return null;
6449
+ const next = list.pop();
6450
+ if (!next?.url) return null;
6451
+ if (list.length > 0) {
6452
+ responseEndpoints.set(key, list);
6453
+ } else {
6454
+ responseEndpoints.delete(key);
6455
+ }
6456
+ return next.url;
6457
+ }
6458
+ async function registerTempLocalMedia(params) {
6459
+ pruneExpiredTempMedia();
6460
+ const absPath = path3__default.resolve(params.filePath);
6461
+ const stat = await promises.stat(absPath);
6462
+ if (!stat.isFile()) {
6463
+ throw new Error(`Local media path is not a file: ${absPath}`);
6464
+ }
6465
+ const id = randomBytes(12).toString("hex");
6466
+ const token = randomBytes(16).toString("hex");
6467
+ const fileName = (params.fileName?.trim() || path3__default.basename(absPath) || "file.bin").replace(/[^\w.\-]/g, "_");
6468
+ tempMedia.set(id, {
6469
+ id,
6470
+ token,
6471
+ filePath: absPath,
6472
+ fileName,
6473
+ createdAt: now(),
6474
+ expiresAt: now() + TEMP_MEDIA_TTL_MS
6475
+ });
6476
+ return { id, token, fileName };
6477
+ }
6478
+ function buildTempMediaUrl(params) {
6479
+ const base = params.baseUrl.replace(/\/+$/, "");
6480
+ const safeName = encodeURIComponent(params.fileName);
6481
+ return `${base}${TEMP_MEDIA_PREFIX}/${params.id}/${safeName}?token=${encodeURIComponent(params.token)}`;
6482
+ }
6483
+ async function handleTempMediaRequest(req, res) {
6484
+ pruneExpiredTempMedia();
6485
+ const url = new URL(req.url ?? "/", "http://localhost");
6486
+ if (!url.pathname.startsWith(`${TEMP_MEDIA_PREFIX}/`)) return false;
6487
+ if (req.method !== "GET") {
6488
+ res.statusCode = 405;
6489
+ res.setHeader("Allow", "GET");
6490
+ res.end("Method Not Allowed");
6491
+ return true;
6492
+ }
6493
+ const parts = url.pathname.split("/").filter(Boolean);
6494
+ if (parts.length < 2) {
6495
+ res.statusCode = 404;
6496
+ res.end("Not Found");
6497
+ return true;
6498
+ }
6499
+ const id = parts[1] ?? "";
6500
+ const token = String(url.searchParams.get("token") ?? "").trim();
6501
+ const entry = tempMedia.get(id);
6502
+ if (!entry || !token || token !== entry.token) {
6503
+ res.statusCode = 404;
6504
+ res.end("Not Found");
6505
+ return true;
6506
+ }
6507
+ try {
6508
+ const data = await promises.readFile(entry.filePath);
6509
+ res.statusCode = 200;
6510
+ res.setHeader("Content-Type", guessContentType(entry.fileName));
6511
+ res.setHeader("Content-Disposition", `inline; filename="${entry.fileName}"`);
6512
+ res.end(data);
6513
+ return true;
6514
+ } catch {
6515
+ tempMedia.delete(id);
6516
+ res.statusCode = 404;
6517
+ res.end("Not Found");
6518
+ return true;
6519
+ }
6520
+ }
6521
+
6522
+ // src/bot.ts
6523
+ function resolveOpenClawStateDir() {
6524
+ const override = process.env.OPENCLAW_STATE_DIR?.trim() || process.env.CLAWDBOT_STATE_DIR?.trim();
6525
+ if (override) {
6526
+ if (override.startsWith("~")) {
6527
+ const home = os2.homedir();
6528
+ const normalized = override === "~" ? home : path3.join(home, override.slice(2));
6529
+ return path3.resolve(normalized);
6530
+ }
6531
+ return path3.resolve(override);
6532
+ }
6533
+ return path3.join(os2.homedir(), ".openclaw");
6534
+ }
6535
+ function resolveWecomInboundMediaDir() {
6536
+ return path3.join(resolveOpenClawStateDir(), "media", "inbound");
6537
+ }
6538
+ function isHttpUrl2(value) {
6539
+ return /^https?:\/\//i.test(value.trim());
6540
+ }
6541
+ function detectMediaTypeByPath(mediaPath) {
6542
+ const ext = path3.extname(mediaPath.split("?")[0] ?? "").toLowerCase();
6543
+ if ([".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"].includes(ext)) {
6544
+ return "image";
6545
+ }
6546
+ return "file";
6547
+ }
6548
+ async function buildPublicMediaUrlForStream(params) {
6549
+ const raw = params.source.trim();
6550
+ if (!raw) return null;
6551
+ if (isHttpUrl2(raw)) {
6552
+ return {
6553
+ url: raw,
6554
+ mediaType: detectMediaTypeByPath(raw)
6555
+ };
6556
+ }
6557
+ if (!path3.isAbsolute(raw)) return null;
6558
+ if (!fs3.existsSync(raw)) return null;
6559
+ const baseUrl = getAccountPublicBaseUrl(params.accountId);
6560
+ if (!baseUrl) {
6561
+ params.log?.warn?.("[wecom] public base URL missing, cannot expose local media in stream");
6562
+ return null;
6563
+ }
6564
+ const temp = await registerTempLocalMedia({
6565
+ filePath: raw,
6566
+ fileName: path3.basename(raw)
6567
+ });
6568
+ const url = buildTempMediaUrl({
6569
+ baseUrl,
6570
+ id: temp.id,
6571
+ token: temp.token,
6572
+ fileName: temp.fileName
6573
+ });
6574
+ return {
6575
+ url,
6576
+ mediaType: detectMediaTypeByPath(temp.fileName)
6577
+ };
6578
+ }
6579
+ async function normalizeChunkForWecomStream(params) {
6580
+ const rawText = String(params.text ?? "");
6581
+ const parseResult = extractMediaFromText(rawText, {
6582
+ removeFromText: true,
6583
+ checkExists: true,
6584
+ existsSync: (p) => fs3.existsSync(p),
6585
+ parseMediaLines: true,
6586
+ parseMarkdownImages: true,
6587
+ parseHtmlImages: true,
6588
+ parseBarePaths: true,
6589
+ parseMarkdownLinks: true
6590
+ });
6591
+ const parts = [];
6592
+ if (parseResult.text.trim()) {
6593
+ parts.push(parseResult.text.trim());
6594
+ }
6595
+ const sourceSet = /* @__PURE__ */ new Set();
6596
+ for (const media of parseResult.all) {
6597
+ const source = (media.localPath ?? media.source ?? "").trim();
6598
+ if (source) sourceSet.add(source);
6599
+ }
6600
+ for (const extra of params.payloadMediaUrls ?? []) {
6601
+ const source = String(extra ?? "").trim();
6602
+ if (source) sourceSet.add(source);
6603
+ }
6604
+ for (const source of sourceSet) {
6605
+ try {
6606
+ const mapped = await buildPublicMediaUrlForStream({
6607
+ accountId: params.accountId,
6608
+ source,
6609
+ log: params.log
6610
+ });
6611
+ if (!mapped) {
6612
+ parts.push(source);
6613
+ continue;
6614
+ }
6615
+ if (mapped.mediaType === "image") {
6616
+ parts.push(`![](${mapped.url})`);
6617
+ } else {
6618
+ parts.push(`[\u4E0B\u8F7D\u6587\u4EF6](${mapped.url})`);
6619
+ }
6620
+ } catch (err) {
6621
+ params.log?.warn?.(`[wecom] failed to map stream media source: ${String(err)}`);
6622
+ parts.push(source);
6623
+ }
6624
+ }
6625
+ return parts.join("\n\n").trim();
6626
+ }
6627
+ function extractWecomContent(msg) {
6628
+ const msgtype = String(msg.msgtype ?? "").toLowerCase();
6629
+ if (msgtype === "text") {
6630
+ const content = msg.text?.content;
6631
+ return typeof content === "string" ? content : "";
6632
+ }
6633
+ if (msgtype === "voice") {
6634
+ const content = msg.voice?.content;
6635
+ return typeof content === "string" ? content : "[voice]";
6636
+ }
6637
+ if (msgtype === "mixed") {
6638
+ const items = msg.mixed?.msg_item;
6639
+ if (Array.isArray(items)) {
6640
+ return items.map((item) => {
6641
+ if (!item || typeof item !== "object") return "";
6642
+ const typed = item;
6643
+ const t = String(typed.msgtype ?? "").toLowerCase();
6644
+ if (t === "text") return String(typed.text?.content ?? "");
6645
+ if (t === "image") return `[image] ${String(typed.image?.url ?? "").trim()}`.trim();
6646
+ return t ? `[${t}]` : "";
6647
+ }).filter((part) => Boolean(part && part.trim())).join("\n");
6648
+ }
6649
+ return "[mixed]";
6650
+ }
6651
+ if (msgtype === "image") {
6652
+ const url = String(msg.image?.url ?? "").trim();
6653
+ return url ? `[image] ${url}` : "[image]";
6654
+ }
6655
+ if (msgtype === "file") {
6656
+ const url = String(msg.file?.url ?? "").trim();
6657
+ return url ? `[file] ${url}` : "[file]";
6658
+ }
6659
+ if (msgtype === "event") {
6660
+ const eventtype = String(msg.event?.eventtype ?? "").trim();
6661
+ return eventtype ? `[event] ${eventtype}` : "[event]";
6662
+ }
6663
+ if (msgtype === "stream") {
6664
+ const id = String(msg.stream?.id ?? "").trim();
6665
+ return id ? `[stream_refresh] ${id}` : "[stream_refresh]";
6666
+ }
6667
+ return msgtype ? `[${msgtype}]` : "";
6668
+ }
6669
+ function resolveSenderId(msg) {
6670
+ const userid = msg.from?.userid?.trim();
6671
+ return userid || "unknown";
6672
+ }
6673
+ function resolveChatType(msg) {
6674
+ return msg.chattype === "group" ? "group" : "direct";
6675
+ }
6676
+ function resolveChatId(msg, senderId, chatType) {
6677
+ if (chatType === "group") {
6678
+ return msg.chatid?.trim() || "unknown";
6679
+ }
6680
+ return senderId;
6681
+ }
6682
+ function resolveMentionedBot(msg) {
6683
+ const msgtype = String(msg.msgtype ?? "").toLowerCase();
6684
+ if (msgtype === "event") return true;
6685
+ const mentionRe = /@[^\s]+/;
6686
+ if (msgtype === "text") {
6687
+ const content = String(msg.text?.content ?? "");
6688
+ return mentionRe.test(content);
6689
+ }
6690
+ if (msgtype === "mixed") {
6691
+ const items = msg.mixed?.msg_item;
6692
+ if (!Array.isArray(items)) return false;
6693
+ return items.some((item) => {
6694
+ if (!item || typeof item !== "object") return false;
6695
+ const typed = item;
6696
+ if (String(typed.msgtype ?? "").toLowerCase() !== "text") return false;
6697
+ const content = String(typed.text?.content ?? "");
6698
+ return mentionRe.test(content);
6699
+ });
6700
+ }
6701
+ return false;
6702
+ }
6703
+ async function dispatchWecomMessage(params) {
6704
+ const { cfg, account, msg, core, hooks } = params;
6705
+ const safeCfg = cfg ?? {};
6706
+ const logger = createLogger("wecom", { log: params.log, error: params.error });
6707
+ const chatType = resolveChatType(msg);
6708
+ const senderId = resolveSenderId(msg);
6709
+ const chatId = resolveChatId(msg, senderId, chatType);
6710
+ const to = chatType === "group" ? `group:${chatId}` : `user:${senderId}`;
6711
+ const responseUrl = typeof msg.response_url === "string" ? msg.response_url.trim() : "";
6712
+ if (responseUrl) {
6713
+ registerResponseUrl({
6714
+ accountId: account.accountId,
6715
+ to,
6716
+ responseUrl
6717
+ });
6718
+ }
6719
+ const accountConfig = account?.config ?? {};
6720
+ if (chatType === "group") {
6721
+ const groupPolicy = resolveGroupPolicy(accountConfig);
6722
+ const groupAllowFrom = resolveGroupAllowFrom(accountConfig);
6723
+ const requireMention = resolveRequireMention(accountConfig);
6724
+ const policyResult = checkGroupPolicy({
6725
+ groupPolicy,
6726
+ conversationId: chatId,
6727
+ groupAllowFrom,
6728
+ requireMention,
6729
+ mentionedBot: resolveMentionedBot(msg)
6730
+ });
6731
+ if (!policyResult.allowed) {
6732
+ logger.debug(`policy rejected: ${policyResult.reason}`);
6733
+ return;
6734
+ }
6735
+ } else {
6736
+ const dmPolicyRaw = accountConfig.dmPolicy ?? "pairing";
6737
+ if (dmPolicyRaw === "disabled") {
6738
+ logger.debug("dmPolicy=disabled, skipping dispatch");
6739
+ return;
6740
+ }
6741
+ const allowFrom = resolveAllowFrom(accountConfig);
6742
+ const policyResult = checkDmPolicy({
6743
+ dmPolicy: dmPolicyRaw,
6744
+ senderId,
6745
+ allowFrom
6746
+ });
6747
+ if (!policyResult.allowed) {
6748
+ logger.debug(`policy rejected: ${policyResult.reason}`);
6749
+ return;
6750
+ }
6751
+ }
6752
+ const channel = core.channel;
6753
+ if (!channel?.routing?.resolveAgentRoute || !channel.reply?.dispatchReplyWithBufferedBlockDispatcher) {
6754
+ logger.debug("core routing or buffered dispatcher missing, skipping dispatch");
6755
+ return;
6756
+ }
6757
+ const route = channel.routing.resolveAgentRoute({
6758
+ cfg: safeCfg,
4563
6759
  channel: "wecom",
4564
6760
  peer: { kind: chatType === "group" ? "group" : "dm", id: chatId }
4565
6761
  });
@@ -4586,12 +6782,13 @@ async function dispatchWecomMessage(params) {
4586
6782
  envelope: envelopeOptions,
4587
6783
  body: rawBody
4588
6784
  }) : rawBody;
6785
+ const from = chatType === "group" ? `wecom:group:${chatId}` : `wecom:user:${senderId}`;
4589
6786
  const ctxPayload = channel.reply?.finalizeInboundContext ? channel.reply.finalizeInboundContext({
4590
6787
  Body: body,
4591
6788
  RawBody: rawBody,
4592
6789
  CommandBody: rawBody,
4593
- From: chatType === "group" ? `wecom:group:${chatId}` : `wecom:${senderId}`,
4594
- To: `wecom:${chatId}`,
6790
+ From: from,
6791
+ To: to,
4595
6792
  SessionKey: route.sessionKey,
4596
6793
  AccountId: route.accountId,
4597
6794
  ChatType: chatType,
@@ -4602,13 +6799,13 @@ async function dispatchWecomMessage(params) {
4602
6799
  Surface: "wecom",
4603
6800
  MessageSid: msg.msgid,
4604
6801
  OriginatingChannel: "wecom",
4605
- OriginatingTo: `wecom:${chatId}`
6802
+ OriginatingTo: to
4606
6803
  }) : {
4607
6804
  Body: body,
4608
6805
  RawBody: rawBody,
4609
6806
  CommandBody: rawBody,
4610
- From: chatType === "group" ? `wecom:group:${chatId}` : `wecom:${senderId}`,
4611
- To: `wecom:${chatId}`,
6807
+ From: from,
6808
+ To: to,
4612
6809
  SessionKey: route.sessionKey,
4613
6810
  AccountId: route.accountId,
4614
6811
  ChatType: chatType,
@@ -4619,13 +6816,44 @@ async function dispatchWecomMessage(params) {
4619
6816
  Surface: "wecom",
4620
6817
  MessageSid: msg.msgid,
4621
6818
  OriginatingChannel: "wecom",
4622
- OriginatingTo: `wecom:${chatId}`
6819
+ OriginatingTo: to
4623
6820
  };
6821
+ const ctxTo = typeof ctxPayload.To === "string" && ctxPayload.To.trim() ? ctxPayload.To.trim() : void 0;
6822
+ const ctxOriginatingTo = typeof ctxPayload.OriginatingTo === "string" && ctxPayload.OriginatingTo.trim() ? ctxPayload.OriginatingTo.trim() : void 0;
6823
+ const stableTo = ctxOriginatingTo ?? ctxTo ?? to;
6824
+ ctxPayload.To = stableTo;
6825
+ ctxPayload.OriginatingTo = stableTo;
6826
+ ctxPayload.SenderId = senderId;
6827
+ ctxPayload.SenderName = senderId;
6828
+ ctxPayload.ConversationLabel = fromLabel;
6829
+ const contextRunId = (() => {
6830
+ const candidates = ["RunId", "runId", "AgentRunId", "agentRunId"];
6831
+ for (const key of candidates) {
6832
+ const value = ctxPayload[key];
6833
+ if (typeof value === "string" && value.trim()) return value.trim();
6834
+ }
6835
+ return void 0;
6836
+ })();
6837
+ hooks.onRouteContext?.({
6838
+ sessionKey: route.sessionKey,
6839
+ runId: contextRunId
6840
+ });
6841
+ ctxPayload.CommandAuthorized = true;
4624
6842
  if (channel.session?.recordInboundSession && storePath) {
6843
+ const mainSessionKeyRaw = route?.mainSessionKey;
6844
+ const mainSessionKey = typeof mainSessionKeyRaw === "string" && mainSessionKeyRaw.trim() ? mainSessionKeyRaw : void 0;
6845
+ const recordSessionKeyRaw = ctxPayload.SessionKey ?? route.sessionKey;
6846
+ const recordSessionKey = typeof recordSessionKeyRaw === "string" && recordSessionKeyRaw.trim() ? recordSessionKeyRaw : route.sessionKey;
4625
6847
  await channel.session.recordInboundSession({
4626
6848
  storePath,
4627
- sessionKey: ctxPayload.SessionKey ?? route.sessionKey,
6849
+ sessionKey: recordSessionKey,
4628
6850
  ctx: ctxPayload,
6851
+ updateLastRoute: {
6852
+ sessionKey: mainSessionKey ?? route.sessionKey,
6853
+ channel: "wecom",
6854
+ to: stableTo,
6855
+ accountId: route.accountId ?? account.accountId
6856
+ },
4629
6857
  onRecordError: (err) => {
4630
6858
  logger.error(`wecom: failed updating session meta: ${String(err)}`);
4631
6859
  }
@@ -4638,9 +6866,20 @@ async function dispatchWecomMessage(params) {
4638
6866
  dispatcherOptions: {
4639
6867
  deliver: async (payload) => {
4640
6868
  const rawText = payload.text ?? "";
4641
- if (!rawText.trim()) return;
6869
+ const payloadMediaUrls = [
6870
+ ...Array.isArray(payload.mediaUrls) ? payload.mediaUrls : [],
6871
+ ...payload.mediaUrl ? [payload.mediaUrl] : []
6872
+ ].map((entry) => String(entry ?? "").trim()).filter(Boolean);
6873
+ if (!rawText.trim() && payloadMediaUrls.length === 0) return;
4642
6874
  const converted = channel.text?.convertMarkdownTables && tableMode ? channel.text.convertMarkdownTables(rawText, tableMode) : rawText;
4643
- hooks.onChunk(converted);
6875
+ const normalized = await normalizeChunkForWecomStream({
6876
+ accountId: account.accountId,
6877
+ text: converted,
6878
+ payloadMediaUrls,
6879
+ log: logger
6880
+ });
6881
+ if (!normalized.trim()) return;
6882
+ await hooks.onChunk(normalized);
4644
6883
  },
4645
6884
  onError: (err, info) => {
4646
6885
  hooks.onError?.(err);
@@ -4695,9 +6934,9 @@ async function downloadAndDecryptMedia(params) {
4695
6934
  } catch (err) {
4696
6935
  throw new Error(`\u89E3\u5BC6\u5931\u8D25: ${err instanceof Error ? err.message : String(err)}`);
4697
6936
  }
4698
- const sanitizeFileName = (input) => {
4699
- if (!input) return void 0;
4700
- const base = path.basename(input);
6937
+ const sanitizeFileName = (input2) => {
6938
+ if (!input2) return void 0;
6939
+ const base = path3.basename(input2);
4701
6940
  const cleaned = base.replace(/[\\\/]+/g, "_").replace(/[\x00-\x1f\x7f]/g, "").trim();
4702
6941
  if (!cleaned || cleaned === "." || cleaned === "..") return void 0;
4703
6942
  return cleaned.length > 200 ? cleaned.slice(0, 200) : cleaned;
@@ -4724,17 +6963,15 @@ async function downloadAndDecryptMedia(params) {
4724
6963
  if (!extension) {
4725
6964
  extension = resolveExtension(contentType);
4726
6965
  }
4727
- const now = /* @__PURE__ */ new Date();
4728
- const yearMonth = now.toISOString().slice(0, 7).replace("-", "");
4729
- const wecomDir = path.join("/tmp", "wecom", yearMonth);
6966
+ const wecomDir = resolveWecomInboundMediaDir();
4730
6967
  await fsPromises.mkdir(wecomDir, { recursive: true });
4731
6968
  const baseFileName = originalFileName || `wecom-media`;
4732
6969
  const baseNameWithoutExt = baseFileName.replace(/\.[-.\w]+$/, "");
4733
6970
  const timestamp = Date.now();
4734
6971
  const safeFileName = `${baseNameWithoutExt}-${timestamp}${extension}`;
4735
- const resolvedDir = path.resolve(wecomDir);
4736
- const resolvedPath = path.resolve(wecomDir, safeFileName);
4737
- if (!resolvedPath.startsWith(`${resolvedDir}${path.sep}`) && resolvedPath !== resolvedDir) {
6972
+ const resolvedDir = path3.resolve(wecomDir);
6973
+ const resolvedPath = path3.resolve(wecomDir, safeFileName);
6974
+ if (!resolvedPath.startsWith(`${resolvedDir}${path3.sep}`) && resolvedPath !== resolvedDir) {
4738
6975
  throw new Error("Invalid media file path");
4739
6976
  }
4740
6977
  await fsPromises.writeFile(resolvedPath, decryptedBuffer);
@@ -4889,9 +7126,14 @@ function tryGetWecomRuntime() {
4889
7126
  var webhookTargets = /* @__PURE__ */ new Map();
4890
7127
  var streams = /* @__PURE__ */ new Map();
4891
7128
  var msgidToStreamId = /* @__PURE__ */ new Map();
7129
+ var streamRouteBindings = /* @__PURE__ */ new Map();
7130
+ var streamBySessionKey = /* @__PURE__ */ new Map();
7131
+ var streamByRunId = /* @__PURE__ */ new Map();
7132
+ var streamFinalizeTimers = /* @__PURE__ */ new Map();
4892
7133
  var STREAM_TTL_MS = 10 * 60 * 1e3;
4893
7134
  var STREAM_MAX_BYTES = 20480;
4894
7135
  var INITIAL_STREAM_WAIT_MS = 800;
7136
+ var STREAM_FINISH_GRACE_MS = 2500;
4895
7137
  function normalizeWebhookPath(raw) {
4896
7138
  const trimmed = raw.trim();
4897
7139
  if (!trimmed) return "/";
@@ -4899,11 +7141,34 @@ function normalizeWebhookPath(raw) {
4899
7141
  if (withSlash.length > 1 && withSlash.endsWith("/")) return withSlash.slice(0, -1);
4900
7142
  return withSlash;
4901
7143
  }
7144
+ function normalizeToToken(raw) {
7145
+ const value = raw.trim();
7146
+ if (!value) return "";
7147
+ if (value.startsWith("user:")) {
7148
+ return `user:${value.slice("user:".length).trim().toLowerCase()}`;
7149
+ }
7150
+ if (value.startsWith("group:")) {
7151
+ return `group:${value.slice("group:".length).trim()}`;
7152
+ }
7153
+ return value;
7154
+ }
7155
+ function appendToStream(streamId, chunk) {
7156
+ const state = streams.get(streamId);
7157
+ if (!state || state.finished) return false;
7158
+ appendStreamContent(state, chunk);
7159
+ return true;
7160
+ }
4902
7161
  function pruneStreams() {
4903
7162
  const cutoff = Date.now() - STREAM_TTL_MS;
4904
7163
  for (const [id, state] of streams.entries()) {
4905
7164
  if (state.updatedAt < cutoff) {
7165
+ const timer = streamFinalizeTimers.get(id);
7166
+ if (timer) {
7167
+ clearTimeout(timer);
7168
+ streamFinalizeTimers.delete(id);
7169
+ }
4906
7170
  streams.delete(id);
7171
+ unbindActiveStream(id);
4907
7172
  }
4908
7173
  }
4909
7174
  for (const [msgid, id] of msgidToStreamId.entries()) {
@@ -4912,6 +7177,28 @@ function pruneStreams() {
4912
7177
  }
4913
7178
  }
4914
7179
  }
7180
+ function finalizeStreamNow(streamId) {
7181
+ const timer = streamFinalizeTimers.get(streamId);
7182
+ if (timer) {
7183
+ clearTimeout(timer);
7184
+ streamFinalizeTimers.delete(streamId);
7185
+ }
7186
+ const state = streams.get(streamId);
7187
+ if (!state) return;
7188
+ state.finished = true;
7189
+ state.updatedAt = Date.now();
7190
+ unbindActiveStream(streamId);
7191
+ }
7192
+ function scheduleStreamFinalize(streamId) {
7193
+ const existing = streamFinalizeTimers.get(streamId);
7194
+ if (existing) {
7195
+ clearTimeout(existing);
7196
+ }
7197
+ const timer = setTimeout(() => {
7198
+ finalizeStreamNow(streamId);
7199
+ }, STREAM_FINISH_GRACE_MS);
7200
+ streamFinalizeTimers.set(streamId, timer);
7201
+ }
4915
7202
  function truncateUtf8Bytes(text, maxBytes) {
4916
7203
  const buf = Buffer.from(text, "utf8");
4917
7204
  if (buf.length <= maxBytes) return text;
@@ -4926,11 +7213,11 @@ function jsonOk(res, body) {
4926
7213
  async function readJsonBody(req, maxBytes) {
4927
7214
  const chunks = [];
4928
7215
  let total = 0;
4929
- return await new Promise((resolve2) => {
7216
+ return await new Promise((resolve3) => {
4930
7217
  req.on("data", (chunk) => {
4931
7218
  total += chunk.length;
4932
7219
  if (total > maxBytes) {
4933
- resolve2({ ok: false, error: "payload too large" });
7220
+ resolve3({ ok: false, error: "payload too large" });
4934
7221
  req.destroy();
4935
7222
  return;
4936
7223
  }
@@ -4940,16 +7227,16 @@ async function readJsonBody(req, maxBytes) {
4940
7227
  try {
4941
7228
  const raw = Buffer.concat(chunks).toString("utf8");
4942
7229
  if (!raw.trim()) {
4943
- resolve2({ ok: false, error: "empty payload" });
7230
+ resolve3({ ok: false, error: "empty payload" });
4944
7231
  return;
4945
7232
  }
4946
- resolve2({ ok: true, value: JSON.parse(raw) });
7233
+ resolve3({ ok: true, value: JSON.parse(raw) });
4947
7234
  } catch (err) {
4948
- resolve2({ ok: false, error: err instanceof Error ? err.message : String(err) });
7235
+ resolve3({ ok: false, error: err instanceof Error ? err.message : String(err) });
4949
7236
  }
4950
7237
  });
4951
7238
  req.on("error", (err) => {
4952
- resolve2({ ok: false, error: err instanceof Error ? err.message : String(err) });
7239
+ resolve3({ ok: false, error: err instanceof Error ? err.message : String(err) });
4953
7240
  });
4954
7241
  });
4955
7242
  }
@@ -4996,13 +7283,16 @@ function buildStreamPlaceholderReply(streamId) {
4996
7283
  }
4997
7284
  function buildStreamReplyFromState(state) {
4998
7285
  const content = truncateUtf8Bytes(state.content, STREAM_MAX_BYTES);
7286
+ const stream = {
7287
+ id: state.streamId,
7288
+ finish: state.finished
7289
+ };
7290
+ if (content.trim()) {
7291
+ stream.content = content;
7292
+ }
4999
7293
  return {
5000
7294
  msgtype: "stream",
5001
- stream: {
5002
- id: state.streamId,
5003
- finish: state.finished,
5004
- content
5005
- }
7295
+ stream
5006
7296
  };
5007
7297
  }
5008
7298
  function createStreamId() {
@@ -5017,12 +7307,12 @@ function parseWecomPlainMessage(raw) {
5017
7307
  }
5018
7308
  async function waitForStreamContent(streamId, maxWaitMs) {
5019
7309
  const startedAt = Date.now();
5020
- await new Promise((resolve2) => {
7310
+ await new Promise((resolve3) => {
5021
7311
  const tick = () => {
5022
7312
  const state = streams.get(streamId);
5023
- if (!state) return resolve2();
5024
- if (state.error || state.finished || state.content.trim()) return resolve2();
5025
- if (Date.now() - startedAt >= maxWaitMs) return resolve2();
7313
+ if (!state) return resolve3();
7314
+ if (state.error || state.finished || state.content.trim()) return resolve3();
7315
+ if (Date.now() - startedAt >= maxWaitMs) return resolve3();
5026
7316
  setTimeout(tick, 25);
5027
7317
  };
5028
7318
  tick();
@@ -5034,6 +7324,124 @@ function appendStreamContent(state, nextText) {
5034
7324
  ${nextText}`.trim() : nextText.trim();
5035
7325
  state.content = truncateUtf8Bytes(content, STREAM_MAX_BYTES);
5036
7326
  state.updatedAt = Date.now();
7327
+ if (streamFinalizeTimers.has(state.streamId)) {
7328
+ scheduleStreamFinalize(state.streamId);
7329
+ }
7330
+ }
7331
+ function listActiveStreamIdsByTo(to) {
7332
+ const normalized = normalizeToToken(to);
7333
+ if (!normalized) return [];
7334
+ const ids = [];
7335
+ for (const [id, state] of streams.entries()) {
7336
+ if (state.finished) continue;
7337
+ if (normalizeToToken(state.to ?? "") !== normalized) continue;
7338
+ ids.push(id);
7339
+ }
7340
+ return ids;
7341
+ }
7342
+ function pickNewestStreamId(streamIds) {
7343
+ let selected;
7344
+ for (const id of streamIds) {
7345
+ const state = streams.get(id);
7346
+ if (!state || state.finished) continue;
7347
+ if (!selected || state.updatedAt > selected.updatedAt || state.updatedAt === selected.updatedAt && state.createdAt > selected.createdAt) {
7348
+ selected = { id, updatedAt: state.updatedAt, createdAt: state.createdAt };
7349
+ }
7350
+ }
7351
+ return selected?.id;
7352
+ }
7353
+ function bindStreamRouteContext(params) {
7354
+ const streamId = params.streamId.trim();
7355
+ if (!streamId) return;
7356
+ const sessionKey = params.sessionKey?.trim();
7357
+ const runId = params.runId?.trim();
7358
+ const current = streamRouteBindings.get(streamId) ?? {};
7359
+ const next = {
7360
+ sessionKey: sessionKey || current.sessionKey,
7361
+ runId: runId || current.runId
7362
+ };
7363
+ streamRouteBindings.set(streamId, next);
7364
+ if (next.sessionKey) {
7365
+ streamBySessionKey.set(next.sessionKey, streamId);
7366
+ }
7367
+ if (next.runId) {
7368
+ streamByRunId.set(next.runId, streamId);
7369
+ }
7370
+ }
7371
+ function unbindActiveStream(streamId) {
7372
+ const timer = streamFinalizeTimers.get(streamId);
7373
+ if (timer) {
7374
+ clearTimeout(timer);
7375
+ streamFinalizeTimers.delete(streamId);
7376
+ }
7377
+ const routeBinding = streamRouteBindings.get(streamId);
7378
+ if (routeBinding?.sessionKey && streamBySessionKey.get(routeBinding.sessionKey) === streamId) {
7379
+ streamBySessionKey.delete(routeBinding.sessionKey);
7380
+ }
7381
+ if (routeBinding?.runId && streamByRunId.get(routeBinding.runId) === streamId) {
7382
+ streamByRunId.delete(routeBinding.runId);
7383
+ }
7384
+ streamRouteBindings.delete(streamId);
7385
+ }
7386
+ function appendWecomActiveStreamChunk(params) {
7387
+ const chunk = params.chunk.trim();
7388
+ if (!chunk) return false;
7389
+ const to = normalizeToToken(params.to);
7390
+ if (!to) return false;
7391
+ const runId = params.runId?.trim();
7392
+ const sessionKey = params.sessionKey?.trim();
7393
+ if (runId) {
7394
+ const streamId = streamByRunId.get(runId);
7395
+ if (streamId && appendToStream(streamId, chunk)) return true;
7396
+ if (sessionKey) {
7397
+ const sessionStreamId = streamBySessionKey.get(sessionKey);
7398
+ if (sessionStreamId && appendToStream(sessionStreamId, chunk)) {
7399
+ bindStreamRouteContext({
7400
+ streamId: sessionStreamId,
7401
+ sessionKey,
7402
+ runId
7403
+ });
7404
+ console.warn(
7405
+ `[wecom] append stream chunk recovered run binding by sessionKey: runId=${runId}, sessionKey=${sessionKey}`
7406
+ );
7407
+ return true;
7408
+ }
7409
+ }
7410
+ const toCandidates2 = listActiveStreamIdsByTo(to);
7411
+ if (toCandidates2.length === 1) {
7412
+ console.warn(`[wecom] append stream chunk fallback by to after runId miss: runId=${runId}, to=${to}`);
7413
+ return appendToStream(toCandidates2[0], chunk);
7414
+ }
7415
+ if (toCandidates2.length > 1) {
7416
+ const newest = pickNewestStreamId(toCandidates2);
7417
+ if (newest) {
7418
+ console.warn(
7419
+ `[wecom] append stream chunk fallback by newest to after runId miss: runId=${runId}, to=${to}, candidates=${toCandidates2.length}`
7420
+ );
7421
+ return appendToStream(newest, chunk);
7422
+ }
7423
+ }
7424
+ return false;
7425
+ }
7426
+ if (sessionKey) {
7427
+ const streamId = streamBySessionKey.get(sessionKey);
7428
+ if (streamId && appendToStream(streamId, chunk)) return true;
7429
+ }
7430
+ const toCandidates = listActiveStreamIdsByTo(to);
7431
+ if (toCandidates.length === 1) {
7432
+ console.warn(`[wecom] append stream chunk fallback by to without context: to=${to}`);
7433
+ return appendToStream(toCandidates[0], chunk);
7434
+ }
7435
+ if (toCandidates.length > 1) {
7436
+ const newest = pickNewestStreamId(toCandidates);
7437
+ if (newest) {
7438
+ console.warn(
7439
+ `[wecom] append stream chunk fallback by newest to without context: to=${to}, candidates=${toCandidates.length}`
7440
+ );
7441
+ return appendToStream(newest, chunk);
7442
+ }
7443
+ }
7444
+ return false;
5037
7445
  }
5038
7446
  function buildLogger(target) {
5039
7447
  return createLogger("wecom", {
@@ -5055,8 +7463,11 @@ function registerWecomWebhookTarget(target) {
5055
7463
  }
5056
7464
  async function handleWecomWebhookRequest(req, res) {
5057
7465
  pruneStreams();
5058
- const path2 = resolvePath(req);
5059
- const targets = webhookTargets.get(path2);
7466
+ if (await handleTempMediaRequest(req, res)) {
7467
+ return true;
7468
+ }
7469
+ const path5 = resolvePath(req);
7470
+ const targets = webhookTargets.get(path5);
5060
7471
  if (!targets || targets.length === 0) return false;
5061
7472
  const query = resolveQueryParams(req);
5062
7473
  const timestamp = query.get("timestamp") ?? "";
@@ -5064,7 +7475,7 @@ async function handleWecomWebhookRequest(req, res) {
5064
7475
  const signature = resolveSignatureParam(query);
5065
7476
  const primary = targets[0];
5066
7477
  const logger = buildLogger(primary);
5067
- logger.debug(`incoming ${req.method} request on ${path2} (timestamp=${timestamp}, nonce=${nonce})`);
7478
+ logger.debug(`incoming ${req.method} request on ${path5} (timestamp=${timestamp}, nonce=${nonce})`);
5068
7479
  if (req.method === "GET") {
5069
7480
  const echostr = query.get("echostr") ?? "";
5070
7481
  if (!timestamp || !nonce || !signature || !echostr) {
@@ -5093,6 +7504,7 @@ async function handleWecomWebhookRequest(req, res) {
5093
7504
  receiveId: target2.account.receiveId,
5094
7505
  encrypt: echostr
5095
7506
  });
7507
+ rememberAccountPublicBaseUrl(target2.account.accountId, req);
5096
7508
  res.statusCode = 200;
5097
7509
  res.setHeader("Content-Type", "text/plain; charset=utf-8");
5098
7510
  res.end(plain2);
@@ -5143,6 +7555,7 @@ async function handleWecomWebhookRequest(req, res) {
5143
7555
  res.end("unauthorized");
5144
7556
  return true;
5145
7557
  }
7558
+ rememberAccountPublicBaseUrl(target.account.accountId, req);
5146
7559
  if (!target.account.configured || !target.account.token || !target.account.encodingAESKey) {
5147
7560
  res.statusCode = 500;
5148
7561
  res.end("wecom not configured");
@@ -5214,6 +7627,26 @@ async function handleWecomWebhookRequest(req, res) {
5214
7627
  );
5215
7628
  return true;
5216
7629
  }
7630
+ const core2 = tryGetWecomRuntime();
7631
+ if (core2) {
7632
+ dispatchWecomMessage({
7633
+ cfg: target.config,
7634
+ account: target.account,
7635
+ msg,
7636
+ core: core2,
7637
+ hooks: {
7638
+ onChunk: () => {
7639
+ },
7640
+ onError: (err) => {
7641
+ logger.error(`wecom event dispatch failed: ${String(err)}`);
7642
+ }
7643
+ },
7644
+ log: target.runtime.log,
7645
+ error: target.runtime.error
7646
+ }).catch((err) => {
7647
+ logger.error(`wecom event dispatch failed: ${String(err)}`);
7648
+ });
7649
+ }
5217
7650
  jsonOk(
5218
7651
  res,
5219
7652
  buildEncryptedJsonReply({
@@ -5227,9 +7660,13 @@ async function handleWecomWebhookRequest(req, res) {
5227
7660
  }
5228
7661
  const streamId = createStreamId();
5229
7662
  if (msgid) msgidToStreamId.set(msgid, streamId);
7663
+ const senderId = String(msg.from?.userid ?? "").trim() || "unknown";
7664
+ const chatType = String(msg.chattype ?? "").toLowerCase() === "group" ? "group" : "single";
7665
+ const to = chatType === "group" ? `group:${String(msg.chatid ?? "").trim() || "unknown"}` : `user:${senderId}`;
5230
7666
  streams.set(streamId, {
5231
7667
  streamId,
5232
7668
  msgid,
7669
+ to: normalizeToToken(to),
5233
7670
  createdAt: Date.now(),
5234
7671
  updatedAt: Date.now(),
5235
7672
  started: false,
@@ -5240,21 +7677,44 @@ async function handleWecomWebhookRequest(req, res) {
5240
7677
  if (core) {
5241
7678
  const state2 = streams.get(streamId);
5242
7679
  if (state2) state2.started = true;
7680
+ let chunkFlush = Promise.resolve();
7681
+ const markStreamFinished = async (err) => {
7682
+ await chunkFlush.catch(() => void 0);
7683
+ const current = streams.get(streamId);
7684
+ if (!current) return;
7685
+ if (err) {
7686
+ current.error = err instanceof Error ? err.message : String(err);
7687
+ current.content = current.content || `Error: ${current.error}`;
7688
+ }
7689
+ current.updatedAt = Date.now();
7690
+ scheduleStreamFinalize(streamId);
7691
+ };
5243
7692
  const hooks = {
7693
+ onRouteContext: (context) => {
7694
+ bindStreamRouteContext({
7695
+ streamId,
7696
+ sessionKey: context.sessionKey,
7697
+ runId: context.runId
7698
+ });
7699
+ },
5244
7700
  onChunk: (text) => {
5245
- const current = streams.get(streamId);
5246
- if (!current) return;
5247
- appendStreamContent(current, text);
5248
- target.statusSink?.({ lastOutboundAt: Date.now() });
7701
+ chunkFlush = chunkFlush.then(async () => {
7702
+ const current = streams.get(streamId);
7703
+ if (!current) return;
7704
+ appendStreamContent(current, text);
7705
+ target.statusSink?.({ lastOutboundAt: Date.now() });
7706
+ });
7707
+ return chunkFlush;
5249
7708
  },
5250
7709
  onError: (err) => {
5251
- const current = streams.get(streamId);
5252
- if (current) {
5253
- current.error = err instanceof Error ? err.message : String(err);
5254
- current.content = current.content || `Error: ${current.error}`;
5255
- current.finished = true;
5256
- current.updatedAt = Date.now();
5257
- }
7710
+ chunkFlush = chunkFlush.then(async () => {
7711
+ const current = streams.get(streamId);
7712
+ if (current) {
7713
+ current.error = err instanceof Error ? err.message : String(err);
7714
+ current.content = current.content || `Error: ${current.error}`;
7715
+ current.updatedAt = Date.now();
7716
+ }
7717
+ });
5258
7718
  logger.error(`wecom agent failed: ${String(err)}`);
5259
7719
  }
5260
7720
  };
@@ -5267,27 +7727,17 @@ async function handleWecomWebhookRequest(req, res) {
5267
7727
  log: target.runtime.log,
5268
7728
  error: target.runtime.error
5269
7729
  }).then(() => {
5270
- const current = streams.get(streamId);
5271
- if (current) {
5272
- current.finished = true;
5273
- current.updatedAt = Date.now();
5274
- }
7730
+ void markStreamFinished();
5275
7731
  }).catch((err) => {
5276
- const current = streams.get(streamId);
5277
- if (current) {
5278
- current.error = err instanceof Error ? err.message : String(err);
5279
- current.content = current.content || `Error: ${current.error}`;
5280
- current.finished = true;
5281
- current.updatedAt = Date.now();
5282
- }
7732
+ void markStreamFinished(err);
5283
7733
  logger.error(`wecom agent failed: ${String(err)}`);
5284
7734
  });
5285
7735
  } else {
5286
7736
  const state2 = streams.get(streamId);
5287
7737
  if (state2) {
5288
- state2.finished = true;
5289
7738
  state2.updatedAt = Date.now();
5290
7739
  }
7740
+ scheduleStreamFinalize(streamId);
5291
7741
  }
5292
7742
  await waitForStreamContent(streamId, INITIAL_STREAM_WAIT_MS);
5293
7743
  const state = streams.get(streamId);
@@ -5305,6 +7755,111 @@ async function handleWecomWebhookRequest(req, res) {
5305
7755
  }
5306
7756
 
5307
7757
  // src/channel.ts
7758
+ var BARE_USER_ID_RE = /^[a-z0-9][a-z0-9._@-]{0,63}$/;
7759
+ var EXPLICIT_USER_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,63}$/;
7760
+ var GROUP_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/;
7761
+ function looksLikeEmail(raw) {
7762
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(raw.trim());
7763
+ }
7764
+ function parseDirectTarget(rawTarget) {
7765
+ let raw = String(rawTarget ?? "").trim();
7766
+ if (!raw) return null;
7767
+ if (raw.startsWith("wecom:")) {
7768
+ raw = raw.slice("wecom:".length);
7769
+ }
7770
+ let accountId;
7771
+ if (!looksLikeEmail(raw)) {
7772
+ const atIdx = raw.lastIndexOf("@");
7773
+ if (atIdx > 0 && atIdx < raw.length - 1) {
7774
+ const candidate = raw.slice(atIdx + 1);
7775
+ if (!/[:/]/.test(candidate)) {
7776
+ accountId = candidate;
7777
+ raw = raw.slice(0, atIdx);
7778
+ }
7779
+ }
7780
+ }
7781
+ if (raw.startsWith("chat:")) {
7782
+ raw = `group:${raw.slice(5)}`;
7783
+ }
7784
+ if (raw.startsWith("group:")) {
7785
+ const id2 = raw.slice(6).trim();
7786
+ if (!id2 || /\s/.test(id2) || !GROUP_ID_RE.test(id2)) return null;
7787
+ return { accountId, kind: "group", id: id2 };
7788
+ }
7789
+ const explicitUserPrefix = raw.startsWith("user:");
7790
+ if (explicitUserPrefix) raw = raw.slice(5);
7791
+ const id = raw.trim();
7792
+ if (!id || /\s/.test(id)) return null;
7793
+ if (!explicitUserPrefix && !BARE_USER_ID_RE.test(id)) return null;
7794
+ if (explicitUserPrefix && !EXPLICIT_USER_ID_RE.test(id)) return null;
7795
+ return { accountId, kind: "user", id };
7796
+ }
7797
+ function isHttpUrl3(value) {
7798
+ return /^https?:\/\//i.test(value.trim());
7799
+ }
7800
+ function normalizeLocalPath2(raw) {
7801
+ const trimmed = raw.trim();
7802
+ if (trimmed.startsWith("file://")) {
7803
+ return decodeURIComponent(trimmed.slice("file://".length));
7804
+ }
7805
+ return trimmed;
7806
+ }
7807
+ async function ensureReadableFile(filePath) {
7808
+ await access(filePath);
7809
+ }
7810
+ function detectOutboundMediaType(mediaUrl, mimeType) {
7811
+ const mime = String(mimeType ?? "").split(";")[0].trim().toLowerCase();
7812
+ if (mime.startsWith("image/")) return "image";
7813
+ const ext = path3__default.extname(mediaUrl.split("?")[0] ?? "").toLowerCase();
7814
+ if ([".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"].includes(ext)) {
7815
+ return "image";
7816
+ }
7817
+ return "file";
7818
+ }
7819
+ function buildMediaMarkdown(params) {
7820
+ const parts = [];
7821
+ const caption = params.caption?.trim();
7822
+ if (caption) {
7823
+ parts.push(caption);
7824
+ }
7825
+ if (params.mediaType === "image") {
7826
+ parts.push(`![](${params.mediaUrl})`);
7827
+ } else {
7828
+ parts.push(`[\u4E0B\u8F7D\u6587\u4EF6](${params.mediaUrl})`);
7829
+ }
7830
+ return parts.join("\n\n").trim();
7831
+ }
7832
+ function resolveReplyTargetToken(parsed) {
7833
+ return `${parsed.kind}:${parsed.id}`;
7834
+ }
7835
+ function resolveStreamContext(params) {
7836
+ if (!params || typeof params !== "object") return {};
7837
+ const maybe = params;
7838
+ const sessionKey = typeof maybe.sessionKey === "string" ? maybe.sessionKey.trim() : "";
7839
+ const runId = typeof maybe.runId === "string" ? maybe.runId.trim() : "";
7840
+ return {
7841
+ sessionKey: sessionKey || void 0,
7842
+ runId: runId || void 0
7843
+ };
7844
+ }
7845
+ async function postWecomResponse(responseUrl, payload) {
7846
+ const body = JSON.stringify(payload);
7847
+ const response = await fetch(responseUrl, {
7848
+ method: "POST",
7849
+ headers: {
7850
+ "Content-Type": "application/json"
7851
+ },
7852
+ body
7853
+ });
7854
+ if (!response.ok) {
7855
+ const text = await response.text().catch(() => "");
7856
+ throw new Error(`WeCom response_url send failed: HTTP ${response.status} ${text}`.trim());
7857
+ }
7858
+ }
7859
+ function formatError(err) {
7860
+ if (err instanceof Error) return err.message;
7861
+ return String(err);
7862
+ }
5308
7863
  var meta = {
5309
7864
  id: "wecom",
5310
7865
  label: "WeCom",
@@ -5323,13 +7878,32 @@ var wecomPlugin = {
5323
7878
  },
5324
7879
  capabilities: {
5325
7880
  chatTypes: ["direct", "group"],
5326
- media: false,
7881
+ media: true,
5327
7882
  reactions: false,
5328
7883
  threads: false,
5329
7884
  edit: false,
5330
7885
  reply: true,
5331
7886
  polls: false
5332
7887
  },
7888
+ messaging: {
7889
+ normalizeTarget: (raw) => {
7890
+ const parsed = parseDirectTarget(raw);
7891
+ if (!parsed) return void 0;
7892
+ return `${parsed.kind}:${parsed.id}${parsed.accountId ? `@${parsed.accountId}` : ""}`;
7893
+ },
7894
+ targetResolver: {
7895
+ looksLikeId: (raw, normalized) => {
7896
+ const candidate = (normalized ?? raw).trim();
7897
+ return Boolean(parseDirectTarget(candidate));
7898
+ },
7899
+ hint: "Use WeCom ids only: user:<userid> for DM, group:<chatid> for groups (optional @accountId)."
7900
+ },
7901
+ formatTargetDisplay: (params) => {
7902
+ const parsed = parseDirectTarget(params.target);
7903
+ if (!parsed) return params.display?.trim() || params.target;
7904
+ return `${parsed.kind}:${parsed.id}`;
7905
+ }
7906
+ },
5333
7907
  configSchema: WecomConfigJsonSchema,
5334
7908
  reload: { configPrefixes: ["channels.wecom"] },
5335
7909
  config: {
@@ -5412,15 +7986,217 @@ var wecomPlugin = {
5412
7986
  return resolveRequireMention(account.config);
5413
7987
  }
5414
7988
  },
7989
+ directory: {
7990
+ canResolve: (params) => Boolean(parseDirectTarget(params.target)),
7991
+ resolveTarget: (params) => {
7992
+ const parsed = parseDirectTarget(params.target);
7993
+ if (!parsed) return null;
7994
+ return { channel: "wecom", accountId: parsed.accountId, to: parsed.id };
7995
+ },
7996
+ resolveTargets: (params) => {
7997
+ const results = [];
7998
+ for (const target of params.targets) {
7999
+ const resolved = wecomPlugin.directory.resolveTarget({ cfg: params.cfg, target });
8000
+ if (resolved) results.push(resolved);
8001
+ }
8002
+ return results;
8003
+ },
8004
+ getTargetFormats: () => [
8005
+ "wecom:user:<userId>",
8006
+ "user:<userId>",
8007
+ "group:<chatId>",
8008
+ "<userid-lowercase>"
8009
+ ]
8010
+ },
5415
8011
  outbound: {
5416
8012
  deliveryMode: "direct",
5417
- sendText: async () => {
8013
+ sendText: async (params) => {
8014
+ console.log(`[wecom] sendText called: to=${params.to}, textLen=${params.text.length}`);
8015
+ const account = resolveWecomAccount({ cfg: params.cfg, accountId: params.accountId });
8016
+ const parsed = parseDirectTarget(params.to);
8017
+ const streamContext = resolveStreamContext(params);
8018
+ if (!parsed) {
8019
+ const error2 = new Error(`Unsupported target for WeCom: ${params.to}`);
8020
+ console.error(`[wecom] sendText failed: ${error2.message}`);
8021
+ return {
8022
+ channel: "wecom",
8023
+ ok: false,
8024
+ messageId: "",
8025
+ error: error2
8026
+ };
8027
+ }
8028
+ console.log(
8029
+ `[wecom] sendText stream context: runId=${streamContext.runId ?? "-"}, sessionKey=${streamContext.sessionKey ?? "-"}`
8030
+ );
8031
+ const replyTarget = resolveReplyTargetToken(parsed);
8032
+ const streamAccepted = appendWecomActiveStreamChunk({
8033
+ accountId: account.accountId,
8034
+ to: replyTarget,
8035
+ chunk: params.text,
8036
+ sessionKey: streamContext.sessionKey,
8037
+ runId: streamContext.runId
8038
+ });
8039
+ if (streamAccepted) {
8040
+ return {
8041
+ channel: "wecom",
8042
+ ok: true,
8043
+ messageId: `stream:${Date.now()}`
8044
+ };
8045
+ }
8046
+ const error = new Error(
8047
+ `No active stream available for ${replyTarget}. WeCom message tool is stream-only in current mode.`
8048
+ );
8049
+ console.error(`[wecom] sendText failed: ${error.message}`);
5418
8050
  return {
5419
8051
  channel: "wecom",
5420
8052
  ok: false,
5421
8053
  messageId: "",
5422
- error: new Error("WeCom intelligent bot only supports replying within callbacks (no standalone sendText).")
8054
+ error
5423
8055
  };
8056
+ },
8057
+ sendMedia: async (params) => {
8058
+ console.log(`[wecom] sendMedia called: to=${params.to}, mediaUrl=${params.mediaUrl}`);
8059
+ const account = resolveWecomAccount({ cfg: params.cfg, accountId: params.accountId });
8060
+ const parsed = parseDirectTarget(params.to);
8061
+ const streamContext = resolveStreamContext(params);
8062
+ if (!parsed) {
8063
+ const error = new Error(`Unsupported target for WeCom: ${params.to}`);
8064
+ console.error(`[wecom] sendMedia failed: ${error.message}`);
8065
+ return {
8066
+ channel: "wecom",
8067
+ ok: false,
8068
+ messageId: "",
8069
+ error
8070
+ };
8071
+ }
8072
+ console.log(
8073
+ `[wecom] sendMedia stream context: runId=${streamContext.runId ?? "-"}, sessionKey=${streamContext.sessionKey ?? "-"}`
8074
+ );
8075
+ try {
8076
+ let publicMediaUrl = params.mediaUrl.trim();
8077
+ if (!isHttpUrl3(publicMediaUrl)) {
8078
+ const localPath = normalizeLocalPath2(publicMediaUrl);
8079
+ await ensureReadableFile(localPath);
8080
+ const baseUrl = getAccountPublicBaseUrl(account.accountId);
8081
+ if (!baseUrl) {
8082
+ throw new Error(
8083
+ "No public base URL captured yet for this account. Send one inbound message first, then retry media reply."
8084
+ );
8085
+ }
8086
+ const temp = await registerTempLocalMedia({
8087
+ filePath: localPath,
8088
+ fileName: path3__default.basename(localPath)
8089
+ });
8090
+ publicMediaUrl = buildTempMediaUrl({
8091
+ baseUrl,
8092
+ id: temp.id,
8093
+ token: temp.token,
8094
+ fileName: temp.fileName
8095
+ });
8096
+ }
8097
+ const mediaType = detectOutboundMediaType(publicMediaUrl, params.mimeType);
8098
+ const markdown = buildMediaMarkdown({
8099
+ mediaUrl: publicMediaUrl,
8100
+ mediaType,
8101
+ caption: params.text
8102
+ });
8103
+ const replyTarget = resolveReplyTargetToken(parsed);
8104
+ const streamAccepted = appendWecomActiveStreamChunk({
8105
+ accountId: account.accountId,
8106
+ to: replyTarget,
8107
+ chunk: markdown,
8108
+ sessionKey: streamContext.sessionKey,
8109
+ runId: streamContext.runId
8110
+ });
8111
+ if (streamAccepted) {
8112
+ console.log(
8113
+ `[wecom] sendMedia success (stream append): type=${mediaType}, to=${replyTarget}`
8114
+ );
8115
+ return {
8116
+ channel: "wecom",
8117
+ ok: true,
8118
+ messageId: `stream:${Date.now()}`
8119
+ };
8120
+ }
8121
+ const error = new Error(
8122
+ `No active stream available for ${replyTarget}. WeCom message tool is stream-only in current mode.`
8123
+ );
8124
+ console.error(`[wecom] sendMedia failed: ${error.message}`);
8125
+ return {
8126
+ channel: "wecom",
8127
+ ok: false,
8128
+ messageId: "",
8129
+ error
8130
+ };
8131
+ } catch (err) {
8132
+ console.error(`[wecom] sendMedia failed: ${formatError(err)}`);
8133
+ return {
8134
+ channel: "wecom",
8135
+ ok: false,
8136
+ messageId: "",
8137
+ error: err instanceof Error ? err : new Error(String(err))
8138
+ };
8139
+ }
8140
+ },
8141
+ sendTemplateCard: async (params) => {
8142
+ console.log(`[wecom] sendTemplateCard called: to=${params.to}`);
8143
+ const account = resolveWecomAccount({ cfg: params.cfg, accountId: params.accountId });
8144
+ const parsed = parseDirectTarget(params.to);
8145
+ if (!parsed) {
8146
+ const error = new Error(`Unsupported target for WeCom: ${params.to}`);
8147
+ console.error(`[wecom] sendTemplateCard failed: ${error.message}`);
8148
+ return {
8149
+ channel: "wecom",
8150
+ ok: false,
8151
+ messageId: "",
8152
+ error
8153
+ };
8154
+ }
8155
+ if (parsed.kind !== "user") {
8156
+ const error = new Error("WeCom active template_card reply is only supported in single chat targets (user:<userid>).");
8157
+ console.error(`[wecom] sendTemplateCard failed: ${error.message}`);
8158
+ return {
8159
+ channel: "wecom",
8160
+ ok: false,
8161
+ messageId: "",
8162
+ error
8163
+ };
8164
+ }
8165
+ const responseUrl = consumeResponseUrl({
8166
+ accountId: account.accountId,
8167
+ to: resolveReplyTargetToken(parsed)
8168
+ });
8169
+ if (!responseUrl) {
8170
+ const error = new Error(
8171
+ `No response_url available for ${resolveReplyTargetToken(parsed)}. WeCom smart bot can only reply after inbound messages.`
8172
+ );
8173
+ console.error(`[wecom] sendTemplateCard failed: ${error.message}`);
8174
+ return {
8175
+ channel: "wecom",
8176
+ ok: false,
8177
+ messageId: "",
8178
+ error
8179
+ };
8180
+ }
8181
+ try {
8182
+ await postWecomResponse(responseUrl, {
8183
+ msgtype: "template_card",
8184
+ template_card: params.templateCard ?? {}
8185
+ });
8186
+ return {
8187
+ channel: "wecom",
8188
+ ok: true,
8189
+ messageId: `response:${Date.now()}`
8190
+ };
8191
+ } catch (err) {
8192
+ console.error(`[wecom] sendTemplateCard failed: ${formatError(err)}`);
8193
+ return {
8194
+ channel: "wecom",
8195
+ ok: false,
8196
+ messageId: "",
8197
+ error: err instanceof Error ? err : new Error(String(err))
8198
+ };
8199
+ }
5424
8200
  }
5425
8201
  },
5426
8202
  gateway: {
@@ -5428,7 +8204,9 @@ var wecomPlugin = {
5428
8204
  ctx.setStatus?.({ accountId: ctx.accountId });
5429
8205
  if (ctx.runtime) {
5430
8206
  const candidate = ctx.runtime;
5431
- if (candidate.channel?.routing?.resolveAgentRoute && candidate.channel?.reply?.dispatchReplyFromConfig) {
8207
+ const hasRouting = Boolean(candidate.channel?.routing?.resolveAgentRoute);
8208
+ const hasReply = Boolean(candidate.channel?.reply?.dispatchReplyWithBufferedBlockDispatcher) || Boolean(candidate.channel?.reply?.dispatchReplyFromConfig);
8209
+ if (hasRouting && hasReply) {
5432
8210
  setWecomRuntime(ctx.runtime);
5433
8211
  }
5434
8212
  }
@@ -5438,7 +8216,7 @@ var wecomPlugin = {
5438
8216
  ctx.setStatus?.({ accountId: ctx.accountId, running: false, configured: false });
5439
8217
  return;
5440
8218
  }
5441
- const path2 = (account.config.webhookPath ?? "/wecom").trim();
8219
+ const path5 = (account.config.webhookPath ?? "/wecom").trim();
5442
8220
  const unregister = registerWecomWebhookTarget({
5443
8221
  account,
5444
8222
  config: ctx.cfg ?? {},
@@ -5446,18 +8224,18 @@ var wecomPlugin = {
5446
8224
  log: ctx.log?.info ?? console.log,
5447
8225
  error: ctx.log?.error ?? console.error
5448
8226
  },
5449
- path: path2,
8227
+ path: path5,
5450
8228
  statusSink: (patch) => ctx.setStatus?.({ accountId: ctx.accountId, ...patch })
5451
8229
  });
5452
8230
  const existing = unregisterHooks.get(ctx.accountId);
5453
8231
  if (existing) existing();
5454
8232
  unregisterHooks.set(ctx.accountId, unregister);
5455
- ctx.log?.info(`[wecom] webhook registered at ${path2} for account ${ctx.accountId}`);
8233
+ ctx.log?.info(`[wecom] webhook registered at ${path5} for account ${ctx.accountId}`);
5456
8234
  ctx.setStatus?.({
5457
8235
  accountId: ctx.accountId,
5458
8236
  running: true,
5459
8237
  configured: true,
5460
- webhookPath: path2,
8238
+ webhookPath: path5,
5461
8239
  lastStartAt: Date.now()
5462
8240
  });
5463
8241
  },
@@ -5483,6 +8261,7 @@ var plugin = {
5483
8261
  properties: {}
5484
8262
  },
5485
8263
  register(api) {
8264
+ registerChinaSetupCli(api, { channels: ["wecom"] });
5486
8265
  if (api.runtime) {
5487
8266
  setWecomRuntime(api.runtime);
5488
8267
  }