alemonjs 2.1.0-alpha.5 → 2.1.0-alpha.7

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/lib/app/load.js CHANGED
@@ -51,7 +51,7 @@ const loadChildren = async (mainPath, appName) => {
51
51
  // 卸载
52
52
  App.un();
53
53
  try {
54
- app?.unMounted && await app.unMounted(e);
54
+ app?.unMounted && (await app.unMounted(e));
55
55
  }
56
56
  catch (e) {
57
57
  // 卸载周期出意外,不需要进行卸载
@@ -60,7 +60,7 @@ const loadChildren = async (mainPath, appName) => {
60
60
  };
61
61
  // onCreated 创建
62
62
  try {
63
- app?.onCreated && await app?.onCreated();
63
+ app?.onCreated && (await app?.onCreated());
64
64
  }
65
65
  catch (e) {
66
66
  unMounted(e);
@@ -117,7 +117,7 @@ const loadChildren = async (mainPath, appName) => {
117
117
  App.pushMiddleware(mwData);
118
118
  App.on();
119
119
  try {
120
- app?.onMounted && await app.onMounted({ response: resData, middleware: mwData });
120
+ app?.onMounted && (await app.onMounted({ response: resData, middleware: mwData }));
121
121
  }
122
122
  catch (e) {
123
123
  unMounted(e);
package/lib/cbp/config.js CHANGED
@@ -26,6 +26,8 @@ const generateUniqueId = () => {
26
26
  // 超时时间
27
27
  const timeoutTime = 1000 * 12; // 12秒
28
28
  // 失败重连
29
- const reconnectInterval = 6000; // 6秒
29
+ const reconnectInterval = 1000 * 6; // 6秒
30
+ // 心跳间隔
31
+ const HEARTBEAT_INTERVAL = 1000 * 18; // 18秒
30
32
 
31
- export { DEVICE_ID_HEADER, FULL_RECEIVE_HEADER, USER_AGENT_HEADER, actionResolves, actionTimeouts, childrenBind, childrenClient, deviceId, fullClient, generateUniqueId, platformClient, reconnectInterval, timeoutTime };
33
+ export { DEVICE_ID_HEADER, FULL_RECEIVE_HEADER, HEARTBEAT_INTERVAL, USER_AGENT_HEADER, actionResolves, actionTimeouts, childrenBind, childrenClient, deviceId, fullClient, generateUniqueId, platformClient, reconnectInterval, timeoutTime };
@@ -1,7 +1,7 @@
1
1
  import { WebSocket } from 'ws';
2
2
  import { onProcessor } from '../app/event-processor.js';
3
3
  import { ResultCode } from '../core/code.js';
4
- import { deviceId, FULL_RECEIVE_HEADER, DEVICE_ID_HEADER, USER_AGENT_HEADER, actionResolves, actionTimeouts, reconnectInterval } from './config.js';
4
+ import { deviceId, FULL_RECEIVE_HEADER, DEVICE_ID_HEADER, USER_AGENT_HEADER, actionResolves, actionTimeouts, reconnectInterval, HEARTBEAT_INTERVAL } from './config.js';
5
5
  import '../app/define-chidren.js';
6
6
  import '../app/event-middleware.js';
7
7
  import '../app/event-response.js';
@@ -17,6 +17,63 @@ import '../app/message-api.js';
17
17
  import '../app/message-format.js';
18
18
  import { createResult } from '../app/utils.js';
19
19
 
20
+ // 心跳
21
+ const useHeartbeat = ({ ping, isConnected, terminate, }) => {
22
+ let heartbeatTimer = null;
23
+ let lastPong = Date.now();
24
+ const stopHeartbeat = () => {
25
+ if (heartbeatTimer) {
26
+ clearInterval(heartbeatTimer);
27
+ heartbeatTimer = null;
28
+ }
29
+ };
30
+ const callback = () => {
31
+ if (isConnected()) {
32
+ const diff = Date.now() - lastPong;
33
+ const max = HEARTBEAT_INTERVAL * 2; // 最大心跳间隔
34
+ // 检查上次 pong 是否超时
35
+ if (diff > max) {
36
+ logger.debug({
37
+ code: ResultCode.Fail,
38
+ message: '心跳超时,断开重连',
39
+ data: null
40
+ });
41
+ terminate(); // 强制断开
42
+ return;
43
+ }
44
+ ping();
45
+ logger.debug({
46
+ code: ResultCode.Ok,
47
+ message: `发送 ping`,
48
+ data: null
49
+ });
50
+ heartbeatTimer = setTimeout(callback, HEARTBEAT_INTERVAL);
51
+ }
52
+ else {
53
+ stopHeartbeat(); // 如果连接已关闭,停止心跳
54
+ terminate(); // 强制断开
55
+ }
56
+ };
57
+ const startHeartbeat = () => {
58
+ lastPong = Date.now();
59
+ stopHeartbeat();
60
+ callback();
61
+ };
62
+ const control = {
63
+ start: startHeartbeat,
64
+ stop: stopHeartbeat,
65
+ pong: () => {
66
+ // 收到 pong,说明连接正常
67
+ lastPong = Date.now();
68
+ logger.debug({
69
+ code: ResultCode.Ok,
70
+ message: `收到 pong`,
71
+ data: null
72
+ });
73
+ }
74
+ };
75
+ return [control];
76
+ };
20
77
  /**
21
78
  * CBP 客户端
22
79
  * @param url
@@ -31,6 +88,27 @@ const cbpClient = (url, options = {}) => {
31
88
  delete global.chatbotClient;
32
89
  }
33
90
  const { open = () => { }, isFullReceive = true } = options;
91
+ const [heartbeatControl] = useHeartbeat({
92
+ ping: () => {
93
+ global?.chatbotClient?.ping?.();
94
+ },
95
+ isConnected: () => {
96
+ return global?.chatbotClient && global?.chatbotClient?.readyState === WebSocket.OPEN;
97
+ },
98
+ terminate: () => {
99
+ try {
100
+ // 强制断开连接
101
+ global?.chatbotClient?.terminate?.();
102
+ }
103
+ catch (error) {
104
+ logger.debug({
105
+ code: ResultCode.Fail,
106
+ message: '强制断开连接失败',
107
+ data: error
108
+ });
109
+ }
110
+ }
111
+ });
34
112
  const start = () => {
35
113
  global.chatbotClient = new WebSocket(url, {
36
114
  headers: {
@@ -39,7 +117,13 @@ const cbpClient = (url, options = {}) => {
39
117
  [FULL_RECEIVE_HEADER]: isFullReceive ? '1' : '0'
40
118
  }
41
119
  });
42
- global.chatbotClient.on('open', open);
120
+ global.chatbotClient.on('open', () => {
121
+ open();
122
+ heartbeatControl.start(); // 启动心跳
123
+ });
124
+ global.chatbotClient.on('pong', () => {
125
+ heartbeatControl.pong(); // 更新 pong 时间
126
+ });
43
127
  // 客户端接收,被标准化的平台消息
44
128
  global.chatbotClient.on('message', message => {
45
129
  try {
@@ -96,6 +180,7 @@ const cbpClient = (url, options = {}) => {
96
180
  }
97
181
  });
98
182
  global.chatbotClient.on('close', () => {
183
+ heartbeatControl.stop(); // 停止心跳
99
184
  logger.warn({
100
185
  code: ResultCode.Fail,
101
186
  message: '连接关闭,尝试重新连接...',
@@ -124,6 +209,26 @@ const cbpPlatform = (url, options = {
124
209
  delete global.chatbotPlatform;
125
210
  }
126
211
  const { open = () => { } } = options;
212
+ const [heartbeatControl] = useHeartbeat({
213
+ ping: () => {
214
+ global?.chatbotPlatform?.ping?.();
215
+ },
216
+ isConnected: () => {
217
+ return global?.chatbotPlatform && global?.chatbotPlatform?.readyState === WebSocket.OPEN;
218
+ },
219
+ terminate: () => {
220
+ try {
221
+ global?.chatbotPlatform?.terminate?.();
222
+ }
223
+ catch (error) {
224
+ logger.debug({
225
+ code: ResultCode.Fail,
226
+ message: '强制断开连接失败',
227
+ data: error
228
+ });
229
+ }
230
+ }
231
+ });
127
232
  /**
128
233
  * 发送数据
129
234
  * @param data
@@ -168,7 +273,13 @@ const cbpPlatform = (url, options = {
168
273
  [DEVICE_ID_HEADER]: deviceId
169
274
  }
170
275
  });
171
- global.chatbotPlatform.on('open', open);
276
+ global.chatbotPlatform.on('open', () => {
277
+ open();
278
+ heartbeatControl.start(); // 启动心跳
279
+ });
280
+ global.chatbotPlatform.on('pong', () => {
281
+ heartbeatControl.pong(); // 更新 pong 时间
282
+ });
172
283
  global.chatbotPlatform.on('message', message => {
173
284
  try {
174
285
  const data = JSON.parse(message.toString());
@@ -192,6 +303,7 @@ const cbpPlatform = (url, options = {
192
303
  }
193
304
  });
194
305
  global.chatbotPlatform.on('close', err => {
306
+ heartbeatControl.stop(); // 停止心跳
195
307
  logger.warn({
196
308
  code: ResultCode.Fail,
197
309
  message: '平台端连接关闭,尝试重新连接...',
@@ -1,32 +1,3 @@
1
- import { Actions } from '../typing/actions.js'
2
- import { EventsEnum } from '../typing/event/map.js'
3
- import '../global.js'
4
-
5
1
  declare const cbpServer: (port: number, listeningListener?: () => void) => void
6
- /**
7
- * 发送行为
8
- * @param data
9
- */
10
- declare const sendAction: (data: Actions) => Promise<any>
11
- type CBPClientOptions = {
12
- open?: () => void
13
- isFullReceive?: boolean
14
- }
15
- /**
16
- * CBP 客户端
17
- * @param url
18
- * @param onopen
19
- */
20
- declare const cbpClient: (url: string, options?: CBPClientOptions) => void
21
- type ReplyFunc = (data: Actions, consume: (payload: any) => void) => void
22
- declare const cbpPlatform: (
23
- url: string,
24
- options?: {
25
- open: () => void
26
- }
27
- ) => {
28
- send: (data: EventsEnum) => void
29
- onactions: (reply: ReplyFunc) => void
30
- }
31
2
 
32
- export { cbpClient, cbpPlatform, cbpServer, sendAction }
3
+ export { cbpServer }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alemonjs",
3
- "version": "2.1.0-alpha.5",
3
+ "version": "2.1.0-alpha.7",
4
4
  "description": "bot script",
5
5
  "author": "lemonade",
6
6
  "license": "MIT",
@@ -1,17 +0,0 @@
1
- import { DefinePlatformFunc } from '../typing/event/index.js'
2
- import '../global.js'
3
-
4
- /**
5
- * 定义机器人
6
- * @param callback
7
- * @throws {Error} - 如果 callback 无效,抛出错误。
8
- * @returns
9
- */
10
- declare const definePlatform: DefinePlatformFunc
11
- /**
12
- * 废弃,请使用 definePlatform
13
- * @deprecated
14
- */
15
- declare const defineBot: DefinePlatformFunc
16
-
17
- export { defineBot, definePlatform }
@@ -1,39 +0,0 @@
1
- import { ResultCode } from '../core/code.js'
2
-
3
- /**
4
- * 定义机器人
5
- * @param callback
6
- * @throws {Error} - 如果 callback 无效,抛出错误。
7
- * @returns
8
- */
9
- const definePlatform = callback => {
10
- // 判断是否是函数
11
- if (typeof callback !== 'function') {
12
- logger.error({
13
- code: ResultCode.FailParams,
14
- message: 'Invalid callback: callback must be a function',
15
- data: null
16
- })
17
- throw new Error('Invalid callback: callback must be a function')
18
- }
19
- return {
20
- _name: 'platform',
21
- callback
22
- }
23
- }
24
- global.definePlatform = definePlatform
25
- /**
26
- * 废弃,请使用 definePlatform
27
- * @deprecated
28
- */
29
- const defineBot = callback => {
30
- logger.warn({
31
- code: ResultCode.Warn,
32
- message: 'defineBot is deprecated, please use definePlatform',
33
- data: null
34
- })
35
- return definePlatform(callback)
36
- }
37
- global.defineBot = defineBot
38
-
39
- export { defineBot, definePlatform }
@@ -1,9 +0,0 @@
1
- import KoaRouter from 'koa-router'
2
-
3
- const router = new KoaRouter({
4
- prefix: '/message'
5
- })
6
- // 消息发送
7
- router.post('/send', () => {})
8
-
9
- export { router as default }
package/lib/jsx.d.ts DELETED
@@ -1,142 +0,0 @@
1
- import { EventKeys, Events } from './typing/event/map.js'
2
- import { ClientAPIMessageResult } from './typing/client/index.js'
3
- import { DataEnums } from './typing/message/index.js'
4
- import { Result } from './app/utils.js'
5
- import React from 'react'
6
- import { DataImage, DataImageURL, DataImageFile } from './typing/message/image.js'
7
- import { DataButton } from './typing/message/button.js'
8
- import { DataText } from './typing/message/text.js'
9
- import { DataMention } from './typing/message/mention.js'
10
-
11
- /**
12
- *
13
- * @param _props
14
- * @returns
15
- */
16
- declare function Text(
17
- _props:
18
- | {
19
- children?: DataText['value'] | DataText['value'][]
20
- style?: DataText['options']['style']
21
- }
22
- | {
23
- value?: DataText['value'] | DataText['value'][]
24
- style?: DataText['options']['style']
25
- }
26
- ): React.ReactElement<
27
- {
28
- dataType: string
29
- },
30
- string | React.JSXElementConstructor<any>
31
- >
32
- declare const Image: React.FC<{
33
- value: DataImage['value']
34
- }> & {
35
- url: React.FC<{
36
- src: DataImageURL['value']
37
- }>
38
- file: React.FC<{
39
- src: DataImageURL['value']
40
- }>
41
- }
42
-
43
- /**
44
- *
45
- * @param _props
46
- * @returns
47
- */
48
- declare function ImageFile(_props: { src: DataImageFile['value'] }): React.ReactElement<
49
- {
50
- dataType: string
51
- },
52
- string | React.JSXElementConstructor<any>
53
- >
54
- /**
55
- *
56
- * @param _props
57
- * @returns
58
- */
59
- declare function ImageURL(_props: { src: DataImageURL['value'] }): React.ReactElement<
60
- {
61
- dataType: string
62
- },
63
- string | React.JSXElementConstructor<any>
64
- >
65
- /**
66
- *
67
- * @param _props
68
- * @returns
69
- */
70
- declare function Mention(_props: {
71
- belong?: DataMention['options']['belong']
72
- value: DataMention['value']
73
- }): React.ReactElement<
74
- {
75
- dataType: string
76
- },
77
- string | React.JSXElementConstructor<any>
78
- >
79
- interface BTProps {
80
- text: DataButton['value']
81
- data: DataButton['options']['data']
82
- autoEnter?: DataButton['options']['autoEnter']
83
- toolTip?: DataButton['options']['toolTip']
84
- showList?: DataButton['options']['showList']
85
- isLink?: DataButton['options']['isLink']
86
- children?: DataButton['value']
87
- }
88
- declare const BT: React.FC<BTProps> & {
89
- group: React.FC<{
90
- children?: React.ReactNode
91
- }>
92
- row: React.FC<{
93
- children?: React.ReactNode
94
- }>
95
- template: React.FC<{
96
- id: string
97
- }>
98
- }
99
-
100
- /**
101
- * 转换数据
102
- * ***
103
- * 原则上,显示文本。使用 children 属性
104
- * ***
105
- * 其他类型使用 value 属性
106
- * ***
107
- * 如果是资源文件,使用 src 属性
108
- * ***
109
- * @param arg
110
- * @returns
111
- */
112
- declare function JSX(...arg: React.JSX.Element[]): DataEnums[]
113
- /**
114
- * 发送消息
115
- * @param e
116
- * @returns
117
- */
118
- declare const useSend: <T extends EventKeys>(
119
- e: Events[T]
120
- ) => (...arg: React.JSX.Element[]) => Promise<Result | ClientAPIMessageResult[]>
121
- /**
122
- *
123
- * @param channel_id
124
- * @param data
125
- * @returns
126
- */
127
- declare const sendToChannel: (
128
- channel_id: string,
129
- data: React.JSX.Element[]
130
- ) => Promise<ClientAPIMessageResult[]>
131
- /**
132
- *
133
- * @param user_id
134
- * @param data
135
- * @returns
136
- */
137
- declare const sendToUser: (
138
- user_id: string,
139
- data: React.JSX.Element[]
140
- ) => Promise<ClientAPIMessageResult[]>
141
-
142
- export { BT, Image, ImageFile, ImageURL, JSX, Mention, Text, sendToChannel, sendToUser, useSend }
package/lib/jsx.js DELETED
@@ -1,234 +0,0 @@
1
- import React from 'react'
2
- import { logger } from './global.js'
3
- import './app/define-bot.js'
4
- import './app/define-chidren.js'
5
- import './app/event-middleware.js'
6
- import './app/event-processor.js'
7
- import './app/event-response.js'
8
- import { useSend as useSend$1 } from './app/hook-use-api.js'
9
- import './typing/event/actions.js'
10
- import 'fs'
11
- import 'path'
12
- import 'yaml'
13
- import { ResultCode } from './core/code.js'
14
- import 'node:fs'
15
- import 'log4js'
16
- import './app/load.js'
17
- import { sendToChannel as sendToChannel$1, sendToUser as sendToUser$1 } from './app/message-api.js'
18
- import {
19
- Text as Text$1,
20
- ImageURL as ImageURL$1,
21
- ImageFile as ImageFile$1,
22
- Image as Image$1,
23
- Mention as Mention$1,
24
- BT as BT$1
25
- } from './app/message-format.js'
26
- import './app/utils.js'
27
-
28
- /**
29
- *
30
- * @param _props
31
- * @returns
32
- */
33
- function Text(_props) {
34
- return React.createElement('div', {
35
- dataType: 'Text'
36
- })
37
- }
38
- const Image = _props => {
39
- return React.createElement('div', {
40
- dataType: 'Image'
41
- })
42
- }
43
- // BT.group 子组件
44
- Image.url = _props => {
45
- return React.createElement('div', {
46
- dataType: 'ImageURL'
47
- })
48
- }
49
- Image.file = _props => {
50
- return React.createElement('div', {
51
- dataType: 'ImageFile'
52
- })
53
- }
54
- /**
55
- *
56
- * @param _props
57
- * @returns
58
- */
59
- function ImageFile(_props) {
60
- return React.createElement('div', {
61
- dataType: 'ImageFile'
62
- })
63
- }
64
- /**
65
- *
66
- * @param _props
67
- * @returns
68
- */
69
- function ImageURL(_props) {
70
- return React.createElement('div', {
71
- dataType: 'ImageURL'
72
- })
73
- }
74
- /**
75
- *
76
- * @param _props
77
- * @returns
78
- */
79
- function Mention(_props) {
80
- return React.createElement('div', {
81
- dataType: 'Mention'
82
- })
83
- }
84
- const BT = _props => {
85
- return React.createElement('div', {
86
- dataType: 'Button'
87
- })
88
- }
89
- function ButtonGroup(_props) {
90
- return React.createElement('div', {
91
- dataType: 'BT.group'
92
- })
93
- }
94
- function ButtonRows(_props) {
95
- return React.createElement('div', {
96
- dataType: 'BT.row'
97
- })
98
- }
99
- function ButtonTemplate(_props) {
100
- return React.createElement('div', {
101
- dataType: 'BT.group'
102
- })
103
- }
104
- // BT.group 子组件
105
- BT.group = ButtonGroup
106
- // BT.template 子组件
107
- BT.template = ButtonTemplate
108
- // BT.row 子组件
109
- BT.row = ButtonRows
110
- /**
111
- * 转换数据
112
- * ***
113
- * 原则上,显示文本。使用 children 属性
114
- * ***
115
- * 其他类型使用 value 属性
116
- * ***
117
- * 如果是资源文件,使用 src 属性
118
- * ***
119
- * @param arg
120
- * @returns
121
- */
122
- function JSX(...arg) {
123
- const data = []
124
- for (const item of arg) {
125
- const props = item.props
126
- const dataType = item.type()?.props?.dataType
127
- if (dataType === 'Text') {
128
- if (props?.value) {
129
- data.push(
130
- Text$1(props.value, {
131
- style: props?.style
132
- })
133
- )
134
- } else if (props?.children) {
135
- data.push(
136
- Text$1(Array.isArray(props.children) ? props.children.join('') : props.children, {
137
- style: props?.style
138
- })
139
- )
140
- }
141
- } else if (dataType === 'ImageURL') {
142
- data.push(ImageURL$1(props.src))
143
- } else if (dataType === 'ImageFile') {
144
- data.push(ImageFile$1(props.src))
145
- } else if (dataType === 'Image') {
146
- data.push(Image$1(props.value))
147
- } else if (dataType === 'Mention') {
148
- // <@!123456> 文本的显示会被平台显示。不用自己定义显示的文本,此处不使用 children
149
- data.push(
150
- Mention$1(
151
- props.value,
152
- props?.belong
153
- ? {
154
- belong: props?.belong
155
- }
156
- : null
157
- )
158
- )
159
- } else if (dataType === 'BT.group') {
160
- const id = props?.id
161
- if (id) {
162
- data.push(BT$1.template(id))
163
- } else {
164
- if (Array.isArray(props?.children)) {
165
- const rows = []
166
- for (const child of props?.children) {
167
- // 拿到每个子组件
168
- const bts = []
169
- if (Array.isArray(child.children)) {
170
- for (const chi of child.children) {
171
- // const type = chi.children
172
- const value = chi.props?.text
173
- const data = chi.props?.data
174
- const options = {}
175
- if (chi.props?.autoEnter) {
176
- options['autoEnter'] = chi.props?.autoEnter ? true : false
177
- }
178
- if (chi.props?.toolTip) {
179
- options['toolTip'] = chi.props?.toolTip ?? ''
180
- }
181
- if (chi.props?.showList) {
182
- options['showList'] = chi.props?.showList ? true : false
183
- }
184
- if (chi.props?.isLink) {
185
- options['isLink'] = chi.props?.isLink ? true : false
186
- }
187
- bts.push(BT$1(value, data, options))
188
- }
189
- }
190
- rows.push(BT$1.row(...bts))
191
- }
192
- data.push(BT$1.group(...rows))
193
- }
194
- }
195
- }
196
- }
197
- if (data.length === 0) {
198
- logger.warn({
199
- code: ResultCode.FailParams,
200
- message: 'Invalid data: data must be a non-empty array',
201
- data: null
202
- })
203
- }
204
- return data
205
- }
206
- /**
207
- * 发送消息
208
- * @param e
209
- * @returns
210
- */
211
- const useSend = e => {
212
- const Send = useSend$1(e)
213
- return (...arg) => Send(...JSX(...arg))
214
- }
215
- /**
216
- *
217
- * @param channel_id
218
- * @param data
219
- * @returns
220
- */
221
- const sendToChannel = async (channel_id, data) => {
222
- return sendToChannel$1(channel_id, JSX(...data))
223
- }
224
- /**
225
- *
226
- * @param user_id
227
- * @param data
228
- * @returns
229
- */
230
- const sendToUser = async (user_id, data) => {
231
- return sendToUser$1(user_id, JSX(...data))
232
- }
233
-
234
- export { BT, Image, ImageFile, ImageURL, JSX, Mention, Text, sendToChannel, sendToUser, useSend }