alemonjs 2.1.17 → 2.1.19

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 (57) hide show
  1. package/lib/app/SinglyLinkedList.d.ts +1 -0
  2. package/lib/app/SinglyLinkedList.js +12 -6
  3. package/lib/app/define-platform.d.ts +1 -0
  4. package/lib/app/define-platform.js +3 -2
  5. package/lib/app/define-response.d.ts +0 -3
  6. package/lib/app/define-response.js +1 -5
  7. package/lib/app/define-router.d.ts +5 -0
  8. package/lib/app/define-router.js +21 -0
  9. package/lib/app/event-processor-callHandler.js +5 -15
  10. package/lib/app/event-processor-cycleFiles.d.ts +1 -0
  11. package/lib/app/event-processor-cycleFiles.js +19 -2
  12. package/lib/app/event-processor-cycleRoute.js +32 -7
  13. package/lib/app/event-processor-event.js +4 -4
  14. package/lib/app/event-processor-middleware.js +4 -4
  15. package/lib/app/event-processor.js +15 -6
  16. package/lib/app/hook-use-api.d.ts +14 -6
  17. package/lib/app/hook-use-api.js +80 -82
  18. package/lib/app/index.d.ts +1 -0
  19. package/lib/app/index.js +4 -3
  20. package/lib/app/load_modules/loadChild.js +6 -6
  21. package/lib/app/message-format.d.ts +30 -1
  22. package/lib/app/message-format.js +82 -1
  23. package/lib/app/store.d.ts +3 -3
  24. package/lib/app/store.js +23 -11
  25. package/lib/cbp/connects/base.d.ts +15 -0
  26. package/lib/cbp/connects/base.js +77 -0
  27. package/lib/cbp/connects/client.js +13 -65
  28. package/lib/cbp/connects/platform.js +11 -63
  29. package/lib/cbp/server/main.js +5 -25
  30. package/lib/client.js +0 -1
  31. package/lib/core/config.js +17 -8
  32. package/lib/core/variable.d.ts +2 -1
  33. package/lib/core/variable.js +3 -2
  34. package/lib/index.js +4 -3
  35. package/lib/types/event/index.d.ts +7 -0
  36. package/package.json +1 -1
  37. package/lib/app/define-chidren.d.ts +0 -2
  38. package/lib/app/define-chidren.js +0 -19
  39. package/lib/app/define-pl.ts +0 -0
  40. package/lib/cbp/core/connection-manager.d.ts +0 -18
  41. package/lib/cbp/core/connection-manager.js +0 -67
  42. package/lib/cbp/core/constants.d.ts +0 -19
  43. package/lib/cbp/core/constants.js +0 -23
  44. package/lib/cbp/core/load-balancer.d.ts +0 -37
  45. package/lib/cbp/core/load-balancer.js +0 -118
  46. package/lib/cbp/processor/request-handler.d.ts +0 -17
  47. package/lib/cbp/processor/request-handler.js +0 -65
  48. package/lib/polyfills/fs-promises.d.ts +0 -41
  49. package/lib/polyfills/fs-promises.js +0 -138
  50. package/lib/polyfills/fs.d.ts +0 -103
  51. package/lib/polyfills/fs.js +0 -229
  52. package/lib/polyfills/util-types.d.ts +0 -33
  53. package/lib/polyfills/util-types.js +0 -36
  54. package/lib/types/event/channal/index.d.ts +0 -10
  55. package/lib/types/event/channal/index.js +0 -1
  56. /package/lib/cbp/processor/{heandle.d.ts → handle.d.ts} +0 -0
  57. /package/lib/cbp/processor/{heandle.js → handle.js} +0 -0
@@ -5,6 +5,7 @@ declare class ListNode<T> {
5
5
  }
6
6
  export declare class SinglyLinkedList<T> {
7
7
  private head;
8
+ private tail;
8
9
  private size;
9
10
  private current;
10
11
  constructor(initialValues?: T[]);
@@ -8,10 +8,12 @@ class ListNode {
8
8
  }
9
9
  class SinglyLinkedList {
10
10
  head;
11
+ tail;
11
12
  size;
12
13
  current;
13
14
  constructor(initialValues) {
14
15
  this.head = null;
16
+ this.tail = null;
15
17
  this.size = 0;
16
18
  this.current = null;
17
19
  if (initialValues) {
@@ -22,13 +24,11 @@ class SinglyLinkedList {
22
24
  const newNode = new ListNode(data);
23
25
  if (!this.head) {
24
26
  this.head = newNode;
27
+ this.tail = newNode;
25
28
  }
26
29
  else {
27
- let current = this.head;
28
- while (current.next) {
29
- current = current.next;
30
- }
31
- current.next = newNode;
30
+ this.tail.next = newNode;
31
+ this.tail = newNode;
32
32
  }
33
33
  this.size++;
34
34
  }
@@ -42,11 +42,14 @@ class SinglyLinkedList {
42
42
  return this.current;
43
43
  }
44
44
  removeCurrent() {
45
- if (!this.head) {
45
+ if (!this.head || !this.current) {
46
46
  return;
47
47
  }
48
48
  if (this.current === this.head) {
49
49
  this.head = this.head.next;
50
+ if (!this.head) {
51
+ this.tail = null;
52
+ }
50
53
  this.current = null;
51
54
  this.size--;
52
55
  return;
@@ -57,6 +60,9 @@ class SinglyLinkedList {
57
60
  }
58
61
  if (previous && this.current) {
59
62
  previous.next = this.current.next;
63
+ if (this.current === this.tail) {
64
+ this.tail = previous;
65
+ }
60
66
  this.current = null;
61
67
  this.size--;
62
68
  }
@@ -1,5 +1,6 @@
1
1
  type Options = {
2
2
  main: () => any;
3
+ name?: string;
3
4
  };
4
5
  export declare const definePlatform: (options: Options) => () => any;
5
6
  export {};
@@ -1,13 +1,14 @@
1
1
  const definePlatform = (options) => {
2
+ const platformName = options.name || process.env.platform || 'unknown';
2
3
  const mainProcess = () => {
3
4
  ['SIGINT', 'SIGTERM', 'SIGQUIT', 'disconnect'].forEach(sig => {
4
5
  process?.on?.(sig, () => {
5
- logger.info?.(`[@alemonjs/qq-bot][${sig}] 收到信号,正在关闭...`);
6
+ logger.info?.(`[${platformName}][${sig}] 收到信号,正在关闭...`);
6
7
  setImmediate(() => process.exit(0));
7
8
  });
8
9
  });
9
10
  process?.on?.('exit', code => {
10
- logger.info?.(`[@alemonjs/qq-bot][exit] 进程退出,code=${code}`);
11
+ logger.info?.(`[${platformName}][exit] 进程退出,code=${code}`);
11
12
  });
12
13
  process.on('message', msg => {
13
14
  try {
@@ -1,5 +1,2 @@
1
1
  import { DefineResponseFunc } from '../types';
2
- export declare const lazy: <T extends {
3
- default: any;
4
- }>(fnc: () => Promise<T>) => (() => Promise<T["default"]>);
5
2
  export declare const defineResponse: DefineResponseFunc;
@@ -1,7 +1,3 @@
1
- const lazy = (fnc) => {
2
- const back = async () => (await fnc()).default;
3
- return back;
4
- };
5
1
  const defineResponse = responses => {
6
2
  return {
7
3
  current: responses
@@ -9,4 +5,4 @@ const defineResponse = responses => {
9
5
  };
10
6
  global.defineResponse = defineResponse;
11
7
 
12
- export { defineResponse, lazy };
8
+ export { defineResponse };
@@ -0,0 +1,5 @@
1
+ import { DefineRouterFunc } from '../types';
2
+ export declare const lazy: <T extends {
3
+ default: any;
4
+ }>(fnc: () => Promise<T>) => (() => Promise<T["default"]>);
5
+ export declare const defineRouter: DefineRouterFunc;
@@ -0,0 +1,21 @@
1
+ const lazy = (fnc) => {
2
+ let c = null;
3
+ const back = async () => {
4
+ if (c) {
5
+ return c;
6
+ }
7
+ const mod = await fnc();
8
+ console.warn('Lazy load module:', mod);
9
+ if (!mod || !mod.default) ;
10
+ c = mod.default;
11
+ return c;
12
+ };
13
+ return back;
14
+ };
15
+ const defineRouter = routes => {
16
+ return {
17
+ current: routes
18
+ };
19
+ };
20
+
21
+ export { defineRouter, lazy };
@@ -1,4 +1,3 @@
1
- import { isAsyncFunction } from 'util/types';
2
1
  import 'fs';
3
2
  import 'path';
4
3
  import 'yaml';
@@ -42,20 +41,11 @@ const createCallHandler = valueEvent => {
42
41
  return;
43
42
  }
44
43
  try {
45
- if (isAsyncFunction(currents[index])) {
46
- const res = await currents[index](valueEvent, (...cns) => {
47
- isNext = true;
48
- nextEvent(...cns);
49
- });
50
- onRes(res);
51
- }
52
- else {
53
- const res = currents[index](valueEvent, (...cns) => {
54
- isNext = true;
55
- nextEvent(...cns);
56
- });
57
- onRes(res);
58
- }
44
+ const res = await currents[index](valueEvent, (...cns) => {
45
+ isNext = true;
46
+ nextEvent(...cns);
47
+ });
48
+ onRes(res);
59
49
  }
60
50
  catch (err) {
61
51
  showErrorModule(err);
@@ -1,2 +1,3 @@
1
1
  import { Next, Events, EventKeys, StoreResponseItem } from '../types';
2
+ export declare const clearModuleCache: (path?: string) => void;
2
3
  export declare const createNextStep: <T extends EventKeys>(valueEvent: Events[T], select: T, next: Next, files: StoreResponseItem[], callHandler: (currents: any, nextEvent: any) => void) => Next;
@@ -3,9 +3,26 @@ import { showErrorModule } from '../core/utils.js';
3
3
  import { EventMessageText } from '../core/variable.js';
4
4
  import { ResponseMiddleware } from './store.js';
5
5
 
6
+ const moduleCache = new Map();
7
+ const clearModuleCache = (path) => {
8
+ if (path) {
9
+ moduleCache.delete(path);
10
+ }
11
+ else {
12
+ moduleCache.clear();
13
+ }
14
+ };
15
+ const loadModule = async (filePath) => {
16
+ if (moduleCache.has(filePath)) {
17
+ return moduleCache.get(filePath);
18
+ }
19
+ const mod = await import(`file://${filePath}`);
20
+ moduleCache.set(filePath, mod);
21
+ return mod;
22
+ };
6
23
  const callHandlerFile = async (valueEvent, select, file, nextStep, callback) => {
7
24
  try {
8
- const app = await import(`file://${file.path}`);
25
+ const app = await loadModule(file.path);
9
26
  if (!app?.default?.current || !app?.default?.select) {
10
27
  nextStep();
11
28
  return;
@@ -88,4 +105,4 @@ const createNextStep = (valueEvent, select, next, files, callHandler) => {
88
105
  return nextStep;
89
106
  };
90
107
 
91
- export { createNextStep };
108
+ export { clearModuleCache, createNextStep };
@@ -1,10 +1,16 @@
1
- import { isAsyncFunction } from 'util/types';
2
1
  import { EventMessageText } from '../core/variable.js';
3
2
  import 'fs';
4
3
  import 'path';
5
4
  import 'yaml';
6
5
  import { showErrorModule } from '../core/utils.js';
7
6
 
7
+ function isPromise(value) {
8
+ return value !== null && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function';
9
+ }
10
+ function isAsyncFunction(fn) {
11
+ const AsyncFunction = (async () => { }).constructor;
12
+ return fn instanceof AsyncFunction;
13
+ }
8
14
  const createRouteProcessChildren = (valueEvent, select, nextCycle, callHandler) => {
9
15
  const processChildren = (nodes, middleware, next) => {
10
16
  if (!nodes || nodes.length === 0) {
@@ -26,11 +32,26 @@ const createRouteProcessChildren = (valueEvent, select, nextCycle, callHandler)
26
32
  return;
27
33
  }
28
34
  }
29
- if (EventMessageText.includes(select) && node.regular) {
30
- const reg = new RegExp(node.regular);
31
- if (!reg.test(valueEvent['MessageText'])) {
32
- void nextNode();
33
- return;
35
+ if (EventMessageText.includes(select)) {
36
+ const text = valueEvent['MessageText'] ?? '';
37
+ if (node.exact !== undefined) {
38
+ if (text !== node.exact) {
39
+ void nextNode();
40
+ return;
41
+ }
42
+ }
43
+ if (node.prefix !== undefined) {
44
+ if (!text.startsWith(node.prefix)) {
45
+ void nextNode();
46
+ return;
47
+ }
48
+ }
49
+ if (node.regular) {
50
+ const reg = new RegExp(node.regular);
51
+ if (!reg.test(text)) {
52
+ void nextNode();
53
+ return;
54
+ }
34
55
  }
35
56
  }
36
57
  if (!node.handler) {
@@ -45,7 +66,11 @@ const createRouteProcessChildren = (valueEvent, select, nextCycle, callHandler)
45
66
  try {
46
67
  const currents = [];
47
68
  for (const item of currentsAndMiddleware) {
48
- const app = isAsyncFunction(item) ? await item() : item();
69
+ const app = await item();
70
+ if (isPromise(app) || isAsyncFunction(app)) {
71
+ currents.push(app);
72
+ continue;
73
+ }
49
74
  const selects = Array.isArray(app.select) ? app.select : [app.select];
50
75
  if (!selects.includes(select)) {
51
76
  void nextNode();
@@ -3,13 +3,13 @@ import { createCallHandler } from './event-processor-callHandler.js';
3
3
  import { createNextStep } from './event-processor-cycleFiles.js';
4
4
  import { createRouteProcessChildren } from './event-processor-cycleRoute.js';
5
5
 
6
+ const responseSingleton = new Response();
7
+ const responseRouterSingleton = new ResponseRouter();
6
8
  const expendEvent = (valueEvent, select, next) => {
7
- const res = new Response();
8
- const StoreResponse = res.value;
9
+ const StoreResponse = responseSingleton.value;
9
10
  const callHandler = createCallHandler(valueEvent);
10
11
  const nextEvent = createNextStep(valueEvent, select, next, StoreResponse, callHandler);
11
- const resRoute = new ResponseRouter();
12
- const routes = resRoute.value;
12
+ const routes = responseRouterSingleton.value;
13
13
  const callRouteHandler = createCallHandler(valueEvent);
14
14
  const processChildren = createRouteProcessChildren(valueEvent, select, nextEvent, callRouteHandler);
15
15
  void processChildren(routes, [], nextEvent);
@@ -3,13 +3,13 @@ import { createCallHandler } from './event-processor-callHandler.js';
3
3
  import { createNextStep } from './event-processor-cycleFiles.js';
4
4
  import { createRouteProcessChildren } from './event-processor-cycleRoute.js';
5
5
 
6
+ const middlewareSingleton = new Middleware();
7
+ const middlewareRouterSingleton = new MiddlewareRouter();
6
8
  const expendMiddleware = (valueEvent, select, next) => {
7
- const mw = new Middleware();
8
- const mwFiles = mw.value;
9
+ const mwFiles = middlewareSingleton.value;
9
10
  const callHandler = createCallHandler(valueEvent);
10
11
  const nextMiddleware = createNextStep(valueEvent, select, next, mwFiles, callHandler);
11
- const resRoute = new MiddlewareRouter();
12
- const routes = resRoute.value;
12
+ const routes = middlewareRouterSingleton.value;
13
13
  const callRouteHandler = createCallHandler(valueEvent);
14
14
  const processChildren = createRouteProcessChildren(valueEvent, select, nextMiddleware, callRouteHandler);
15
15
  void processChildren(routes, [], nextMiddleware);
@@ -1,7 +1,7 @@
1
1
  import { getConfigValue } from '../core/config.js';
2
- import { processorRepeatedClearTimeMin, processorRepeatedClearTimeMax, processorRepeatedEventTime, processorRepeatedUserTime, processorPepeatedClearSize } from '../core/variable.js';
2
+ import { processorRepeatedClearTimeMin, processorRepeatedClearTimeMax, processorRepeatedEventTime, processorRepeatedUserTime, processorRepeatedClearSize, processorMaxMapSize } from '../core/variable.js';
3
3
  import { expendCycle } from './event-processor-cycle.js';
4
- import { ProcessorEventAutoClearMap, ProcessorEventUserAudoClearMap } from './store.js';
4
+ import { ProcessorEventAutoClearMap, ProcessorEventUserAutoClearMap } from './store.js';
5
5
  import { createHash } from '../core/utils.js';
6
6
 
7
7
  const filter = ({ Now, store, INTERVAL }, MessageId) => {
@@ -12,6 +12,15 @@ const filter = ({ Now, store, INTERVAL }, MessageId) => {
12
12
  return true;
13
13
  }
14
14
  }
15
+ if (store.size >= processorMaxMapSize) {
16
+ cleanupStore({ Now, store, INTERVAL });
17
+ if (store.size >= processorMaxMapSize) {
18
+ const firstKey = store.keys().next().value;
19
+ if (firstKey !== undefined) {
20
+ store.delete(firstKey);
21
+ }
22
+ }
23
+ }
15
24
  store.set(MessageId, Date.now());
16
25
  };
17
26
  const cleanupStore = ({ Now, store, INTERVAL }) => {
@@ -27,12 +36,12 @@ const cleanupStoreAll = () => {
27
36
  const EVENT_INTERVAL = value?.processor?.repeated_event_time ?? processorRepeatedEventTime;
28
37
  const USER_INTERVAL = value?.processor?.repeated_user_time ?? processorRepeatedUserTime;
29
38
  cleanupStore({ Now, INTERVAL: EVENT_INTERVAL, store: ProcessorEventAutoClearMap });
30
- cleanupStore({ Now, INTERVAL: USER_INTERVAL, store: ProcessorEventUserAudoClearMap });
39
+ cleanupStore({ Now, INTERVAL: USER_INTERVAL, store: ProcessorEventUserAutoClearMap });
31
40
  };
32
41
  const callback = () => {
33
42
  cleanupStoreAll();
34
- const length = ProcessorEventAutoClearMap.size + ProcessorEventUserAudoClearMap.size;
35
- const time = length > processorPepeatedClearSize ? processorRepeatedClearTimeMin : processorRepeatedClearTimeMax;
43
+ const length = ProcessorEventAutoClearMap.size + ProcessorEventUserAutoClearMap.size;
44
+ const time = length > processorRepeatedClearSize ? processorRepeatedClearTimeMin : processorRepeatedClearTimeMax;
36
45
  setTimeout(callback, time);
37
46
  };
38
47
  setTimeout(callback, processorRepeatedClearTimeMin);
@@ -103,7 +112,7 @@ const onProcessor = (name, event, data) => {
103
112
  const USER_INTERVAL = value?.processor?.repeated_user_time ?? processorRepeatedUserTime;
104
113
  if (event['UserId']) {
105
114
  const UserId = createHash(event['UserId']);
106
- if (filter({ Now, INTERVAL: USER_INTERVAL, store: ProcessorEventUserAudoClearMap }, UserId)) {
115
+ if (filter({ Now, INTERVAL: USER_INTERVAL, store: ProcessorEventUserAutoClearMap }, UserId)) {
107
116
  return;
108
117
  }
109
118
  }
@@ -1,6 +1,6 @@
1
1
  import { DataEnums, EventKeys, Events, User } from '../types';
2
2
  import { Result } from '../core/utils';
3
- import { BT, MD } from './message-format';
3
+ import { BT, Format, MD } from './message-format';
4
4
  type Options = {
5
5
  UserId?: string;
6
6
  UserKey?: string;
@@ -9,11 +9,15 @@ type Options = {
9
9
  IsBot?: boolean;
10
10
  };
11
11
  export declare const useMention: <T extends EventKeys>(event: Events[T]) => [{
12
- find: (options: Options) => Promise<Result<User[]>>;
13
- findOne: (options?: Options) => Promise<Result<User | null>>;
12
+ find: (options?: Options) => Promise<Result<User[]> & {
13
+ count: number;
14
+ }>;
15
+ findOne: (options?: Options) => Promise<Result<User | null> & {
16
+ count: number;
17
+ }>;
14
18
  }];
15
19
  export declare const useMessage: <T extends EventKeys>(event: Events[T]) => readonly [{
16
- "__#7@#format": DataEnums[];
20
+ "__#8@#format": DataEnums[];
17
21
  readonly currentFormat: DataEnums[];
18
22
  addText(val: string, options?: {
19
23
  style?: "none" | "bold" | "block" | "strikethrough" | "boldItalic" | "italic";
@@ -36,12 +40,16 @@ export declare const useMessage: <T extends EventKeys>(event: Events[T]) => read
36
40
  }): any;
37
41
  addFormat(val: DataEnums[]): any;
38
42
  clear(): any;
39
- send(val?: DataEnums[]): Promise<Result[]>;
43
+ send(params?: {
44
+ format: Format | DataEnums[];
45
+ } | DataEnums[]): Promise<Result[]>;
40
46
  }];
41
47
  export declare const useMember: <T extends EventKeys>(event: Events[T]) => readonly [{}];
42
48
  export declare const useChannel: <T extends EventKeys>(event: Events[T]) => readonly [{}];
43
49
  export declare const useSend: <T extends EventKeys>(event: Events[T]) => (...val: DataEnums[]) => Promise<Result[]>;
44
- export declare const useSends: <T extends EventKeys>(event: Events[T]) => readonly [(val?: DataEnums[]) => Promise<Result[]>];
50
+ export declare const useSends: <T extends EventKeys>(event: Events[T]) => readonly [(params?: DataEnums[] | {
51
+ format: Format | DataEnums[];
52
+ }) => Promise<Result[]>];
45
53
  export declare const unChildren: (name?: string) => void;
46
54
  export declare const onSelects: <T extends EventKeys[] | EventKeys>(values: T) => T;
47
55
  export declare const createSelects: <T extends EventKeys[] | EventKeys>(values: T) => T;
@@ -3,7 +3,7 @@ import { ChildrenApp } from './store.js';
3
3
  import { createResult } from '../core/utils.js';
4
4
  import { sendAction } from '../cbp/processor/actions.js';
5
5
  import { sendAPI } from '../cbp/processor/api.js';
6
- import { Text, Link, Image, ImageFile, ImageURL, Mention, BT, MD } from './message-format.js';
6
+ import { Text, Link, Image, ImageFile, ImageURL, Mention, BT, MD, Format } from './message-format.js';
7
7
 
8
8
  const useMention = (event) => {
9
9
  if (!event || typeof event !== 'object') {
@@ -15,94 +15,80 @@ const useMention = (event) => {
15
15
  throw new Error('Invalid event: event must be an object');
16
16
  }
17
17
  let res = null;
18
+ const load = async () => {
19
+ if (res) {
20
+ return;
21
+ }
22
+ const results = await sendAction({
23
+ action: 'mention.get',
24
+ payload: { event }
25
+ });
26
+ const result = results.find(item => item.code === ResultCode.Ok);
27
+ if (result) {
28
+ res = result.data;
29
+ }
30
+ };
31
+ const match = (item, options) => {
32
+ if (options.UserId !== undefined && item.UserId !== options.UserId) {
33
+ return false;
34
+ }
35
+ if (options.UserKey !== undefined && item.UserKey !== options.UserKey) {
36
+ return false;
37
+ }
38
+ if (options.UserName !== undefined && item.UserName !== options.UserName) {
39
+ return false;
40
+ }
41
+ if (options.IsMaster !== undefined && item.IsMaster !== options.IsMaster) {
42
+ return false;
43
+ }
44
+ if (options.IsBot !== undefined && item.IsBot !== options.IsBot) {
45
+ return false;
46
+ }
47
+ if (options.IsBot === undefined && item.IsBot) {
48
+ return false;
49
+ }
50
+ return true;
51
+ };
18
52
  const mention = {
19
53
  find: async (options = {}) => {
20
54
  try {
21
- if (!res) {
22
- const results = await sendAction({
23
- action: 'mention.get',
24
- payload: {
25
- event
26
- }
27
- });
28
- const result = results.find(item => item.code === ResultCode.Ok);
29
- if (result) {
30
- res = result.data;
31
- }
32
- }
55
+ await load();
33
56
  }
34
57
  catch (err) {
35
- return createResult(ResultCode.Fail, err?.message || 'Failed to get mention data', null);
58
+ const result = createResult(ResultCode.Fail, err?.message || 'Failed to get mention data', null);
59
+ return {
60
+ ...result,
61
+ count: 0
62
+ };
36
63
  }
37
64
  if (!Array.isArray(res)) {
38
- return createResult(ResultCode.Warn, 'No mention data found', null);
65
+ return {
66
+ ...createResult(ResultCode.Warn, 'No mention data found', null),
67
+ count: 0
68
+ };
39
69
  }
40
- const data = res.filter(item => {
41
- if (options.UserId !== undefined && item.UserId !== options.UserId) {
42
- return false;
43
- }
44
- if (options.UserKey !== undefined && item.UserKey !== options.UserKey) {
45
- return false;
46
- }
47
- if (options.UserName !== undefined && item.UserName !== options.UserName) {
48
- return false;
49
- }
50
- if (options.IsMaster !== undefined && item.IsMaster !== options.IsMaster) {
51
- return false;
52
- }
53
- if (options.IsBot !== undefined && item.IsBot !== options.IsBot) {
54
- return false;
55
- }
56
- return true;
57
- });
58
- return createResult(ResultCode.Ok, 'Successfully retrieved mention data', data);
70
+ const data = res.filter(item => match(item, options));
71
+ const result = createResult(ResultCode.Ok, 'Successfully retrieved mention data', data);
72
+ return {
73
+ ...result,
74
+ count: data.length || 0
75
+ };
59
76
  },
60
77
  findOne: async (options = {}) => {
61
- try {
62
- if (!res) {
63
- const results = await sendAction({
64
- action: 'mention.get',
65
- payload: {
66
- event
67
- }
68
- });
69
- const result = results.find(item => item.code === ResultCode.Ok);
70
- if (result) {
71
- res = result.data;
72
- }
73
- }
74
- }
75
- catch (err) {
76
- return createResult(ResultCode.Fail, err?.message || 'Failed to get mention data', null);
77
- }
78
- if (!Array.isArray(res)) {
79
- return createResult(ResultCode.Warn, 'No mention data found', null);
80
- }
81
- const data = res.find(item => {
82
- if (options.UserId !== undefined && item.UserId !== options.UserId) {
83
- return false;
84
- }
85
- if (options.UserKey !== undefined && item.UserKey !== options.UserKey) {
86
- return false;
87
- }
88
- if (options.UserName !== undefined && item.UserName !== options.UserName) {
89
- return false;
90
- }
91
- if (options.IsMaster !== undefined && item.IsMaster !== options.IsMaster) {
92
- return false;
93
- }
94
- if (options.IsBot !== undefined && item.IsBot !== options.IsBot) {
95
- return false;
96
- }
97
- if (item.IsBot) {
98
- return false;
99
- }
100
- return true;
101
- });
102
- if (!data) {
103
- return createResult(ResultCode.Warn, 'No mention data found', null);
78
+ const results = await mention.find(options);
79
+ if (results.code !== ResultCode.Ok || !results.data?.length) {
80
+ const result = createResult(results.code, results.message, null);
81
+ return {
82
+ ...result,
83
+ count: 0
84
+ };
104
85
  }
105
- return createResult(ResultCode.Ok, 'Successfully retrieved mention data', data);
86
+ const data = results?.data[0];
87
+ const result = createResult(ResultCode.Ok, results.message, data);
88
+ return {
89
+ ...result,
90
+ count: results.data?.length || 0
91
+ };
106
92
  }
107
93
  };
108
94
  return [mention];
@@ -116,7 +102,13 @@ const useMessage = (event) => {
116
102
  });
117
103
  throw new Error('Invalid event: event must be an object');
118
104
  }
119
- const send = async (val) => {
105
+ const resolveFormat = (params) => {
106
+ if (params.format instanceof Format) {
107
+ return params.format.value;
108
+ }
109
+ return params.format;
110
+ };
111
+ const sendRaw = async (val) => {
120
112
  if (!val || val.length === 0) {
121
113
  return [createResult(ResultCode.FailParams, 'Invalid val: val must be a non-empty array', null)];
122
114
  }
@@ -184,9 +176,15 @@ const useMessage = (event) => {
184
176
  this.#format = [];
185
177
  return this;
186
178
  }
187
- send(val) {
188
- const dataToSend = val && val.length > 0 ? val : this.#format;
189
- return send(dataToSend);
179
+ send(params) {
180
+ if (!params) {
181
+ return sendRaw(this.#format);
182
+ }
183
+ if (Array.isArray(params)) {
184
+ const dataToSend = params.length > 0 ? params : this.#format;
185
+ return sendRaw(dataToSend);
186
+ }
187
+ return sendRaw(resolveFormat(params));
190
188
  }
191
189
  }
192
190
  return [new MessageController()];
@@ -4,6 +4,7 @@ export * from './define-children.js';
4
4
  export * from './define-platform.js';
5
5
  export * from './define-response.js';
6
6
  export * from './define-middleware.js';
7
+ export * from './define-router.js';
7
8
  export * from './event-group.js';
8
9
  export * from './event-middleware';
9
10
  export * from './event-processor';
package/lib/app/index.js CHANGED
@@ -1,10 +1,11 @@
1
- export { ChildrenApp, Core, Logger, Middleware, MiddlewareRouter, ProcessorEventAutoClearMap, ProcessorEventUserAudoClearMap, Response, ResponseMiddleware, ResponseRouter, State, StateSubscribe, SubscribeList, core, logger } from './store.js';
1
+ export { ChildrenApp, Core, Logger, Middleware, MiddlewareRouter, ProcessorEventAutoClearMap, ProcessorEventUserAutoClearMap, Response, ResponseMiddleware, ResponseRouter, State, StateSubscribe, SubscribeList, core, logger } from './store.js';
2
2
  export { loadModels, run } from './load_modules/load.js';
3
3
  export { loadChildren, loadChildrenFile } from './load_modules/loadChild.js';
4
4
  export { defineChildren } from './define-children.js';
5
5
  export { definePlatform } from './define-platform.js';
6
- export { defineResponse, lazy } from './define-response.js';
6
+ export { defineResponse } from './define-response.js';
7
7
  export { defineMiddleware } from './define-middleware.js';
8
+ export { defineRouter, lazy } from './define-router.js';
8
9
  export { onGroup } from './event-group.js';
9
10
  export { OnMiddleware, onMiddleware } from './event-middleware.js';
10
11
  export { OnProcessor, onProcessor } from './event-processor.js';
@@ -17,4 +18,4 @@ export { createSelects, onSelects, unChildren, useChannel, useClient, useMe, use
17
18
  export { onState, unState, useState } from './hook-use-state.js';
18
19
  export { useObserver, useSubscribe } from './hook-use-subscribe.js';
19
20
  export { createDataFormat, createEventValue, format, getMessageIntent, sendToChannel, sendToUser } from './message-api.js';
20
- export { Ark, BT, Image, ImageFile, ImageURL, Link, MD, Mention, Text } from './message-format.js';
21
+ export { Ark, BT, Format, Image, ImageFile, ImageURL, Link, MD, Mention, Text, createEvent } from './message-format.js';