@satorijs/adapter-lark 3.11.9 → 3.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/lib/bot.d.ts +5 -5
  2. package/lib/http.d.ts +6 -3
  3. package/lib/index.cjs +293 -223
  4. package/lib/types/acs.d.ts +4 -1
  5. package/lib/types/apaas.d.ts +152 -0
  6. package/lib/types/application.d.ts +20 -4
  7. package/lib/types/approval.d.ts +0 -13
  8. package/lib/types/attendance.d.ts +11 -5
  9. package/lib/types/authen.d.ts +8 -2
  10. package/lib/types/bitable.d.ts +25 -4
  11. package/lib/types/board.d.ts +17 -0
  12. package/lib/types/calendar.d.ts +16 -5
  13. package/lib/types/contact.d.ts +55 -12
  14. package/lib/types/corehr.d.ts +754 -142
  15. package/lib/types/drive.d.ts +20 -3
  16. package/lib/types/ehr.d.ts +11 -2
  17. package/lib/types/helpdesk.d.ts +15 -6
  18. package/lib/types/hire.d.ts +13 -13
  19. package/lib/types/human_authentication.d.ts +1 -1
  20. package/lib/types/im.d.ts +76 -20
  21. package/lib/types/index.d.ts +712 -115
  22. package/lib/types/mail.d.ts +106 -16
  23. package/lib/types/search.d.ts +4 -1
  24. package/lib/ws.d.ts +30 -0
  25. package/package.json +6 -3
  26. package/src/bot.ts +28 -15
  27. package/src/http.ts +10 -4
  28. package/src/types/acs.ts +4 -1
  29. package/src/types/apaas.ts +185 -0
  30. package/src/types/application.ts +20 -4
  31. package/src/types/approval.ts +0 -15
  32. package/src/types/attendance.ts +11 -5
  33. package/src/types/authen.ts +8 -2
  34. package/src/types/bitable.ts +25 -4
  35. package/src/types/board.ts +22 -0
  36. package/src/types/calendar.ts +16 -5
  37. package/src/types/contact.ts +55 -12
  38. package/src/types/corehr.ts +796 -142
  39. package/src/types/drive.ts +20 -3
  40. package/src/types/ehr.ts +11 -2
  41. package/src/types/helpdesk.ts +15 -6
  42. package/src/types/hire.ts +17 -17
  43. package/src/types/human_authentication.ts +1 -1
  44. package/src/types/im.ts +76 -20
  45. package/src/types/index.ts +738 -115
  46. package/src/types/mail.ts +106 -16
  47. package/src/types/search.ts +4 -1
  48. package/src/ws.ts +183 -0
  49. package/lib/types/api.d.ts +0 -28510
  50. package/lib/types/internal.d.ts +0 -21
  51. package/lib/types/message/content.d.ts +0 -433
  52. package/lib/types/message/index.d.ts +0 -95
package/lib/index.cjs CHANGED
@@ -39,7 +39,7 @@ __export(index_exports, {
39
39
  module.exports = __toCommonJS(index_exports);
40
40
 
41
41
  // src/bot.ts
42
- var import_core5 = require("@satorijs/core");
42
+ var import_core6 = require("@satorijs/core");
43
43
 
44
44
  // src/http.ts
45
45
  var import_core2 = require("@satorijs/core");
@@ -48,120 +48,20 @@ var import_core2 = require("@satorijs/core");
48
48
  var import_crypto = __toESM(require("crypto"), 1);
49
49
  var import_core = require("@satorijs/core");
50
50
 
51
- // node_modules/cosmokit/lib/index.mjs
52
- var __defProp2 = Object.defineProperty;
53
- var __name2 = /* @__PURE__ */ __name((target, value) => __defProp2(target, "name", { value, configurable: true }), "__name");
54
- function noop() {
55
- }
56
- __name(noop, "noop");
57
- __name2(noop, "noop");
58
- function isNullable(value) {
59
- return value === null || value === void 0;
60
- }
61
- __name(isNullable, "isNullable");
62
- __name2(isNullable, "isNullable");
63
- function isNonNullable(value) {
64
- return !isNullable(value);
65
- }
66
- __name(isNonNullable, "isNonNullable");
67
- __name2(isNonNullable, "isNonNullable");
68
- function isPlainObject(data) {
69
- return data && typeof data === "object" && !Array.isArray(data);
70
- }
71
- __name(isPlainObject, "isPlainObject");
72
- __name2(isPlainObject, "isPlainObject");
73
- function filterKeys(object, filter) {
74
- return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
75
- }
76
- __name(filterKeys, "filterKeys");
77
- __name2(filterKeys, "filterKeys");
78
- function mapValues(object, transform) {
79
- return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
80
- }
81
- __name(mapValues, "mapValues");
82
- __name2(mapValues, "mapValues");
83
- function pick(source, keys, forced) {
84
- if (!keys) return { ...source };
85
- const result = {};
86
- for (const key of keys) {
87
- if (forced || source[key] !== void 0) result[key] = source[key];
88
- }
89
- return result;
90
- }
91
- __name(pick, "pick");
92
- __name2(pick, "pick");
93
- function omit(source, keys) {
94
- if (!keys) return { ...source };
95
- const result = { ...source };
96
- for (const key of keys) {
97
- Reflect.deleteProperty(result, key);
98
- }
99
- return result;
100
- }
101
- __name(omit, "omit");
102
- __name2(omit, "omit");
103
- function defineProperty(object, key, value) {
104
- return Object.defineProperty(object, key, { writable: true, value, enumerable: false });
105
- }
106
- __name(defineProperty, "defineProperty");
107
- __name2(defineProperty, "defineProperty");
108
- function contain(array1, array2) {
109
- return array2.every((item) => array1.includes(item));
110
- }
111
- __name(contain, "contain");
112
- __name2(contain, "contain");
113
- function intersection(array1, array2) {
114
- return array1.filter((item) => array2.includes(item));
115
- }
116
- __name(intersection, "intersection");
117
- __name2(intersection, "intersection");
118
- function difference(array1, array2) {
119
- return array1.filter((item) => !array2.includes(item));
120
- }
121
- __name(difference, "difference");
122
- __name2(difference, "difference");
123
- function union(array1, array2) {
124
- return Array.from(/* @__PURE__ */ new Set([...array1, ...array2]));
125
- }
126
- __name(union, "union");
127
- __name2(union, "union");
128
- function deduplicate(array) {
129
- return [...new Set(array)];
130
- }
131
- __name(deduplicate, "deduplicate");
132
- __name2(deduplicate, "deduplicate");
133
- function remove(list, item) {
134
- const index = list?.indexOf(item);
135
- if (index >= 0) {
136
- list.splice(index, 1);
137
- return true;
138
- } else {
139
- return false;
140
- }
141
- }
142
- __name(remove, "remove");
143
- __name2(remove, "remove");
144
- function makeArray(source) {
145
- return Array.isArray(source) ? source : isNullable(source) ? [] : [source];
146
- }
147
- __name(makeArray, "makeArray");
148
- __name2(makeArray, "makeArray");
51
+ // ../../node_modules/cosmokit/lib/index.mjs
149
52
  function is(type, value) {
150
53
  if (arguments.length === 1) return (value2) => is(type, value2);
151
54
  return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
152
55
  }
153
56
  __name(is, "is");
154
- __name2(is, "is");
155
57
  function isArrayBufferLike(value) {
156
58
  return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
157
59
  }
158
60
  __name(isArrayBufferLike, "isArrayBufferLike");
159
- __name2(isArrayBufferLike, "isArrayBufferLike");
160
61
  function isArrayBufferSource(value) {
161
62
  return isArrayBufferLike(value) || ArrayBuffer.isView(value);
162
63
  }
163
64
  __name(isArrayBufferSource, "isArrayBufferSource");
164
- __name2(isArrayBufferSource, "isArrayBufferSource");
165
65
  var Binary;
166
66
  ((Binary2) => {
167
67
  Binary2.is = isArrayBufferLike;
@@ -175,8 +75,8 @@ var Binary;
175
75
  }
176
76
  __name(fromSource, "fromSource");
177
77
  Binary2.fromSource = fromSource;
178
- __name2(fromSource, "fromSource");
179
78
  function toBase64(source) {
79
+ source = fromSource(source);
180
80
  if (typeof Buffer !== "undefined") {
181
81
  return Buffer.from(source).toString("base64");
182
82
  }
@@ -189,21 +89,19 @@ var Binary;
189
89
  }
190
90
  __name(toBase64, "toBase64");
191
91
  Binary2.toBase64 = toBase64;
192
- __name2(toBase64, "toBase64");
193
92
  function fromBase64(source) {
194
93
  if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
195
94
  return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
196
95
  }
197
96
  __name(fromBase64, "fromBase64");
198
97
  Binary2.fromBase64 = fromBase64;
199
- __name2(fromBase64, "fromBase64");
200
98
  function toHex(source) {
99
+ source = fromSource(source);
201
100
  if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
202
101
  return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
203
102
  }
204
103
  __name(toHex, "toHex");
205
104
  Binary2.toHex = toHex;
206
- __name2(toHex, "toHex");
207
105
  function fromHex(source) {
208
106
  if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
209
107
  const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
@@ -215,87 +113,50 @@ var Binary;
215
113
  }
216
114
  __name(fromHex, "fromHex");
217
115
  Binary2.fromHex = fromHex;
218
- __name2(fromHex, "fromHex");
219
116
  })(Binary || (Binary = {}));
220
117
  var base64ToArrayBuffer = Binary.fromBase64;
221
118
  var arrayBufferToBase64 = Binary.toBase64;
222
119
  var hexToArrayBuffer = Binary.fromHex;
223
120
  var arrayBufferToHex = Binary.toHex;
224
- function clone(source) {
225
- if (!source || typeof source !== "object") return source;
226
- if (Array.isArray(source)) return source.map(clone);
227
- if (is("Date", source)) return new Date(source.valueOf());
228
- if (is("RegExp", source)) return new RegExp(source.source, source.flags);
229
- if (isArrayBufferLike(source)) return source.slice(0);
230
- if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
231
- const result = Object.create(Object.getPrototypeOf(source));
232
- for (const key of Reflect.ownKeys(source)) {
233
- Reflect.defineProperty(result, key, Reflect.getOwnPropertyDescriptor(source, key));
234
- }
235
- return result;
236
- }
237
- __name(clone, "clone");
238
- __name2(clone, "clone");
239
- function deepEqual(a, b, strict) {
240
- if (a === b) return true;
241
- if (!strict && isNullable(a) && isNullable(b)) return true;
242
- if (typeof a !== typeof b) return false;
243
- if (typeof a !== "object") return false;
244
- if (!a || !b) return false;
245
- function check(test, then) {
246
- return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
247
- }
248
- __name(check, "check");
249
- __name2(check, "check");
250
- return check(Array.isArray, (a2, b2) => a2.length === b2.length && a2.every((item, index) => deepEqual(item, b2[index]))) ?? check(is("Date"), (a2, b2) => a2.valueOf() === b2.valueOf()) ?? check(is("RegExp"), (a2, b2) => a2.source === b2.source && a2.flags === b2.flags) ?? check(isArrayBufferLike, (a2, b2) => {
251
- if (a2.byteLength !== b2.byteLength) return false;
252
- const viewA = new Uint8Array(a2);
253
- const viewB = new Uint8Array(b2);
254
- for (let i = 0; i < viewA.length; i++) {
255
- if (viewA[i] !== viewB[i]) return false;
121
+ function tokenize(source, delimiters, delimiter) {
122
+ const output = [];
123
+ let state = 0;
124
+ for (let i = 0; i < source.length; i++) {
125
+ const code = source.charCodeAt(i);
126
+ if (code >= 65 && code <= 90) {
127
+ if (state === 1) {
128
+ const next = source.charCodeAt(i + 1);
129
+ if (next >= 97 && next <= 122) {
130
+ output.push(delimiter);
131
+ }
132
+ output.push(code + 32);
133
+ } else {
134
+ if (state !== 0) {
135
+ output.push(delimiter);
136
+ }
137
+ output.push(code + 32);
138
+ }
139
+ state = 1;
140
+ } else if (code >= 97 && code <= 122) {
141
+ output.push(code);
142
+ state = 2;
143
+ } else if (delimiters.includes(code)) {
144
+ if (state !== 0) {
145
+ output.push(delimiter);
146
+ }
147
+ state = 0;
148
+ } else {
149
+ output.push(code);
256
150
  }
257
- return true;
258
- }) ?? Object.keys({ ...a, ...b }).every((key) => deepEqual(a[key], b[key], strict));
259
- }
260
- __name(deepEqual, "deepEqual");
261
- __name2(deepEqual, "deepEqual");
262
- function capitalize(source) {
263
- return source.charAt(0).toUpperCase() + source.slice(1);
264
- }
265
- __name(capitalize, "capitalize");
266
- __name2(capitalize, "capitalize");
267
- function uncapitalize(source) {
268
- return source.charAt(0).toLowerCase() + source.slice(1);
269
- }
270
- __name(uncapitalize, "uncapitalize");
271
- __name2(uncapitalize, "uncapitalize");
272
- function camelCase(source) {
273
- return source.replace(/[_-][a-z]/g, (str) => str.slice(1).toUpperCase());
151
+ }
152
+ return String.fromCharCode(...output);
274
153
  }
275
- __name(camelCase, "camelCase");
276
- __name2(camelCase, "camelCase");
154
+ __name(tokenize, "tokenize");
277
155
  function paramCase(source) {
278
- return uncapitalize(source).replace(/_/g, "-").replace(/.[A-Z]+/g, (str) => str[0] + "-" + str.slice(1).toLowerCase());
156
+ return tokenize(source, [45, 95], 45);
279
157
  }
280
158
  __name(paramCase, "paramCase");
281
- __name2(paramCase, "paramCase");
282
- function snakeCase(source) {
283
- return uncapitalize(source).replace(/-/g, "_").replace(/.[A-Z]+/g, (str) => str[0] + "_" + str.slice(1).toLowerCase());
284
- }
285
- __name(snakeCase, "snakeCase");
286
- __name2(snakeCase, "snakeCase");
287
159
  var hyphenate = paramCase;
288
- function trimSlash(source) {
289
- return source.replace(/\/$/, "");
290
- }
291
- __name(trimSlash, "trimSlash");
292
- __name2(trimSlash, "trimSlash");
293
- function sanitize(source) {
294
- if (!source.startsWith("/")) source = "/" + source;
295
- return trimSlash(source);
296
- }
297
- __name(sanitize, "sanitize");
298
- __name2(sanitize, "sanitize");
299
160
  var Time;
300
161
  ((Time22) => {
301
162
  Time22.millisecond = 1;
@@ -310,13 +171,11 @@ var Time;
310
171
  }
311
172
  __name(setTimezoneOffset, "setTimezoneOffset");
312
173
  Time22.setTimezoneOffset = setTimezoneOffset;
313
- __name2(setTimezoneOffset, "setTimezoneOffset");
314
174
  function getTimezoneOffset() {
315
175
  return timezoneOffset;
316
176
  }
317
177
  __name(getTimezoneOffset, "getTimezoneOffset");
318
178
  Time22.getTimezoneOffset = getTimezoneOffset;
319
- __name2(getTimezoneOffset, "getTimezoneOffset");
320
179
  function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
321
180
  if (typeof date === "number") date = new Date(date);
322
181
  if (offset === void 0) offset = timezoneOffset;
@@ -324,7 +183,6 @@ var Time;
324
183
  }
325
184
  __name(getDateNumber, "getDateNumber");
326
185
  Time22.getDateNumber = getDateNumber;
327
- __name2(getDateNumber, "getDateNumber");
328
186
  function fromDateNumber(value, offset) {
329
187
  const date = new Date(value * Time22.day);
330
188
  if (offset === void 0) offset = timezoneOffset;
@@ -332,7 +190,6 @@ var Time;
332
190
  }
333
191
  __name(fromDateNumber, "fromDateNumber");
334
192
  Time22.fromDateNumber = fromDateNumber;
335
- __name2(fromDateNumber, "fromDateNumber");
336
193
  const numeric = /\d+(?:\.\d+)?/.source;
337
194
  const timeRegExp = new RegExp(`^${[
338
195
  "w(?:eek(?:s)?)?",
@@ -348,7 +205,6 @@ var Time;
348
205
  }
349
206
  __name(parseTime, "parseTime");
350
207
  Time22.parseTime = parseTime;
351
- __name2(parseTime, "parseTime");
352
208
  function parseDate(date) {
353
209
  const parsed = parseTime(date);
354
210
  if (parsed) {
@@ -362,7 +218,6 @@ var Time;
362
218
  }
363
219
  __name(parseDate, "parseDate");
364
220
  Time22.parseDate = parseDate;
365
- __name2(parseDate, "parseDate");
366
221
  function format(ms) {
367
222
  const abs = Math.abs(ms);
368
223
  if (abs >= Time22.day - Time22.hour / 2) {
@@ -378,19 +233,16 @@ var Time;
378
233
  }
379
234
  __name(format, "format");
380
235
  Time22.format = format;
381
- __name2(format, "format");
382
236
  function toDigits(source, length = 2) {
383
237
  return source.toString().padStart(length, "0");
384
238
  }
385
239
  __name(toDigits, "toDigits");
386
240
  Time22.toDigits = toDigits;
387
- __name2(toDigits, "toDigits");
388
241
  function template(template2, time = /* @__PURE__ */ new Date()) {
389
242
  return template2.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
390
243
  }
391
244
  __name(template, "template");
392
245
  Time22.template = template;
393
- __name2(template, "template");
394
246
  })(Time || (Time = {}));
395
247
 
396
248
  // src/utils.ts
@@ -684,7 +536,7 @@ var HttpServer = class extends import_core2.Adapter {
684
536
  const result = enabledSignatureVerify.some((bot2) => {
685
537
  const timestamp = ctx.get("X-Lark-Request-Timestamp");
686
538
  const nonce = ctx.get("X-Lark-Request-Nonce");
687
- const body2 = ctx.request.body[Symbol.for("unparsedBody")];
539
+ const body2 = ctx.request.body[/* @__PURE__ */ Symbol.for("unparsedBody")];
688
540
  const actualSignature = this.ciphers[bot2.config.appId]?.calculateSignature(timestamp, nonce, body2);
689
541
  if (actualSignature === signature) return true;
690
542
  else return false;
@@ -708,7 +560,7 @@ var HttpServer = class extends import_core2.Adapter {
708
560
  if (!result) return ctx.status = 403;
709
561
  }
710
562
  }
711
- bot.logger.debug("received decryped event: %o", body);
563
+ bot.logger.debug("received decrypted event: %o", body);
712
564
  this.dispatchSession(body);
713
565
  ctx.body = {};
714
566
  return ctx.status = 200;
@@ -752,16 +604,154 @@ var HttpServer = class extends import_core2.Adapter {
752
604
  };
753
605
  ((HttpServer2) => {
754
606
  HttpServer2.createConfig = /* @__PURE__ */ __name((path) => import_core2.Schema.object({
607
+ protocol: import_core2.Schema.const("http"),
755
608
  path: import_core2.Schema.string().role("url").description("要连接的服务器地址。").default(path),
756
609
  selfUrl: import_core2.Schema.string().role("link").description("服务器暴露在公网的地址。缺省时将使用全局配置。"),
610
+ encryptKey: import_core2.Schema.string().role("secret").description("机器人的 Encrypt Key。"),
611
+ verificationToken: import_core2.Schema.string().description("事件推送的验证令牌。"),
757
612
  verifyToken: import_core2.Schema.boolean().description("是否验证令牌。"),
758
613
  verifySignature: import_core2.Schema.boolean().description("是否验证签名。")
759
614
  }).description("服务端设置"), "createConfig");
760
615
  })(HttpServer || (HttpServer = {}));
761
616
 
762
- // src/message.ts
617
+ // src/ws.ts
763
618
  var import_core3 = require("@satorijs/core");
764
- var LarkMessageEncoder = class extends import_core3.MessageEncoder {
619
+ var import_light = __toESM(require("protobufjs/light"), 1);
620
+ var WsClient = class extends import_core3.Adapter.WsClient {
621
+ static {
622
+ __name(this, "WsClient");
623
+ }
624
+ _deviceId;
625
+ _serviceId;
626
+ _pingInterval = 9e4;
627
+ _ping;
628
+ _cache = {};
629
+ _frame;
630
+ constructor(ctx, bot) {
631
+ super(ctx, bot);
632
+ }
633
+ async prepare() {
634
+ this._frame = import_light.default.Root.fromJSON({
635
+ nested: {
636
+ Header: {
637
+ fields: {
638
+ key: { rule: "required", type: "string", id: 1 },
639
+ value: { rule: "required", type: "string", id: 2 }
640
+ }
641
+ },
642
+ Frame: {
643
+ fields: {
644
+ SeqID: { rule: "required", type: "uint64", id: 1 },
645
+ LogID: { rule: "required", type: "uint64", id: 2 },
646
+ service: { rule: "required", type: "int32", id: 3 },
647
+ method: { rule: "required", type: "int32", id: 4 },
648
+ headers: { rule: "repeated", type: "Header", id: 5 },
649
+ payloadEncoding: { type: "string", id: 6 },
650
+ payloadType: { type: "string", id: 7 },
651
+ payload: { type: "bytes", id: 8 },
652
+ LogIDNew: { type: "string", id: 9 }
653
+ }
654
+ }
655
+ }
656
+ }).lookupType("Frame");
657
+ const baseUrl = this.bot.config.baseURL ?? new URL(this.bot.config.endpoint).origin;
658
+ const { code, data: { URL: url, ClientConfig: config }, msg } = await this.bot.http.post(`${baseUrl}/callback/ws/endpoint`, {
659
+ AppID: this.bot.config.appId,
660
+ AppSecret: this.bot.config.appSecret
661
+ });
662
+ if (code !== 0) throw new Error(`failed to get gateway url: ${code} ${msg}`);
663
+ const urlObj = new URL(url);
664
+ this._deviceId = urlObj.searchParams.get("device_id");
665
+ this._serviceId = +urlObj.searchParams.get("service_id");
666
+ this._pingInterval = config.PingInterval * 1e3;
667
+ return this.bot.ctx.http.ws(url);
668
+ }
669
+ ping() {
670
+ if (!this.socket || this.bot.status !== import_core3.Universal.Status.ONLINE) {
671
+ clearTimeout(this._ping);
672
+ return;
673
+ }
674
+ const frame = {
675
+ headers: [{
676
+ key: "type",
677
+ value: "ping" /* ping */
678
+ }],
679
+ service: this._serviceId,
680
+ method: 0 /* control */,
681
+ SeqID: 0,
682
+ LogID: 0
683
+ };
684
+ this.send(frame);
685
+ this._ping = setTimeout(() => this.ping(), this._pingInterval);
686
+ }
687
+ async accept() {
688
+ await this.bot.initialize();
689
+ this.socket.addEventListener("message", async ({ data }) => {
690
+ const frame = this._frame.decode(new Uint8Array(data));
691
+ const headers = (frame.headers ?? []).reduce((acc, cur) => {
692
+ acc[cur.key] = cur.value;
693
+ return acc;
694
+ }, {});
695
+ if (frame.method === 0 /* control */ && headers.type === "pong" /* pong */) {
696
+ this.bot.logger.debug("pong");
697
+ return;
698
+ }
699
+ if (frame.method === 1 /* data */) {
700
+ if (headers.type !== "event" /* event */) return;
701
+ const data2 = this.retrieve({
702
+ message_id: headers.message_id,
703
+ sum: +headers.sum,
704
+ seq: +headers.seq,
705
+ data: frame.payload
706
+ });
707
+ if (!data2) return;
708
+ const body = JSON.parse(Buffer.from(data2).toString("utf8"));
709
+ if (!body.header) return;
710
+ this.bot.logger.info("received event: %o", body);
711
+ body.type = body.header.event_type;
712
+ const session = await adaptSession(this.bot, body);
713
+ this.bot.dispatch(session);
714
+ this.send({
715
+ ...frame,
716
+ headers: [...frame.headers, { key: "biz_rt", value: "0" }],
717
+ payload: Buffer.from(JSON.stringify({ code: 200 }))
718
+ });
719
+ }
720
+ });
721
+ this.socket.addEventListener("close", (e) => {
722
+ clearTimeout(this._ping);
723
+ this.bot.offline();
724
+ });
725
+ this.ping();
726
+ }
727
+ send(frame) {
728
+ const encoded = this._frame.encode(frame).finish();
729
+ this.socket.send(encoded);
730
+ }
731
+ retrieve(seg) {
732
+ const { message_id, sum } = seg;
733
+ if (sum === 1) return seg.data;
734
+ if (!this._cache[message_id]) this._cache[message_id] = [];
735
+ this._cache[message_id].push(seg);
736
+ if (this._cache[message_id].length === sum) {
737
+ const data = Buffer.concat(this._cache[message_id].sort((a, b) => a.seq - b.seq).map((item) => item.data));
738
+ delete this._cache[message_id];
739
+ return data;
740
+ }
741
+ }
742
+ };
743
+ ((WsClient2) => {
744
+ WsClient2.Options = import_core3.Schema.intersect([
745
+ import_core3.Schema.object({
746
+ protocol: import_core3.Schema.const("ws").required()
747
+ }),
748
+ import_core3.Adapter.WsClientConfig
749
+ ]);
750
+ })(WsClient || (WsClient = {}));
751
+
752
+ // src/message.ts
753
+ var import_core4 = require("@satorijs/core");
754
+ var LarkMessageEncoder = class extends import_core4.MessageEncoder {
765
755
  static {
766
756
  __name(this, "LarkMessageEncoder");
767
757
  }
@@ -1304,7 +1294,7 @@ var LarkMessageEncoder = class extends import_core3.MessageEncoder {
1304
1294
  };
1305
1295
 
1306
1296
  // src/internal.ts
1307
- var import_core4 = require("@satorijs/core");
1297
+ var import_core5 = require("@satorijs/core");
1308
1298
  var Internal = class _Internal {
1309
1299
  static {
1310
1300
  __name(this, "Internal");
@@ -1322,7 +1312,7 @@ var Internal = class _Internal {
1322
1312
  static _assertResponse(bot, response) {
1323
1313
  if (!response.data.code) return;
1324
1314
  bot.logger.debug("response: %o", response.data);
1325
- const error = new import_core4.HTTP.Error(`request failed`);
1315
+ const error = new import_core5.HTTP.Error(`request failed`);
1326
1316
  error.response = response;
1327
1317
  throw error;
1328
1318
  }
@@ -1346,7 +1336,7 @@ var Internal = class _Internal {
1346
1336
  for (const path in routes) {
1347
1337
  for (const key in routes[path]) {
1348
1338
  const method = key;
1349
- for (let route of (0, import_core4.makeArray)(routes[path][method])) {
1339
+ for (let route of (0, import_core5.makeArray)(routes[path][method])) {
1350
1340
  if (typeof route === "string") {
1351
1341
  route = { name: route };
1352
1342
  }
@@ -1400,16 +1390,16 @@ var Internal = class _Internal {
1400
1390
  iterArgs[argIndex] = { ...args[argIndex] };
1401
1391
  let pagination;
1402
1392
  result.next = async function() {
1403
- pagination ??= await this[Symbol.for("satori.pagination")]();
1393
+ pagination ??= await this[/* @__PURE__ */ Symbol.for("satori.pagination")]();
1404
1394
  if (pagination.data.length) return { done: false, value: pagination.data.shift() };
1405
1395
  if (!pagination.next) return { done: true, value: void 0 };
1406
- pagination = await this[Symbol.for("satori.pagination")]();
1396
+ pagination = await this[/* @__PURE__ */ Symbol.for("satori.pagination")]();
1407
1397
  return this.next();
1408
1398
  };
1409
1399
  result[Symbol.asyncIterator] = function() {
1410
1400
  return this;
1411
1401
  };
1412
- result[Symbol.for("satori.pagination")] = async () => {
1402
+ result[/* @__PURE__ */ Symbol.for("satori.pagination")] = async () => {
1413
1403
  const data = await impl(this, ...iterArgs);
1414
1404
  iterArgs[argIndex].page_token = data[tokenKey];
1415
1405
  return {
@@ -1435,7 +1425,7 @@ var fileTypeMap = {
1435
1425
  xls: ["application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
1436
1426
  ppt: ["application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation"]
1437
1427
  };
1438
- var LarkBot = class extends import_core5.Bot {
1428
+ var LarkBot = class extends import_core6.Bot {
1439
1429
  static {
1440
1430
  __name(this, "LarkBot");
1441
1431
  }
@@ -1452,7 +1442,11 @@ var LarkBot = class extends import_core5.Bot {
1452
1442
  });
1453
1443
  this.assetsQuester = ctx.http;
1454
1444
  this.internal = new Internal(this);
1455
- ctx.plugin(HttpServer, this);
1445
+ if (config.protocol === "http") {
1446
+ ctx.plugin(HttpServer, this);
1447
+ } else if (config.protocol === "ws") {
1448
+ ctx.plugin(WsClient, this);
1449
+ }
1456
1450
  this.defineInternalRoute("/*path", async ({ params, method, headers, body, query }) => {
1457
1451
  const response = await this.http("/" + params.path, {
1458
1452
  method,
@@ -1481,7 +1475,8 @@ var LarkBot = class extends import_core5.Bot {
1481
1475
  this.online();
1482
1476
  }
1483
1477
  async refreshToken() {
1484
- let timeout = import_core5.Time.minute * 20;
1478
+ if (!this.isActive) return;
1479
+ let timeout = import_core6.Time.minute * 20;
1485
1480
  try {
1486
1481
  const { tenant_access_token: token } = await this.internal.auth.tenantAccessTokenInternal({
1487
1482
  app_id: this.config.appId,
@@ -1492,7 +1487,7 @@ var LarkBot = class extends import_core5.Bot {
1492
1487
  } catch (error) {
1493
1488
  this.logger.error("failed to refresh token, retrying in 10s");
1494
1489
  this.logger.error(error);
1495
- timeout = import_core5.Time.second * 10;
1490
+ timeout = import_core6.Time.second * 10;
1496
1491
  }
1497
1492
  if (this._refresher) clearTimeout(this._refresher);
1498
1493
  this._refresher = setTimeout(() => this.refreshToken(), timeout);
@@ -1510,7 +1505,7 @@ var LarkBot = class extends import_core5.Bot {
1510
1505
  const data = await this.internal.im.message.get(messageId);
1511
1506
  const message = await decodeMessage(this, data.items[0], recursive);
1512
1507
  const im = await this.internal.im.chat.get(channelId);
1513
- message.channel.type = im.chat_mode === "p2p" ? import_core5.Universal.Channel.Type.DIRECT : import_core5.Universal.Channel.Type.TEXT;
1508
+ message.channel.type = im.chat_mode === "p2p" ? import_core6.Universal.Channel.Type.DIRECT : import_core6.Universal.Channel.Type.TEXT;
1514
1509
  return message;
1515
1510
  }
1516
1511
  async getMessageList(channelId, before) {
@@ -1561,28 +1556,33 @@ var LarkBot = class extends import_core5.Bot {
1561
1556
  }
1562
1557
  };
1563
1558
  ((LarkBot2) => {
1564
- LarkBot2.Config = import_core5.Schema.intersect([
1565
- import_core5.Schema.object({
1566
- platform: import_core5.Schema.union(["feishu", "lark"]).required().description("平台名称。"),
1567
- appId: import_core5.Schema.string().required().description("机器人的应用 ID。"),
1568
- appSecret: import_core5.Schema.string().role("secret").required().description("机器人的应用密钥。"),
1569
- encryptKey: import_core5.Schema.string().role("secret").description("机器人的 Encrypt Key。"),
1570
- verificationToken: import_core5.Schema.string().description("事件推送的验证令牌。")
1559
+ LarkBot2.Config = import_core6.Schema.intersect([
1560
+ import_core6.Schema.object({
1561
+ platform: import_core6.Schema.union(["feishu", "lark"]).default("feishu").description("平台名称。"),
1562
+ appId: import_core6.Schema.string().required().description("机器人的应用 ID。"),
1563
+ appSecret: import_core6.Schema.string().role("secret").required().description("机器人的应用密钥。"),
1564
+ protocol: process.env.KOISHI_ENV === "browser" ? import_core6.Schema.const("ws").default("ws") : import_core6.Schema.union(["http", "ws"]).description("选择要使用的协议。").default("http")
1571
1565
  }),
1572
- import_core5.Schema.union([
1573
- import_core5.Schema.intersect([
1574
- import_core5.Schema.object({
1575
- platform: import_core5.Schema.const("feishu").required()
1566
+ import_core6.Schema.union([
1567
+ import_core6.Schema.intersect([
1568
+ import_core6.Schema.object({
1569
+ platform: import_core6.Schema.const("lark").required()
1576
1570
  }),
1577
- import_core5.HTTP.createConfig("https://open.feishu.cn/open-apis"),
1578
- HttpServer.createConfig("/feishu")
1571
+ import_core6.HTTP.createConfig("https://open.larksuite.com/open-apis"),
1572
+ import_core6.Schema.union([
1573
+ HttpServer.createConfig("/lark"),
1574
+ WsClient.Options
1575
+ ])
1579
1576
  ]),
1580
- import_core5.Schema.intersect([
1581
- import_core5.Schema.object({
1582
- platform: import_core5.Schema.const("lark").required()
1577
+ import_core6.Schema.intersect([
1578
+ import_core6.Schema.object({
1579
+ platform: import_core6.Schema.const("feishu")
1583
1580
  }),
1584
- import_core5.HTTP.createConfig("https://open.larksuite.com/open-apis"),
1585
- HttpServer.createConfig("/lark")
1581
+ import_core6.HTTP.createConfig("https://open.feishu.cn/open-apis"),
1582
+ import_core6.Schema.union([
1583
+ HttpServer.createConfig("/feishu"),
1584
+ WsClient.Options
1585
+ ])
1586
1586
  ])
1587
1587
  ])
1588
1588
  ]);
@@ -1609,6 +1609,7 @@ __export(types_exports, {
1609
1609
  CustomFieldValueType: () => CustomFieldValueType,
1610
1610
  CustomFieldValueUserType: () => CustomFieldValueUserType,
1611
1611
  DataSource: () => DataSource,
1612
+ DiagramType: () => DiagramType,
1612
1613
  Docx: () => Docx,
1613
1614
  Ehr: () => Ehr,
1614
1615
  EmployeeActiveStatusDirectory: () => EmployeeActiveStatusDirectory,
@@ -1631,6 +1632,8 @@ __export(types_exports, {
1631
1632
  Search: () => Search,
1632
1633
  SecurityAndCompliance: () => SecurityAndCompliance,
1633
1634
  SnapTo: () => SnapTo,
1635
+ StyleType: () => StyleType,
1636
+ SyntaxType: () => SyntaxType,
1634
1637
  Vc: () => Vc
1635
1638
  });
1636
1639
 
@@ -1909,6 +1912,21 @@ Internal.define({
1909
1912
  },
1910
1913
  "/apaas/v1/user_tasks/{task_id}/chat_group": {
1911
1914
  POST: "apaas.userTask.chatGroup"
1915
+ },
1916
+ "/apaas/v1/workspaces/{workspace_id}/tables/{table_name}/records": {
1917
+ GET: "apaas.workspace.table.recordsGet",
1918
+ POST: "apaas.workspace.table.recordsPost",
1919
+ PATCH: "apaas.workspace.table.recordsPatch",
1920
+ DELETE: "apaas.workspace.table.recordsDelete"
1921
+ },
1922
+ "/apaas/v1/workspaces/{workspace_id}/tables/{table_name}/records_batch_update": {
1923
+ PATCH: "apaas.workspace.table.recordsBatchUpdate"
1924
+ },
1925
+ "/apaas/v1/workspaces/{workspace_id}/views/{view_name}/records": {
1926
+ GET: "apaas.workspace.view.viewsGet"
1927
+ },
1928
+ "/apaas/v1/workspaces/{workspace_id}/sql_commands": {
1929
+ POST: "apaas.workspace.sqlCommands"
1912
1930
  }
1913
1931
  });
1914
1932
 
@@ -2107,8 +2125,7 @@ Internal.define({
2107
2125
  GET: "approval.get"
2108
2126
  },
2109
2127
  "/approval/v4/instances": {
2110
- POST: "approval.instance.create",
2111
- GET: { name: "approval.instance.list", pagination: { argIndex: 0, itemsKey: "instance_code_list" } }
2128
+ POST: "approval.instance.create"
2112
2129
  },
2113
2130
  "/approval/v4/instances/cancel": {
2114
2131
  POST: "approval.instance.cancel"
@@ -2606,6 +2623,9 @@ Internal.define({
2606
2623
  "/board/v1/whiteboards/{whiteboard_id}/download_as_image": {
2607
2624
  GET: { name: "board.whiteboard.downloadAsImage", type: "binary" }
2608
2625
  },
2626
+ "/board/v1/whiteboards/{whiteboard_id}/nodes/plantuml": {
2627
+ POST: "board.whiteboard.node.createPlantuml"
2628
+ },
2609
2629
  "/board/v1/whiteboards/{whiteboard_id}/nodes": {
2610
2630
  POST: "board.whiteboard.node.create",
2611
2631
  GET: "board.whiteboard.node.list"
@@ -3699,6 +3719,30 @@ Internal.define({
3699
3719
  "/corehr/v1/offboardings/search": {
3700
3720
  POST: { name: "corehr.offboarding.search", pagination: { argIndex: 1 } }
3701
3721
  },
3722
+ "/corehr/v2/signature_files/terminate": {
3723
+ POST: "corehr.signatureFile.terminate"
3724
+ },
3725
+ "/corehr/v2/signature_files": {
3726
+ GET: { name: "corehr.signatureFile.list", pagination: { argIndex: 0 } }
3727
+ },
3728
+ "/corehr/v2/signature_files/query": {
3729
+ POST: { name: "corehr.signatureFile.query", pagination: { argIndex: 1 } }
3730
+ },
3731
+ "/corehr/v2/signature_nodes/list_by_file_id": {
3732
+ GET: "corehr.signatureNode.listByFileId"
3733
+ },
3734
+ "/corehr/v2/signature_files/list_by_biz_id": {
3735
+ GET: "corehr.signatureFile.listByBizId"
3736
+ },
3737
+ "/corehr/v2/signature_files/{signature_file_id}/download": {
3738
+ POST: { name: "corehr.signatureFile.download", type: "binary" }
3739
+ },
3740
+ "/corehr/v2/signature_templates/search": {
3741
+ GET: "corehr.signatureTemplate.search"
3742
+ },
3743
+ "/corehr/v2/signature_template_info_with_thumbnails": {
3744
+ GET: { name: "corehr.signatureTemplateInfoWithThumbnail.list", pagination: { argIndex: 0 } }
3745
+ },
3702
3746
  "/corehr/v1/contracts": {
3703
3747
  POST: "corehr.contract.create",
3704
3748
  GET: { name: "corehr.contract.list", pagination: { argIndex: 0 } }
@@ -4750,9 +4794,6 @@ var Hire;
4750
4794
  })(OfferSchema = Hire2.OfferSchema || (Hire2.OfferSchema = {}));
4751
4795
  })(Hire || (Hire = {}));
4752
4796
  Internal.define({
4753
- "/hire/v1/portal_apply_schemas": {
4754
- GET: { name: "hire.portalApplySchema.list", pagination: { argIndex: 0 } }
4755
- },
4756
4797
  "/hire/v1/locations/query": {
4757
4798
  POST: { name: "hire.location.query", pagination: { argIndex: 1 } }
4758
4799
  },
@@ -4881,6 +4922,9 @@ Internal.define({
4881
4922
  "/hire/v1/referrals/get_by_application": {
4882
4923
  GET: "hire.referral.getByApplication"
4883
4924
  },
4925
+ "/hire/v1/portal_apply_schemas": {
4926
+ GET: { name: "hire.portalApplySchema.list", pagination: { argIndex: 0 } }
4927
+ },
4884
4928
  "/hire/v1/websites/{website_id}/channels": {
4885
4929
  POST: "hire.website.channel.create",
4886
4930
  GET: { name: "hire.website.channel.list", pagination: { argIndex: 1, itemsKey: "website_channel_list" } }
@@ -6861,6 +6905,21 @@ var DataSource = /* @__PURE__ */ ((DataSource2) => {
6861
6905
  DataSource2[DataSource2["DIR_SYNC_VISA_SCIM"] = 3] = "DIR_SYNC_VISA_SCIM";
6862
6906
  return DataSource2;
6863
6907
  })(DataSource || {});
6908
+ var DiagramType = /* @__PURE__ */ ((DiagramType2) => {
6909
+ DiagramType2[DiagramType2["UNKOWN"] = 0] = "UNKOWN";
6910
+ DiagramType2[DiagramType2["MIND_MAP"] = 1] = "MIND_MAP";
6911
+ DiagramType2[DiagramType2["SEQUENCE"] = 2] = "SEQUENCE";
6912
+ DiagramType2[DiagramType2["ACTIVITY"] = 3] = "ACTIVITY";
6913
+ DiagramType2[DiagramType2["CLASS"] = 4] = "CLASS";
6914
+ DiagramType2[DiagramType2["ER"] = 5] = "ER";
6915
+ DiagramType2[DiagramType2["FLOWCHART"] = 6] = "FLOWCHART";
6916
+ DiagramType2[DiagramType2["STATE"] = 7] = "STATE";
6917
+ DiagramType2[DiagramType2["COMPONENT_DIAGRAM"] = 8] = "COMPONENT_DIAGRAM";
6918
+ DiagramType2[DiagramType2["STREAMING_ACTIVITY"] = 101] = "STREAMING_ACTIVITY";
6919
+ DiagramType2[DiagramType2["STREAMING_SEQUENCE"] = 102] = "STREAMING_SEQUENCE";
6920
+ DiagramType2[DiagramType2["TIMELINE_GML"] = 201] = "TIMELINE_GML";
6921
+ return DiagramType2;
6922
+ })(DiagramType || {});
6864
6923
  var EmployeeActiveStatusDirectory = /* @__PURE__ */ ((EmployeeActiveStatusDirectory2) => {
6865
6924
  EmployeeActiveStatusDirectory2[EmployeeActiveStatusDirectory2["EmployeeActiveStatusDirectoryUnregister"] = 1] = "EmployeeActiveStatusDirectoryUnregister";
6866
6925
  EmployeeActiveStatusDirectory2[EmployeeActiveStatusDirectory2["EmployeeActiveStatusDirectoryRegister"] = 2] = "EmployeeActiveStatusDirectoryRegister";
@@ -6964,6 +7023,17 @@ var SnapTo = /* @__PURE__ */ ((SnapTo2) => {
6964
7023
  SnapTo2["Left"] = "left";
6965
7024
  return SnapTo2;
6966
7025
  })(SnapTo || {});
7026
+ var StyleType = /* @__PURE__ */ ((StyleType2) => {
7027
+ StyleType2[StyleType2["Board"] = 1] = "Board";
7028
+ StyleType2[StyleType2["Classic"] = 2] = "Classic";
7029
+ return StyleType2;
7030
+ })(StyleType || {});
7031
+ var SyntaxType = /* @__PURE__ */ ((SyntaxType2) => {
7032
+ SyntaxType2[SyntaxType2["UNKOWN"] = 0] = "UNKOWN";
7033
+ SyntaxType2[SyntaxType2["PLANT_UML"] = 1] = "PLANT_UML";
7034
+ SyntaxType2[SyntaxType2["MERMAID"] = 2] = "MERMAID";
7035
+ return SyntaxType2;
7036
+ })(SyntaxType || {});
6967
7037
 
6968
7038
  // src/index.ts
6969
7039
  var index_default = LarkBot;