alemonjs 2.1.66 → 2.1.67

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.
@@ -2,7 +2,7 @@ import 'fs';
2
2
  import 'path';
3
3
  import 'yaml';
4
4
  import { showErrorModule } from '../core/utils.js';
5
- import { withEventContext } from './hook-event-context.js';
5
+ import { withEventContext, finishCurrentTrace } from './hook-event-context.js';
6
6
 
7
7
  const createCallHandler = valueEvent => {
8
8
  const callHandler = (currents, nextEvent) => {
@@ -26,10 +26,15 @@ const createCallHandler = valueEvent => {
26
26
  };
27
27
  const res = await withEventContext(valueEvent, nextFn, () => currents[index](valueEvent, nextFn));
28
28
  if (res !== true) {
29
+ if (!isNext) {
30
+ finishCurrentTrace('consumed');
31
+ return;
32
+ }
29
33
  isClose = true;
30
34
  }
31
35
  }
32
36
  catch (err) {
37
+ finishCurrentTrace('error');
33
38
  showErrorModule(err);
34
39
  return;
35
40
  }
@@ -1,2 +1,2 @@
1
1
  import { Events, EventKeys } from '../types';
2
- export declare const expendCycle: <T extends EventKeys>(valueEvent: Events[T], select: T, config?: any) => void;
2
+ export declare const expendCycle: <T extends EventKeys>(valueEvent: Events[T], select: T, _config?: any) => void;
@@ -1,42 +1,12 @@
1
- import { ResultCode } from '../core/variable.js';
2
1
  import { expendEvent } from './event-processor-event.js';
3
2
  import { expendMiddleware } from './event-processor-middleware.js';
4
3
  import { expendSubscribeCreate, expendSubscribeMount, expendSubscribeUnmount } from './event-processor-subscribe.js';
5
- import { getConfigValue } from '../core/config.js';
4
+ import { finishCurrentTrace } from './hook-event-context.js';
6
5
 
7
- const showLog = (event, select) => {
8
- if (process.env.NODE_ENV === 'development') {
9
- const log = {
10
- Name: select
11
- };
12
- for (const key in event) {
13
- if (Object.prototype.hasOwnProperty.call(event, key)) {
14
- const value = event[key];
15
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
16
- log[key] = value;
17
- }
18
- }
19
- }
20
- logger.debug({
21
- code: ResultCode.Ok,
22
- message: 'new event',
23
- data: log
24
- });
25
- }
26
- else {
27
- const parts = [`[Name:${select}]`];
28
- const fields = ['GuildId', 'ChannelId', 'UserKey', 'UserId', 'MessageId', 'MessageText'];
29
- for (const f of fields) {
30
- const v = event[f];
31
- if (typeof v === 'string' && v !== '') {
32
- parts.push(`[${f}:${v}]`);
33
- }
34
- }
35
- logger.info(parts.join(''));
36
- }
37
- };
38
- const expendCycle = (valueEvent, select, config) => {
39
- const nextEnd = () => { };
6
+ const expendCycle = (valueEvent, select, _config) => {
7
+ const nextEnd = () => {
8
+ finishCurrentTrace('completed');
9
+ };
40
10
  const nextUnMount = (cn, ...cns) => {
41
11
  if (cn) {
42
12
  nextEnd(...cns);
@@ -65,16 +35,6 @@ const expendCycle = (valueEvent, select, config) => {
65
35
  }
66
36
  void expendMiddleware(valueEvent, select, nextMount);
67
37
  };
68
- const value = config ?? getConfigValue() ?? {};
69
- if (Array.isArray(value?.logs?.channel_id)) {
70
- const channelIds = value?.logs?.channel_id;
71
- if (channelIds && channelIds.length > 0 && channelIds.includes(valueEvent['ChannelId'])) {
72
- showLog(valueEvent, select);
73
- }
74
- }
75
- else {
76
- showLog(valueEvent, select);
77
- }
78
38
  void expendSubscribeCreate(valueEvent, select, nextCreate);
79
39
  };
80
40
 
@@ -1,6 +1,10 @@
1
+ import 'fs';
2
+ import 'path';
3
+ import 'yaml';
4
+ import { showErrorModule } from '../core/utils.js';
1
5
  import { getSubscribeList } from './store.js';
2
6
  import { SubscribeStatus } from './config.js';
3
- import { withEventContext } from './hook-event-context.js';
7
+ import { withEventContext, finishCurrentTrace } from './hook-event-context.js';
4
8
 
5
9
  const expendSubscribe = (valueEvent, select, next, choose) => {
6
10
  const subListValue = getSubscribeList(choose, select);
@@ -51,13 +55,35 @@ const expendSubscribe = (valueEvent, select, next, choose) => {
51
55
  }
52
56
  };
53
57
  onPaused();
58
+ let isContinue = false;
54
59
  const Continue = (cn, ...cns) => {
55
60
  onActive();
56
61
  if (cn) {
62
+ isContinue = true;
57
63
  nextObserver(...cns);
58
64
  }
59
65
  };
60
- withEventContext(valueEvent, Continue, () => item.data.current(valueEvent, Continue));
66
+ try {
67
+ const result = withEventContext(valueEvent, Continue, () => item.data.current(valueEvent, Continue));
68
+ if (result && typeof result.then === 'function') {
69
+ void result.then(() => {
70
+ if (!isContinue) {
71
+ finishCurrentTrace('consumed');
72
+ }
73
+ }, error => {
74
+ finishCurrentTrace('error');
75
+ showErrorModule(error);
76
+ });
77
+ return;
78
+ }
79
+ if (!isContinue) {
80
+ finishCurrentTrace('consumed');
81
+ }
82
+ }
83
+ catch (error) {
84
+ finishCurrentTrace('error');
85
+ showErrorModule(error);
86
+ }
61
87
  };
62
88
  nextObserver();
63
89
  };
@@ -1,6 +1,7 @@
1
1
  import { getConfigValue } from '../core/config.js';
2
2
  import { processorRepeatedClearTimeMin, processorRepeatedClearTimeMax, processorRepeatedEventTime, processorRepeatedUserTime, processorRepeatedClearSize, processorMaxMapSize } from '../core/variable.js';
3
3
  import { expendCycle } from './event-processor-cycle.js';
4
+ import { withProcessorTrace, finishCurrentTrace } from './hook-event-context.js';
4
5
  import { ProcessorEventAutoClearMap, ProcessorEventUserAutoClearMap } from './store.js';
5
6
  import { getCachedRegExp, matchIn, fastHash } from '../core/utils.js';
6
7
 
@@ -58,85 +59,99 @@ const callback = () => {
58
59
  };
59
60
  setTimeout(callback, processorRepeatedClearTimeMin);
60
61
  const onProcessor = (name, event, data) => {
61
- const value = getConfigValue();
62
- const disabledTextRegular = value?.disabled_text_regular;
63
- if (disabledTextRegular && event['MessageText']) {
64
- if (getCachedRegExp(disabledTextRegular).test(event['MessageText'])) {
65
- return;
66
- }
67
- }
68
- const disabledSelects = value?.disabled_selects ?? {};
69
- if (disabledSelects[name]) {
70
- return;
71
- }
72
- const disabledUserId = value?.disabled_user_id;
73
- if (event['UserId'] && matchIn(disabledUserId, event['UserId'])) {
74
- return;
75
- }
76
- const disabledUserKey = value?.disabled_user_key;
77
- if (event['UserKey'] && matchIn(disabledUserKey, event['UserKey'])) {
78
- return;
79
- }
80
- const redirectRegular = value?.redirect_regular ?? value?.redirect_text_regular;
81
- const redirectTarget = value?.redirect_target ?? value?.redirect_text_target;
82
- if (redirectRegular && redirectTarget && event['MessageText']) {
83
- const cachedReg = getCachedRegExp(redirectRegular);
84
- if (cachedReg.test(event['MessageText'])) {
85
- event['MessageText'] = event['MessageText'].replace(cachedReg, redirectTarget);
86
- }
87
- }
88
- const mappingText = value?.mapping_text ?? [];
89
- if (event['MessageText']) {
90
- for (const mapping of mappingText) {
91
- const { regular, target } = mapping ?? {};
92
- if (!regular) {
93
- continue;
62
+ withProcessorTrace(name, event, () => {
63
+ try {
64
+ const value = getConfigValue();
65
+ const disabledTextRegular = value?.disabled_text_regular;
66
+ if (disabledTextRegular && event['MessageText']) {
67
+ if (getCachedRegExp(disabledTextRegular).test(event['MessageText'])) {
68
+ finishCurrentTrace('filtered');
69
+ return;
70
+ }
94
71
  }
95
- const cachedReg = getCachedRegExp(regular);
96
- if (cachedReg.test(event['MessageText'])) {
97
- event['MessageText'] = event['MessageText'].replace(cachedReg, target);
72
+ const disabledSelects = value?.disabled_selects ?? {};
73
+ if (disabledSelects[name]) {
74
+ finishCurrentTrace('filtered');
75
+ return;
98
76
  }
77
+ const disabledUserId = value?.disabled_user_id;
78
+ if (event['UserId'] && matchIn(disabledUserId, event['UserId'])) {
79
+ finishCurrentTrace('filtered');
80
+ return;
81
+ }
82
+ const disabledUserKey = value?.disabled_user_key;
83
+ if (event['UserKey'] && matchIn(disabledUserKey, event['UserKey'])) {
84
+ finishCurrentTrace('filtered');
85
+ return;
86
+ }
87
+ const redirectRegular = value?.redirect_regular ?? value?.redirect_text_regular;
88
+ const redirectTarget = value?.redirect_target ?? value?.redirect_text_target;
89
+ if (redirectRegular && redirectTarget && event['MessageText']) {
90
+ const cachedReg = getCachedRegExp(redirectRegular);
91
+ if (cachedReg.test(event['MessageText'])) {
92
+ event['MessageText'] = event['MessageText'].replace(cachedReg, redirectTarget);
93
+ }
94
+ }
95
+ const mappingText = value?.mapping_text ?? [];
96
+ if (event['MessageText']) {
97
+ for (const mapping of mappingText) {
98
+ const { regular, target } = mapping ?? {};
99
+ if (!regular) {
100
+ continue;
101
+ }
102
+ const cachedReg = getCachedRegExp(regular);
103
+ if (cachedReg.test(event['MessageText'])) {
104
+ event['MessageText'] = event['MessageText'].replace(cachedReg, target);
105
+ }
106
+ }
107
+ }
108
+ else {
109
+ event['MessageText'] = '';
110
+ }
111
+ const masterId = value?.master_id;
112
+ const masterKey = value?.master_key;
113
+ if (event['UserId'] && matchIn(masterId, event['UserId'])) {
114
+ event['isMaster'] = true;
115
+ }
116
+ else if (event['UserKey'] && matchIn(masterKey, event['UserKey'])) {
117
+ event['isMaster'] = true;
118
+ }
119
+ const botId = value?.bot_id;
120
+ const botKey = value?.bot_key;
121
+ if (event['UserId'] && matchIn(botId, event['UserId'])) {
122
+ event['isBot'] = true;
123
+ }
124
+ else if (event['UserKey'] && matchIn(botKey, event['UserKey'])) {
125
+ event['isBot'] = true;
126
+ }
127
+ const Now = Date.now();
128
+ const EVENT_INTERVAL = value?.processor?.repeated_event_time ?? processorRepeatedEventTime;
129
+ if (event['MessageId']) {
130
+ const MessageId = fastHash(event['MessageId']);
131
+ if (filter({ Now, INTERVAL: EVENT_INTERVAL, store: ProcessorEventAutoClearMap }, MessageId)) {
132
+ finishCurrentTrace('filtered');
133
+ return;
134
+ }
135
+ }
136
+ const USER_INTERVAL = value?.processor?.repeated_user_time ?? processorRepeatedUserTime;
137
+ if (event['UserId']) {
138
+ const UserId = fastHash(event['UserId']);
139
+ if (filter({ Now, INTERVAL: USER_INTERVAL, store: ProcessorEventUserAutoClearMap }, UserId)) {
140
+ finishCurrentTrace('filtered');
141
+ return;
142
+ }
143
+ }
144
+ if (data) {
145
+ event['value'] = data;
146
+ }
147
+ event['name'] = name;
148
+ expendCycle(event, name, value);
99
149
  }
100
- }
101
- else {
102
- event['MessageText'] = '';
103
- }
104
- const masterId = value?.master_id;
105
- const masterKey = value?.master_key;
106
- if (event['UserId'] && matchIn(masterId, event['UserId'])) {
107
- event['isMaster'] = true;
108
- }
109
- else if (event['UserKey'] && matchIn(masterKey, event['UserKey'])) {
110
- event['isMaster'] = true;
111
- }
112
- const botId = value?.bot_id;
113
- const botKey = value?.bot_key;
114
- if (event['UserId'] && matchIn(botId, event['UserId'])) {
115
- event['isBot'] = true;
116
- }
117
- else if (event['UserKey'] && matchIn(botKey, event['UserKey'])) {
118
- event['isBot'] = true;
119
- }
120
- const Now = Date.now();
121
- const EVENT_INTERVAL = value?.processor?.repeated_event_time ?? processorRepeatedEventTime;
122
- if (event['MessageId']) {
123
- const MessageId = fastHash(event['MessageId']);
124
- if (filter({ Now, INTERVAL: EVENT_INTERVAL, store: ProcessorEventAutoClearMap }, MessageId)) {
125
- return;
126
- }
127
- }
128
- const USER_INTERVAL = value?.processor?.repeated_user_time ?? processorRepeatedUserTime;
129
- if (event['UserId']) {
130
- const UserId = fastHash(event['UserId']);
131
- if (filter({ Now, INTERVAL: USER_INTERVAL, store: ProcessorEventUserAutoClearMap }, UserId)) {
132
- return;
150
+ catch (error) {
151
+ finishCurrentTrace('error');
152
+ throw error;
133
153
  }
134
- }
135
- if (data) {
136
- event['value'] = data;
137
- }
138
- event['name'] = name;
139
- expendCycle(event, name, value);
154
+ });
140
155
  };
141
156
  const OnProcessor = (event, name) => {
142
157
  onProcessor(name, event);
@@ -1,4 +1,7 @@
1
1
  import { EventKeys, Events } from '../types';
2
+ export type EventTraceReason = 'filtered' | 'completed' | 'consumed' | 'error';
2
3
  export declare const withEventContext: <T extends EventKeys, R>(event: Events[T], next: (...args: boolean[]) => void, runner: () => R) => R;
4
+ export declare const withProcessorTrace: <T extends EventKeys, R>(select: T, event: Events[T], runner: () => R) => R;
3
5
  export declare const getCurrentEvent: <T extends EventKeys>() => Events[T] | undefined;
4
6
  export declare const getCurrentNext: () => ((...args: boolean[]) => void) | undefined;
7
+ export declare const finishCurrentTrace: (reason: EventTraceReason) => void;
@@ -1,8 +1,88 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { performance } from 'node:perf_hooks';
3
+ import { getConfigValue } from '../core/config.js';
4
+ import { ResultCode } from '../core/variable.js';
2
5
 
3
6
  const eventStore = new AsyncLocalStorage();
7
+ const shouldShowLog = (event) => {
8
+ const value = getConfigValue() ?? {};
9
+ if (Array.isArray(value?.logs?.channel_id)) {
10
+ const channelIds = value.logs.channel_id;
11
+ return channelIds.length > 0 && channelIds.includes(event['ChannelId']);
12
+ }
13
+ return true;
14
+ };
15
+ const createLogData = (event, select, reason, duration) => {
16
+ const log = {
17
+ Name: select,
18
+ reason,
19
+ duration
20
+ };
21
+ for (const key in event) {
22
+ if (Object.prototype.hasOwnProperty.call(event, key)) {
23
+ const value = event[key];
24
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
25
+ log[key] = value;
26
+ }
27
+ }
28
+ }
29
+ return log;
30
+ };
31
+ const createLogText = (event, select, reason, duration) => {
32
+ const parts = [`[Name:${select}]`, `[reason:${reason}]`, `[duration:${duration}ms]`];
33
+ const fields = ['GuildId', 'ChannelId', 'UserKey', 'UserId', 'MessageId', 'MessageText'];
34
+ for (const f of fields) {
35
+ const v = event[f];
36
+ if (typeof v === 'string' && v !== '') {
37
+ parts.push(`[${f}:${v}]`);
38
+ }
39
+ }
40
+ return parts.join('');
41
+ };
42
+ const createEventTrace = (select) => {
43
+ const trace = {
44
+ select,
45
+ startTime: performance.now(),
46
+ ended: false,
47
+ finish(reason) {
48
+ if (trace.ended) {
49
+ return;
50
+ }
51
+ trace.ended = true;
52
+ const store = eventStore.getStore();
53
+ const event = store?.event;
54
+ const duration = Number((performance.now() - trace.startTime).toFixed(2));
55
+ if (!event || !shouldShowLog(event)) {
56
+ return;
57
+ }
58
+ if (process.env.NODE_ENV === 'development') {
59
+ logger.debug({
60
+ code: ResultCode.Ok,
61
+ message: 'event processor finished',
62
+ data: createLogData(event, trace.select, reason, duration)
63
+ });
64
+ return;
65
+ }
66
+ logger.info(createLogText(event, trace.select, reason, duration));
67
+ }
68
+ };
69
+ return trace;
70
+ };
4
71
  const withEventContext = (event, next, runner) => {
5
- return eventStore.run({ event, next }, runner);
72
+ const current = eventStore.getStore();
73
+ return eventStore.run({
74
+ event,
75
+ next,
76
+ trace: current?.trace
77
+ }, runner);
78
+ };
79
+ const withProcessorTrace = (select, event, runner) => {
80
+ const current = eventStore.getStore();
81
+ return eventStore.run({
82
+ event,
83
+ next: current?.next,
84
+ trace: current?.trace ?? createEventTrace(select)
85
+ }, runner);
6
86
  };
7
87
  const getCurrentEvent = () => {
8
88
  return eventStore.getStore()?.event;
@@ -10,5 +90,8 @@ const getCurrentEvent = () => {
10
90
  const getCurrentNext = () => {
11
91
  return eventStore.getStore()?.next;
12
92
  };
93
+ const finishCurrentTrace = (reason) => {
94
+ eventStore.getStore()?.trace?.finish(reason);
95
+ };
13
96
 
14
- export { getCurrentEvent, getCurrentNext, withEventContext };
97
+ export { finishCurrentTrace, getCurrentEvent, getCurrentNext, withEventContext, withProcessorTrace };
package/lib/app/index.js CHANGED
@@ -34,7 +34,7 @@ export { useUser } from './hook-use/user.js';
34
34
  export { useObserver, useSubscribe } from './hook-use/subscribe.js';
35
35
  export { createEvent, useEvent } from './hook-use/event.js';
36
36
  export { clearInterval, clearTimeout, listSchedule, pauseSchedule, resumeSchedule, setCron, setInterval, setTimeout } from './api/schedule.js';
37
- export { getCurrentEvent, getCurrentNext, withEventContext } from './hook-event-context.js';
37
+ export { finishCurrentTrace, getCurrentEvent, getCurrentNext, withEventContext, withProcessorTrace } from './hook-event-context.js';
38
38
  export { registerAppDir, scheduleCancel, scheduleCancelAll, scheduleCancelByApp, scheduleCron, scheduleInterval, scheduleList, schedulePause, scheduleResume, scheduleTimeout, unregisterAppDir } from './schedule-store.js';
39
39
  export { createEventValue, createSelects, onSelects, onState, unChildren, unState, useState } from './event-utils.js';
40
40
  export { MessageDirect, createDataFormat, format, getMessageIntent, sendToChannel, sendToUser } from './message-api.js';
package/lib/index.js CHANGED
@@ -41,7 +41,7 @@ export { useUser } from './app/hook-use/user.js';
41
41
  export { useObserver, useSubscribe } from './app/hook-use/subscribe.js';
42
42
  export { createEvent, useEvent } from './app/hook-use/event.js';
43
43
  export { clearInterval, clearTimeout, listSchedule, pauseSchedule, resumeSchedule, setCron, setInterval, setTimeout } from './app/api/schedule.js';
44
- export { getCurrentEvent, getCurrentNext, withEventContext } from './app/hook-event-context.js';
44
+ export { finishCurrentTrace, getCurrentEvent, getCurrentNext, withEventContext, withProcessorTrace } from './app/hook-event-context.js';
45
45
  export { registerAppDir, scheduleCancel, scheduleCancelAll, scheduleCancelByApp, scheduleCron, scheduleInterval, scheduleList, schedulePause, scheduleResume, scheduleTimeout, unregisterAppDir } from './app/schedule-store.js';
46
46
  export { createEventValue, createSelects, onSelects, onState, unChildren, unState, useState } from './app/event-utils.js';
47
47
  export { MessageDirect, createDataFormat, format, getMessageIntent, sendToChannel, sendToUser } from './app/message-api.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alemonjs",
3
- "version": "2.1.66",
3
+ "version": "2.1.67",
4
4
  "description": "bot script",
5
5
  "author": "lemonade",
6
6
  "license": "MIT",