@wabot-dev/framework 0.1.0-beta.9 → 0.2.0-beta.1

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 (212) hide show
  1. package/dist/src/addon/async/pg/PgJobRepository.js +26 -0
  2. package/dist/src/addon/auth/api-key/@apiKeyConnectionGuard.js +16 -0
  3. package/dist/src/addon/auth/api-key/@apiKeyGuard.js +17 -0
  4. package/dist/src/addon/auth/api-key/ApiKey.js +45 -0
  5. package/dist/src/addon/auth/api-key/ApiKeyConnectionGuardMiddleware.js +57 -0
  6. package/dist/src/addon/auth/api-key/ApiKeyGuardMiddleware.js +45 -0
  7. package/dist/src/addon/auth/api-key/ApiKeyRepository.js +22 -0
  8. package/dist/src/addon/auth/api-key/PgApiKeyRepository.js +53 -0
  9. package/dist/src/addon/auth/api-key/RemoteApiKeyRepository.js +62 -0
  10. package/dist/src/addon/auth/jwt/@jwtConnectionGuard.js +16 -0
  11. package/dist/src/addon/auth/jwt/@jwtGuard.js +17 -0
  12. package/dist/src/addon/auth/jwt/Jwt.js +53 -0
  13. package/dist/src/addon/auth/jwt/JwtAccessAndRefreshTokenDto.js +20 -0
  14. package/dist/src/addon/auth/jwt/JwtConfig.js +28 -0
  15. package/dist/src/addon/auth/jwt/JwtConnectionGuardMiddleware.js +57 -0
  16. package/dist/src/addon/auth/jwt/JwtGuardMiddleware.js +45 -0
  17. package/dist/src/addon/auth/jwt/JwtRefreshToken.js +56 -0
  18. package/dist/src/addon/auth/jwt/JwtRefreshTokenRepository.js +25 -0
  19. package/dist/src/addon/auth/jwt/JwtSigner.js +36 -0
  20. package/dist/src/addon/auth/jwt/JwtTokenDto.js +22 -0
  21. package/dist/src/addon/auth/jwt/PgJwtRefreshTokenRepository.js +21 -0
  22. package/dist/src/addon/chat-bot/anthropic/AnthropicChatAdapter.js +135 -0
  23. package/dist/src/addon/chat-bot/deepseek/DeepSeekChatAdapter.js +137 -0
  24. package/dist/src/addon/chat-bot/google/GoogleChatAdapter.js +128 -0
  25. package/dist/src/addon/chat-bot/openia/OpenaiChatAdapter.js +117 -0
  26. package/dist/src/{pre-made/repository/chat → addon/chat-bot}/pg/PgChatMemory.js +6 -4
  27. package/dist/src/{pre-made/repository/chat → addon/chat-bot}/pg/PgChatRepository.js +6 -5
  28. package/dist/src/{pre-made/repository/chat → addon/chat-bot}/ram/RamChatRepository.js +2 -2
  29. package/dist/src/addon/chat-bot/wabot/WabotChatAdapter.js +41 -0
  30. package/dist/src/addon/chat-controller/cmd/@cmd.js +24 -0
  31. package/dist/src/addon/chat-controller/cmd/CmdChannel.js +91 -0
  32. package/dist/src/{channels → addon/chat-controller}/socket/@socket.js +10 -4
  33. package/dist/src/{channels → addon/chat-controller}/socket/SocketChannel.js +9 -23
  34. package/dist/src/{channels → addon/chat-controller}/socket/SocketChannelConfig.js +1 -1
  35. package/dist/src/{channels → addon/chat-controller}/telegram/@telegram.js +10 -4
  36. package/dist/src/{channels → addon/chat-controller}/telegram/TelegramChannel.js +4 -22
  37. package/dist/src/addon/chat-controller/whatsapp/@whatsApp.js +26 -0
  38. package/dist/src/{channels → addon/chat-controller}/whatsapp/EnvWhatsAppRepository.js +3 -3
  39. package/dist/src/{channels → addon/chat-controller}/whatsapp/PgWhatsAppRepository.js +2 -2
  40. package/dist/src/{channels → addon/chat-controller}/whatsapp/WhatsApp.js +2 -4
  41. package/dist/src/{channels → addon/chat-controller}/whatsapp/WhatsAppChannel.js +6 -18
  42. package/dist/src/addon/chat-controller/whatsapp/WhatsAppReceiver.js +10 -0
  43. package/dist/src/{channels → addon/chat-controller}/whatsapp/WhatsAppSender.js +15 -39
  44. package/dist/src/addon/chat-controller/whatsapp/cloud-api/WhatsAppReceiverByCloudApi.js +97 -0
  45. package/dist/src/{channels/whatsapp → addon/chat-controller/whatsapp/cloud-api}/WhatsAppSenderByCloudApi.js +27 -20
  46. package/dist/src/addon/chat-controller/whatsapp/proxy/WhatsAppProxyContracts.js +5 -0
  47. package/dist/src/addon/chat-controller/whatsapp/proxy/WhatsAppReceiverByWabotProxy.js +65 -0
  48. package/dist/src/addon/chat-controller/whatsapp/proxy/WhatsAppSenderByWabotProxy.js +61 -0
  49. package/dist/src/addon/chat-controller/whatsapp/proxy/WhatsAppWabotProxyConnection.js +45 -0
  50. package/dist/src/{pre-made/module → addon/mindset}/html/HtmlModule.js +7 -7
  51. package/dist/src/core/auth/Auth.js +33 -0
  52. package/dist/src/core/{Persistent.js → entity/Entity.js} +24 -12
  53. package/dist/src/core/env/Env.js +39 -0
  54. package/dist/src/core/error/CustomError.js +15 -0
  55. package/dist/src/core/injection/index.js +4 -0
  56. package/dist/src/core/mapper/Mapper.js +42 -0
  57. package/dist/src/core/password/Password.js +30 -0
  58. package/dist/src/core/random/Random.js +65 -0
  59. package/dist/src/core/storable/Storable.js +8 -0
  60. package/dist/src/core/validation/core/validateArray.js +51 -0
  61. package/dist/src/core/validation/core/validateModel.js +36 -0
  62. package/dist/src/{validation/metadata/@isNumber.js → core/validation/metadata/@isArray.js} +5 -4
  63. package/dist/src/{validation/metadata/@isDate.js → core/validation/metadata/@isModel.js} +5 -4
  64. package/dist/src/{validation → core/validation}/metadata/@isOptional.js +1 -1
  65. package/dist/src/core/validation/metadata/ValidationMetadataStore.js +98 -0
  66. package/dist/src/core/validation/modelInfo.js +9 -0
  67. package/dist/src/{validation/validateModel2.js → core/validation/validate.js} +3 -3
  68. package/dist/src/{validation/metadata → core/validation/validators/is-boolean}/@isBoolean.js +3 -3
  69. package/dist/src/core/validation/validators/is-date/@isDate.js +17 -0
  70. package/dist/src/core/validation/validators/is-in/@isIn.js +18 -0
  71. package/dist/src/core/validation/validators/is-in/validateIsIn.js +12 -0
  72. package/dist/src/{validation/metadata → core/validation/validators/is-not-empty}/@isNotEmpty.js +3 -3
  73. package/dist/src/core/validation/validators/is-number/@isNumber.js +17 -0
  74. package/dist/src/{validation/metadata → core/validation/validators/is-present}/@isPresent.js +3 -3
  75. package/dist/src/{validation/metadata → core/validation/validators/is-string}/@isString.js +3 -3
  76. package/dist/src/{validation/metadata → core/validation/validators/max}/@max.js +3 -3
  77. package/dist/src/{validation/metadata → core/validation/validators/min}/@min.js +3 -3
  78. package/dist/src/feature/async/@command.js +11 -0
  79. package/dist/src/feature/async/@commandHandler.js +12 -0
  80. package/dist/src/feature/async/Async.js +38 -0
  81. package/dist/src/feature/async/Command.js +9 -0
  82. package/dist/src/feature/async/CommandMetadataStore.js +38 -0
  83. package/dist/src/feature/async/Job.js +27 -0
  84. package/dist/src/feature/async/JobRepository.js +31 -0
  85. package/dist/src/feature/async/JobRunner.js +48 -0
  86. package/dist/src/feature/async/JobsEventsHub.js +36 -0
  87. package/dist/src/feature/async/runCommandHandlers.js +29 -0
  88. package/dist/src/{core/chat → feature/chat-bot}/Chat.js +2 -2
  89. package/dist/src/feature/chat-bot/ChatAdapter.js +7 -0
  90. package/dist/src/feature/chat-bot/ChatBot.js +73 -0
  91. package/dist/src/feature/chat-bot/ChatItem.js +24 -0
  92. package/dist/src/feature/chat-bot/ChatMemory.js +10 -0
  93. package/dist/src/{core/chat/repository/IChatRepository.js → feature/chat-bot/ChatRepository.js} +2 -8
  94. package/dist/src/feature/chat-bot/IChatItem.js +3 -0
  95. package/dist/src/{chatbot → feature/chat-bot}/metadata/@chatBot.js +1 -1
  96. package/dist/src/{chatbot → feature/chat-bot}/metadata/ChatBotMetadataStore.js +1 -1
  97. package/dist/src/{controller/channel → feature/chat-controller}/ChatResolver.js +6 -4
  98. package/dist/src/{controller → feature/chat-controller}/metadata/ControllerMetadataStore.js +1 -1
  99. package/dist/src/{controller → feature/chat-controller}/metadata/controller/@chatController.js +1 -1
  100. package/dist/src/feature/chat-controller/runChatControllers.js +83 -0
  101. package/dist/src/{channels → feature}/express/ExpressProvider.js +2 -4
  102. package/dist/src/{channels → feature}/http/HttpServerProvider.js +2 -2
  103. package/dist/src/{mindset → feature/mindset}/IMindset.js +6 -0
  104. package/dist/src/feature/mindset/MindsetOperator.js +180 -0
  105. package/dist/src/{mindset → feature/mindset}/metadata/MindsetMetadataStore.js +1 -1
  106. package/dist/src/{mindset → feature/mindset}/metadata/functions/@mindsetFunction.js +1 -1
  107. package/dist/src/{mindset → feature/mindset}/metadata/mindsets/@mindset.js +1 -1
  108. package/dist/src/{mindset → feature/mindset}/metadata/modules/@mindsetModule.js +1 -2
  109. package/dist/src/{mindset → feature/mindset}/metadata/params/@param.js +1 -1
  110. package/dist/src/feature/money/Money.js +61 -0
  111. package/dist/src/feature/money/MoneyDto.js +22 -0
  112. package/dist/src/{repository → feature}/pg/PgCrudRepository.js +24 -10
  113. package/dist/src/{repository → feature}/pg/PgRepositoryBase.js +2 -2
  114. package/dist/src/feature/rest-controller/injection-tokens.js +4 -0
  115. package/dist/src/{rest-controller/metadata/@post.js → feature/rest-controller/metadata/@middleware.js} +5 -8
  116. package/dist/src/feature/rest-controller/metadata/@onDelete.js +7 -0
  117. package/dist/src/feature/rest-controller/metadata/@onGet.js +7 -0
  118. package/dist/src/feature/rest-controller/metadata/@onPost.js +7 -0
  119. package/dist/src/feature/rest-controller/metadata/@onPut.js +7 -0
  120. package/dist/src/{rest-controller → feature/rest-controller}/metadata/@restController.js +2 -2
  121. package/dist/src/{rest-controller → feature/rest-controller}/metadata/RestControllerMetadataStore.js +14 -1
  122. package/dist/src/{rest-controller/metadata/@get.js → feature/rest-controller/metadata/methodDecorator.js} +5 -5
  123. package/dist/src/feature/rest-controller/runRestControllers.js +103 -0
  124. package/dist/src/{channels → feature}/socket/SocketServerProvider.js +2 -2
  125. package/dist/src/feature/socket-controller/metadata/@connectionMiddleware.js +16 -0
  126. package/dist/src/feature/socket-controller/metadata/@socketConnection.js +18 -0
  127. package/dist/src/feature/socket-controller/metadata/@socketController.js +15 -0
  128. package/dist/src/feature/socket-controller/metadata/@socketEvent.js +18 -0
  129. package/dist/src/feature/socket-controller/metadata/SocketControllerMetadataStore.js +65 -0
  130. package/dist/src/feature/socket-controller/runSocketControllers.js +99 -0
  131. package/dist/src/index.d.ts +1219 -718
  132. package/dist/src/index.js +147 -102
  133. package/package.json +8 -2
  134. package/dist/src/_virtual/_commonjsHelpers.js +0 -5
  135. package/dist/src/_virtual/cjs.js +0 -7
  136. package/dist/src/ai/deepseek/DeepSeekChatBotAdapter.js +0 -107
  137. package/dist/src/ai/openia/OpenaiChatBotAdapter.js +0 -88
  138. package/dist/src/channels/cmd/@cmd.js +0 -18
  139. package/dist/src/channels/cmd/CmdChannel.js +0 -73
  140. package/dist/src/channels/wabot/WabotDevConnection.js +0 -57
  141. package/dist/src/channels/wabot/WabotDevSocketContracts.js +0 -10
  142. package/dist/src/channels/whatsapp/@whatsapp.js +0 -20
  143. package/dist/src/channels/whatsapp/WhatsAppReceiver.js +0 -59
  144. package/dist/src/channels/whatsapp/WhatsAppReceiverByDevConnection.js +0 -32
  145. package/dist/src/channels/whatsapp/WhatsAppReceiverByWebHook.js +0 -63
  146. package/dist/src/channels/whatsapp/WhatsAppSenderByDevConnection.js +0 -61
  147. package/dist/src/chatbot/ChatBot.js +0 -51
  148. package/dist/src/chatbot/ChatBotAdapter.js +0 -72
  149. package/dist/src/controller/channel/UserResolver.js +0 -21
  150. package/dist/src/core/IMessageContext.js +0 -12
  151. package/dist/src/core/chat/ChatItem.js +0 -15
  152. package/dist/src/core/chat/repository/IChatMemory.js +0 -10
  153. package/dist/src/core/user/IUserRepository.js +0 -19
  154. package/dist/src/core/user/User.js +0 -26
  155. package/dist/src/env/WabotEnv.js +0 -27
  156. package/dist/src/injection/index.js +0 -4
  157. package/dist/src/mindset/MindsetOperator.js +0 -101
  158. package/dist/src/node_modules/@selderee/plugin-htmlparser2/lib/hp2-builder.js +0 -90
  159. package/dist/src/node_modules/deepmerge/dist/cjs.js +0 -142
  160. package/dist/src/node_modules/dom-serializer/lib/esm/foreignNames.js +0 -102
  161. package/dist/src/node_modules/dom-serializer/lib/esm/index.js +0 -186
  162. package/dist/src/node_modules/domelementtype/lib/esm/index.js +0 -53
  163. package/dist/src/node_modules/domhandler/lib/esm/index.js +0 -148
  164. package/dist/src/node_modules/domhandler/lib/esm/node.js +0 -334
  165. package/dist/src/node_modules/entities/lib/esm/decode.js +0 -458
  166. package/dist/src/node_modules/entities/lib/esm/decode_codepoint.js +0 -62
  167. package/dist/src/node_modules/entities/lib/esm/escape.js +0 -99
  168. package/dist/src/node_modules/entities/lib/esm/generated/decode-data-html.js +0 -8
  169. package/dist/src/node_modules/entities/lib/esm/generated/decode-data-xml.js +0 -8
  170. package/dist/src/node_modules/html-to-text/lib/html-to-text.js +0 -2147
  171. package/dist/src/node_modules/htmlparser2/lib/esm/Parser.js +0 -491
  172. package/dist/src/node_modules/htmlparser2/lib/esm/Tokenizer.js +0 -928
  173. package/dist/src/node_modules/htmlparser2/lib/esm/index.js +0 -18
  174. package/dist/src/node_modules/leac/lib/leac.js +0 -3
  175. package/dist/src/node_modules/parseley/lib/parseley.js +0 -270
  176. package/dist/src/node_modules/peberminta/lib/core.js +0 -171
  177. package/dist/src/node_modules/selderee/lib/selderee.js +0 -380
  178. package/dist/src/pre-made/module/authentication/AuthenticationModule.js +0 -97
  179. package/dist/src/pre-made/module/authentication/requests/SendOneTimePasswordRequest.js +0 -25
  180. package/dist/src/pre-made/module/authentication/requests/ValidateOneTimePasswordRequest.js +0 -25
  181. package/dist/src/pre-made/module/register-user/RegisterUserModule.js +0 -56
  182. package/dist/src/pre-made/module/register-user/requests/RegisterUserWithEmailRequest.js +0 -25
  183. package/dist/src/pre-made/repository/user/pg/PgUserRepository.js +0 -33
  184. package/dist/src/pre-made/repository/user/ram/RamUserRepository.js +0 -27
  185. package/dist/src/pre-made/service/EmailService.js +0 -13
  186. package/dist/src/pre-made/service/OtpService.js +0 -14
  187. package/dist/src/rest-controller/runRestControllers.js +0 -74
  188. package/dist/src/server/prepareChatContainer.js +0 -43
  189. package/dist/src/server/runChannel.js +0 -27
  190. package/dist/src/server/runServer.js +0 -40
  191. package/dist/src/validation/metadata/@validable.js +0 -14
  192. package/dist/src/validation/metadata/ValidationMetadataStore.js +0 -55
  193. package/dist/src/validation/validators/validateModel.js +0 -47
  194. /package/dist/src/{pre-made/repository/chat → addon/chat-bot}/ram/RamChatMemory.js +0 -0
  195. /package/dist/src/{channels → addon/chat-controller}/telegram/TelegramChannelConfig.js +0 -0
  196. /package/dist/src/{channels → addon/chat-controller}/whatsapp/WhatsAppChannelConfig.js +0 -0
  197. /package/dist/src/{channels → addon/chat-controller}/whatsapp/WhatsAppRepository.js +0 -0
  198. /package/dist/src/{injection → core/injection}/Container.js +0 -0
  199. /package/dist/src/{logger → core/logger}/Logger.js +0 -0
  200. /package/dist/src/{validation/validators → core/validation/core}/validateIsOptional.js +0 -0
  201. /package/dist/src/{validation/validators → core/validation/validators/is-boolean}/validateIsBoolean.js +0 -0
  202. /package/dist/src/{validation/validators → core/validation/validators/is-date}/validateIsDate.js +0 -0
  203. /package/dist/src/{validation/validators → core/validation/validators/is-not-empty}/validateIsNotEmpty.js +0 -0
  204. /package/dist/src/{validation/validators → core/validation/validators/is-number}/validateIsNumber.js +0 -0
  205. /package/dist/src/{validation/validators → core/validation/validators/is-present}/validateIsPresent.js +0 -0
  206. /package/dist/src/{validation/validators → core/validation/validators/is-string}/validateIsString.js +0 -0
  207. /package/dist/src/{validation/validators → core/validation/validators/max}/validateMax.js +0 -0
  208. /package/dist/src/{validation/validators → core/validation/validators/min}/validateMin.js +0 -0
  209. /package/dist/src/{mindset → feature/mindset}/metadata/functions/decoratorNames.js +0 -0
  210. /package/dist/src/{mindset → feature/mindset}/metadata/mindsets/decoratorNames.js +0 -0
  211. /package/dist/src/{mindset → feature/mindset}/metadata/modules/decoratorNames.js +0 -0
  212. /package/dist/src/{mindset → feature/mindset}/metadata/params/decoratorNames.js +0 -0
@@ -1,20 +1,25 @@
1
1
  import { __decorate, __metadata } from 'tslib';
2
- import { Logger } from '../../logger/Logger.js';
3
- import { WhatsAppSender } from './WhatsAppSender.js';
4
- import { ChatRepository } from '../../core/chat/repository/IChatRepository.js';
5
- import '../../core/user/IUserRepository.js';
6
- import { ChatResolver } from '../../controller/channel/ChatResolver.js';
7
- import '../../controller/channel/UserResolver.js';
8
- import { singleton, container } from '../../injection/index.js';
9
- import '../../controller/metadata/ControllerMetadataStore.js';
10
- import { WhatsAppRepository } from './WhatsAppRepository.js';
11
- import { WabotDevConnection } from '../wabot/WabotDevConnection.js';
2
+ import { Logger } from '../../../../core/logger/Logger.js';
3
+ import { WhatsAppSender } from '../WhatsAppSender.js';
4
+ import { singleton } from '../../../../core/injection/index.js';
5
+ import '../../../../feature/chat-controller/metadata/ControllerMetadataStore.js';
6
+ import { ChatResolver } from '../../../../feature/chat-controller/ChatResolver.js';
7
+ import '../../../../core/auth/Auth.js';
8
+ import '../../../../feature/chat-bot/ChatBot.js';
9
+ import { ChatRepository } from '../../../../feature/chat-bot/ChatRepository.js';
10
+ import 'uuid';
11
+ import '../../../../feature/chat-bot/metadata/ChatBotMetadataStore.js';
12
+ import 'reflect-metadata';
13
+ import '../../../../feature/mindset/metadata/MindsetMetadataStore.js';
14
+ import '../../../../feature/mindset/MindsetOperator.js';
15
+ import { WhatsAppRepository } from '../WhatsAppRepository.js';
12
16
 
13
17
  let WhatsAppSenderByCloudApi = class WhatsAppSenderByCloudApi extends WhatsAppSender {
18
+ logger = new Logger('wabot:whatsapp-sender-by-cloud-api');
14
19
  constructor(chatRepository, chatResolver, whatsAppRepository) {
15
- super(new Logger('wabot:whatsapp-sender-by-cloud-api'), chatRepository, chatResolver, whatsAppRepository);
20
+ super(chatRepository, chatResolver, whatsAppRepository);
16
21
  }
17
- async handleSendRequest(request) {
22
+ async sendWhatsApp(request, options) {
18
23
  const whatsApp = await this.whatsAppRepository.findByBusinessNumber(request.from);
19
24
  if (!whatsApp) {
20
25
  throw new Error(`not found WhatsApp with bussiness number '${request.from}'`);
@@ -43,8 +48,11 @@ let WhatsAppSenderByCloudApi = class WhatsAppSenderByCloudApi extends WhatsAppSe
43
48
  if (!response.ok) {
44
49
  throw new Error(JSON.stringify(data));
45
50
  }
51
+ if (options?.writeChatMemory) {
52
+ await this.writePrivateChatMemory(request.message, request.to);
53
+ }
46
54
  }
47
- async handleSendTemplateRequest(request) {
55
+ async sendWhatsAppTemplate(request, options) {
48
56
  const whatsApp = await this.whatsAppRepository.findByBusinessNumber(request.from);
49
57
  if (!whatsApp) {
50
58
  throw new Error(`not found WhatsApp with bussiness number '${request.from}'`);
@@ -80,8 +88,12 @@ let WhatsAppSenderByCloudApi = class WhatsAppSenderByCloudApi extends WhatsAppSe
80
88
  if (!response.ok) {
81
89
  throw new Error(JSON.stringify(data));
82
90
  }
91
+ if (options?.writeChatMemory) {
92
+ const message = await this.mapTemplateToChatMessage(request);
93
+ await this.writePrivateChatMemory(message, request.to);
94
+ }
83
95
  }
84
- async handleGetWhatsAppTemplate(request) {
96
+ async getWhatsAppTemplate(request) {
85
97
  const whatsApp = await this.whatsAppRepository.findByBusinessNumber(request.from);
86
98
  if (!whatsApp) {
87
99
  throw new Error(`not found WhatsApp with bussiness number '${request.from}'`);
@@ -104,7 +116,7 @@ let WhatsAppSenderByCloudApi = class WhatsAppSenderByCloudApi extends WhatsAppSe
104
116
  return template;
105
117
  }
106
118
  catch (error) {
107
- console.error('Failed to get WhatsApp template:', error);
119
+ this.logger.error(error);
108
120
  throw error;
109
121
  }
110
122
  }
@@ -115,10 +127,5 @@ WhatsAppSenderByCloudApi = __decorate([
115
127
  ChatResolver,
116
128
  WhatsAppRepository])
117
129
  ], WhatsAppSenderByCloudApi);
118
- if (!WabotDevConnection.isTokenAvailable()) {
119
- container.register(WhatsAppSender, {
120
- useClass: WhatsAppSenderByCloudApi,
121
- });
122
- }
123
130
 
124
131
  export { WhatsAppSenderByCloudApi };
@@ -0,0 +1,5 @@
1
+ const WHATSAPP_PROXY_SEND_MESSAGE_EVENT = 'sendMessage';
2
+ const WHATSAPP_PROXY_LISTEN_MESSAGE_EVENT = 'listenMessage';
3
+ const WHATSAPP_MESSAGE_EVENT = 'message';
4
+
5
+ export { WHATSAPP_MESSAGE_EVENT, WHATSAPP_PROXY_LISTEN_MESSAGE_EVENT, WHATSAPP_PROXY_SEND_MESSAGE_EVENT };
@@ -0,0 +1,65 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { WhatsAppReceiver } from '../WhatsAppReceiver.js';
3
+ import { injectable } from '../../../../core/injection/index.js';
4
+ import { Logger } from '../../../../core/logger/Logger.js';
5
+ import { WHATSAPP_MESSAGE_EVENT } from './WhatsAppProxyContracts.js';
6
+ import { WhatsAppWabotProxyConnection } from './WhatsAppWabotProxyConnection.js';
7
+
8
+ let WhatsAppReceiverByWabotProxy = class WhatsAppReceiverByWabotProxy extends WhatsAppReceiver {
9
+ connection;
10
+ loger = new Logger('wabot:whats-app-receiver-by-wabot-proxy');
11
+ constructor(connection) {
12
+ super();
13
+ this.connection = connection;
14
+ }
15
+ async connect() {
16
+ // Nothing
17
+ }
18
+ listenMessage(request) {
19
+ this.connection.getSocket().then(async (socket) => {
20
+ const req = {
21
+ event: 'listenMessage',
22
+ data: {
23
+ to: [request.to],
24
+ },
25
+ };
26
+ const response = await socket.emitWithAck(req.event, req.data);
27
+ if (response && typeof response == 'object' && response['error']) {
28
+ this.loger.error(response.error);
29
+ return;
30
+ }
31
+ else if (!response ||
32
+ typeof response !== 'object' ||
33
+ !Array.isArray(response.from) ||
34
+ !Array.isArray(response.to)) {
35
+ this.loger.error('unknown response');
36
+ return;
37
+ }
38
+ this.loger.trace(`succes add whats-app proxy listener for messages from [${response.from.join(',')}] to [${response.to.join(',')}]`);
39
+ socket.on(WHATSAPP_MESSAGE_EVENT, (data, callback) => {
40
+ if (data.to !== request.to) {
41
+ throw new Error(`expecting message to '${request.to}' but received to='${data.to}'`);
42
+ }
43
+ callback({ success: true });
44
+ this.loger.trace(`success receive message from '${data.from}' to '${data.to}'`);
45
+ request.listener({
46
+ chatConnection: {
47
+ channelName: 'WhatsAppChannel',
48
+ id: data.from,
49
+ },
50
+ message: {
51
+ text: data.content.text,
52
+ senderName: data.senderName,
53
+ senderId: data.from,
54
+ },
55
+ });
56
+ });
57
+ });
58
+ }
59
+ };
60
+ WhatsAppReceiverByWabotProxy = __decorate([
61
+ injectable(),
62
+ __metadata("design:paramtypes", [WhatsAppWabotProxyConnection])
63
+ ], WhatsAppReceiverByWabotProxy);
64
+
65
+ export { WhatsAppReceiverByWabotProxy };
@@ -0,0 +1,61 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { WhatsAppSender } from '../WhatsAppSender.js';
3
+ import { singleton } from '../../../../core/injection/index.js';
4
+ import { Logger } from '../../../../core/logger/Logger.js';
5
+ import '../../../../feature/chat-bot/ChatBot.js';
6
+ import { ChatRepository } from '../../../../feature/chat-bot/ChatRepository.js';
7
+ import 'uuid';
8
+ import '../../../../feature/chat-bot/metadata/ChatBotMetadataStore.js';
9
+ import '../../../../feature/chat-controller/metadata/ControllerMetadataStore.js';
10
+ import { ChatResolver } from '../../../../feature/chat-controller/ChatResolver.js';
11
+ import '../../../../core/auth/Auth.js';
12
+ import 'reflect-metadata';
13
+ import '../../../../feature/mindset/metadata/MindsetMetadataStore.js';
14
+ import '../../../../feature/mindset/MindsetOperator.js';
15
+ import { WhatsAppRepository } from '../WhatsAppRepository.js';
16
+ import { WhatsAppWabotProxyConnection } from './WhatsAppWabotProxyConnection.js';
17
+
18
+ let WhatsAppSenderByWabotProxy = class WhatsAppSenderByWabotProxy extends WhatsAppSender {
19
+ wabotDevConnection;
20
+ logger = new Logger('wabot:whatsapp-sender-by-wabot-proxy');
21
+ constructor(wabotDevConnection, chatRepository, chatResolver, whatsAppRepository) {
22
+ super(chatRepository, chatResolver, whatsAppRepository);
23
+ this.wabotDevConnection = wabotDevConnection;
24
+ }
25
+ async sendWhatsApp(request, options) {
26
+ try {
27
+ const socket = await this.wabotDevConnection.getSocket();
28
+ const req = {
29
+ event: 'sendMessage',
30
+ data: {
31
+ from: request.from,
32
+ to: request.to,
33
+ content: {
34
+ text: request.message.text ?? 'No Text',
35
+ },
36
+ },
37
+ };
38
+ const ack = await socket.timeout(5000).emitWithAck(req.event, req.data);
39
+ if (!ack || !ack.success) {
40
+ throw new Error(`not success ack, when send whatsapp from '${request.from}' to '${request.to}'`);
41
+ }
42
+ this.logger.trace(`success send whatsapp from '${request.from}' to '${request.to}'`);
43
+ if (options?.writeChatMemory) {
44
+ await this.writePrivateChatMemory(request.message, request.to);
45
+ }
46
+ }
47
+ catch (err) {
48
+ this.logger.error(err);
49
+ throw new Error(undefined, { cause: err });
50
+ }
51
+ }
52
+ };
53
+ WhatsAppSenderByWabotProxy = __decorate([
54
+ singleton(),
55
+ __metadata("design:paramtypes", [WhatsAppWabotProxyConnection,
56
+ ChatRepository,
57
+ ChatResolver,
58
+ WhatsAppRepository])
59
+ ], WhatsAppSenderByWabotProxy);
60
+
61
+ export { WhatsAppSenderByWabotProxy };
@@ -0,0 +1,45 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { Env } from '../../../../core/env/Env.js';
3
+ import { injectable } from '../../../../core/injection/index.js';
4
+ import { Logger } from '../../../../core/logger/Logger.js';
5
+ import { io } from 'socket.io-client';
6
+
7
+ let WhatsAppWabotProxyConnection = class WhatsAppWabotProxyConnection {
8
+ baseUrl;
9
+ socket = null;
10
+ apiKey;
11
+ logger = new Logger('wabot:whats-app-wabot-proxy-connection');
12
+ constructor(env) {
13
+ this.apiKey = env.requireString('WABOT_API_KEY');
14
+ this.baseUrl = env.requireString('WABOT_PROXY_URL');
15
+ while (this.baseUrl.endsWith('/')) {
16
+ this.baseUrl = this.baseUrl.substring(0, this.baseUrl.length - 1);
17
+ }
18
+ }
19
+ async getSocket() {
20
+ if (this.socket) {
21
+ return this.socket;
22
+ }
23
+ return new Promise((resolve, reject) => {
24
+ const socket = io(`${this.baseUrl}/whats-app`, {
25
+ autoConnect: false,
26
+ auth: { token: this.apiKey },
27
+ reconnection: true,
28
+ });
29
+ socket.on('connect', async () => {
30
+ this.socket = socket;
31
+ resolve(socket);
32
+ });
33
+ socket.on('connect_error', (err) => {
34
+ reject(new Error(err && err.message ? err.message : 'connection error', { cause: err }));
35
+ });
36
+ socket.connect();
37
+ });
38
+ }
39
+ };
40
+ WhatsAppWabotProxyConnection = __decorate([
41
+ injectable(),
42
+ __metadata("design:paramtypes", [Env])
43
+ ], WhatsAppWabotProxyConnection);
44
+
45
+ export { WhatsAppWabotProxyConnection };
@@ -1,12 +1,12 @@
1
1
  import { __decorate, __metadata } from 'tslib';
2
- import { mindsetFunction } from '../../../mindset/metadata/functions/@mindsetFunction.js';
2
+ import { mindsetFunction } from '../../../feature/mindset/metadata/functions/@mindsetFunction.js';
3
3
  import 'reflect-metadata';
4
- import '../../../injection/index.js';
5
- import '../../../mindset/metadata/MindsetMetadataStore.js';
6
- import { mindsetModule } from '../../../mindset/metadata/modules/@mindsetModule.js';
7
- import { param } from '../../../mindset/metadata/params/@param.js';
8
- import '../../../mindset/MindsetOperator.js';
9
- import { convert } from '../../../node_modules/html-to-text/lib/html-to-text.js';
4
+ import '../../../core/injection/index.js';
5
+ import '../../../feature/mindset/metadata/MindsetMetadataStore.js';
6
+ import { mindsetModule } from '../../../feature/mindset/metadata/modules/@mindsetModule.js';
7
+ import { param } from '../../../feature/mindset/metadata/params/@param.js';
8
+ import '../../../feature/mindset/MindsetOperator.js';
9
+ import { convert } from 'html-to-text';
10
10
 
11
11
  function toPascalCaseFunctionName(title) {
12
12
  const cleaned = title.replace(/[^a-zA-Z0-9]+/g, ' ');
@@ -0,0 +1,33 @@
1
+ import { __decorate } from 'tslib';
2
+ import { CustomError } from '../error/CustomError.js';
3
+ import { scoped, Lifecycle } from '../injection/index.js';
4
+
5
+ let Auth = class Auth {
6
+ authInfo = null;
7
+ require() {
8
+ if (!this.authInfo) {
9
+ throw new CustomError({ message: 'Unauthorized', httpCode: 401 });
10
+ }
11
+ return this.authInfo;
12
+ }
13
+ assign(authInfo) {
14
+ if (this.authInfo) {
15
+ throw new CustomError({ message: 'Authorization info already assigned', httpCode: 401 });
16
+ }
17
+ this.authInfo = authInfo;
18
+ }
19
+ override(authInfo) {
20
+ this.authInfo = authInfo;
21
+ }
22
+ clear() {
23
+ this.authInfo = null;
24
+ }
25
+ isAssigned() {
26
+ return this.authInfo !== null;
27
+ }
28
+ };
29
+ Auth = __decorate([
30
+ scoped(Lifecycle.ContainerScoped)
31
+ ], Auth);
32
+
33
+ export { Auth };
@@ -1,22 +1,32 @@
1
- class Persistent {
2
- data;
3
- constructor(data) {
4
- this.data = data;
5
- }
6
- getId() {
1
+ import { Storable } from '../storable/Storable.js';
2
+
3
+ class Entity extends Storable {
4
+ get id() {
7
5
  if (!this.data.id) {
8
6
  throw new Error('id is required');
9
7
  }
10
8
  return this.data.id;
11
9
  }
12
- getCreatedAt() {
10
+ /**
11
+ * @deprecated use id
12
+ */
13
+ getId() {
14
+ return this.id;
15
+ }
16
+ get createdAt() {
13
17
  if (!this.data.createdAt) {
14
18
  throw new Error('createdAt is required');
15
19
  }
16
20
  return new Date(this.data.createdAt);
17
21
  }
22
+ /**
23
+ * @deprecated use createdAt
24
+ */
25
+ getCreatedAt() {
26
+ return this.createdAt;
27
+ }
18
28
  update(newData) {
19
- this.data = newData;
29
+ this.data = { ...this.data, ...newData, updatedAt: new Date().getTime() };
20
30
  }
21
31
  wasCreated() {
22
32
  return !!this.data.createdAt || !!this.data.id;
@@ -29,9 +39,11 @@ class Persistent {
29
39
  throw new Error('createdAt is required');
30
40
  }
31
41
  }
32
- discard() {
33
- this.data.discardedAt = new Date().getTime();
34
- }
42
+ }
43
+ /**
44
+ * @deprecated Should use Entity
45
+ */
46
+ class Persistent extends Entity {
35
47
  }
36
48
 
37
- export { Persistent };
49
+ export { Entity, Persistent };
@@ -0,0 +1,39 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { singleton } from '../injection/index.js';
3
+
4
+ let Env = class Env {
5
+ envType;
6
+ constructor() {
7
+ this.envType = process.env.WABOT_ENV ?? 'development';
8
+ }
9
+ isDevelopment() {
10
+ return this.envType === 'development';
11
+ }
12
+ isProduction() {
13
+ return this.envType === 'production';
14
+ }
15
+ isTesting() {
16
+ return this.envType === 'testing';
17
+ }
18
+ requireString(varName, options) {
19
+ const value = process.env[varName] ?? options?.default;
20
+ if (!value)
21
+ throw new Error(`Env Variable ${varName} is required`);
22
+ return value;
23
+ }
24
+ requireNumber(varName, options) {
25
+ const strValue = this.requireString(varName, {
26
+ default: options?.default != null ? String(options.default) : undefined,
27
+ });
28
+ const value = Number(strValue);
29
+ if (isNaN(value))
30
+ throw new Error(`Env Variable ${varName} should have number format`);
31
+ return value;
32
+ }
33
+ };
34
+ Env = __decorate([
35
+ singleton(),
36
+ __metadata("design:paramtypes", [])
37
+ ], Env);
38
+
39
+ export { Env };
@@ -0,0 +1,15 @@
1
+ class CustomError extends Error {
2
+ humanMessage;
3
+ code;
4
+ httpCode;
5
+ info;
6
+ constructor(data) {
7
+ super(data.message, { cause: data.cause });
8
+ this.humanMessage = data.humanMessage;
9
+ this.code = data.code;
10
+ this.httpCode = data.httpCode;
11
+ this.info = data.info;
12
+ }
13
+ }
14
+
15
+ export { CustomError };
@@ -0,0 +1,4 @@
1
+ await import('reflect-metadata');
2
+ const { injectable, container, singleton, inject, scoped, Lifecycle } = await import('tsyringe');
3
+
4
+ export { Lifecycle, container, inject, injectable, scoped, singleton };
@@ -0,0 +1,42 @@
1
+ import { Storable } from '../storable/Storable.js';
2
+ import { CustomError } from '../error/CustomError.js';
3
+ import '../injection/index.js';
4
+ import '../validation/metadata/ValidationMetadataStore.js';
5
+ import { validate } from '../validation/validate.js';
6
+
7
+ function deepCopyWithStorable(obj) {
8
+ if (obj === null || typeof obj !== 'object') {
9
+ return obj;
10
+ }
11
+ if (obj instanceof Date) {
12
+ return obj.getTime();
13
+ }
14
+ if (obj instanceof Storable) {
15
+ return deepCopyWithStorable(obj['data']);
16
+ }
17
+ if (Array.isArray(obj)) {
18
+ return obj.map((item) => deepCopyWithStorable(item));
19
+ }
20
+ const copy = {};
21
+ for (const key in obj) {
22
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
23
+ copy[key] = deepCopyWithStorable(obj[key]);
24
+ }
25
+ }
26
+ return copy;
27
+ }
28
+ class Mapper {
29
+ map(data, ctor) {
30
+ const validationResult = validate(deepCopyWithStorable(data), ctor);
31
+ if (validationResult.error) {
32
+ throw new CustomError({
33
+ httpCode: 500,
34
+ message: `Cant map value to ${ctor.name}`,
35
+ info: validationResult.error,
36
+ });
37
+ }
38
+ return validationResult.value;
39
+ }
40
+ }
41
+
42
+ export { Mapper };
@@ -0,0 +1,30 @@
1
+ import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
2
+ import { Random } from '../random/Random.js';
3
+
4
+ class Password {
5
+ static hash(options) {
6
+ const { password: secret, saltLength = 16, keyLength = 64 } = options;
7
+ const salt = randomBytes(saltLength).toString('hex');
8
+ const derivedKey = scryptSync(secret, salt, keyLength);
9
+ return `${salt}:${derivedKey.toString('hex')}`;
10
+ }
11
+ static isValid(req) {
12
+ const [salt, storedKeyHex] = req.hash.split(':');
13
+ if (!salt || !storedKeyHex)
14
+ return false;
15
+ try {
16
+ const keyLength = Buffer.from(storedKeyHex, 'hex').length;
17
+ const derivedKey = scryptSync(req.password, salt, keyLength);
18
+ const storedKey = Buffer.from(storedKeyHex, 'hex');
19
+ return timingSafeEqual(derivedKey, storedKey);
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }
25
+ static generate(length) {
26
+ return Random.alphaNumeric(length);
27
+ }
28
+ }
29
+
30
+ export { Password };
@@ -0,0 +1,65 @@
1
+ import { randomBytes } from 'node:crypto';
2
+
3
+ const DIGITS = '0123456789';
4
+ const ALPHA_NUMERIC_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
5
+ const ALPHA_NUMERIC_LOWER_CASE_CHARSET = 'abcdefghijklmnopqrstuvwxyz0123456789';
6
+ class Random {
7
+ static integer(options) {
8
+ const { min, max } = options;
9
+ if (min > max) {
10
+ throw new RangeError('min must be less than or equal to max');
11
+ }
12
+ const range = max - min + 1;
13
+ if (range <= 0) {
14
+ throw new RangeError('Range must be a positive number');
15
+ }
16
+ const byteSize = 6; // gives us up to 2^48
17
+ const maxGeneratedValue = Math.pow(2, byteSize * 8) - 1;
18
+ const maxAcceptable = maxGeneratedValue - (maxGeneratedValue % range);
19
+ let randomNumber;
20
+ do {
21
+ randomNumber = parseInt(randomBytes(byteSize).toString('hex'), 16);
22
+ } while (randomNumber >= maxAcceptable);
23
+ return min + (randomNumber % range);
24
+ }
25
+ static slug(name, options) {
26
+ const base = name
27
+ .toLowerCase()
28
+ .trim()
29
+ .replace(/[\s\_]+/g, '-') // spaces/underscores to hyphens
30
+ .replace(/[^a-z0-9\-]/g, '') // remove non-alphanumeric except hyphens
31
+ .replace(/\-+/g, '-') // collapse multiple hyphens
32
+ .replace(/^\-+|\-+$/g, ''); // trim hyphens from ends
33
+ const random = this.alphaNumericLowerCase(options.randomLength);
34
+ return `${base}-${random}`;
35
+ }
36
+ static alphaNumeric(length) {
37
+ const bytes = randomBytes(length);
38
+ let result = '';
39
+ for (let i = 0; i < length; i++) {
40
+ const index = bytes[i] % ALPHA_NUMERIC_CHARSET.length;
41
+ result += ALPHA_NUMERIC_CHARSET[index];
42
+ }
43
+ return result;
44
+ }
45
+ static alphaNumericLowerCase(length) {
46
+ const bytes = randomBytes(length);
47
+ let result = '';
48
+ for (let i = 0; i < length; i++) {
49
+ const index = bytes[i] % ALPHA_NUMERIC_LOWER_CASE_CHARSET.length;
50
+ result += ALPHA_NUMERIC_LOWER_CASE_CHARSET[index];
51
+ }
52
+ return result;
53
+ }
54
+ static numberCode(length) {
55
+ const bytes = randomBytes(length);
56
+ let result = '';
57
+ for (let i = 0; i < length; i++) {
58
+ const index = bytes[i] % 10; // 0–9
59
+ result += DIGITS[index];
60
+ }
61
+ return result;
62
+ }
63
+ }
64
+
65
+ export { Random };
@@ -0,0 +1,8 @@
1
+ class Storable {
2
+ data;
3
+ constructor(data) {
4
+ this.data = data;
5
+ }
6
+ }
7
+
8
+ export { Storable };
@@ -0,0 +1,51 @@
1
+ function validateArray(value, options) {
2
+ if (!Array.isArray(value)) {
3
+ return {
4
+ error: { description: 'Should be an array', items: [] },
5
+ };
6
+ }
7
+ if (options?.minLength != null && value.length < options.minLength) {
8
+ return {
9
+ error: { description: 'exceeds the established min length limit', items: [] },
10
+ };
11
+ }
12
+ if (options?.maxLength != null && value.length > options.maxLength) {
13
+ return {
14
+ error: { description: 'exceeds the established max length limit', items: [] },
15
+ };
16
+ }
17
+ const { itemsValidator } = options ?? {};
18
+ const valueOut = [];
19
+ const errorItems = [];
20
+ for (const item of value) {
21
+ let itemOut = item;
22
+ const itemErrors = [];
23
+ for (const itemValidator of itemsValidator ?? []) {
24
+ const { error, value } = itemValidator.validator(itemOut, itemValidator.options);
25
+ if (error) {
26
+ itemErrors.push(error);
27
+ }
28
+ else {
29
+ itemOut = value;
30
+ }
31
+ }
32
+ if (itemErrors.length == 0) {
33
+ valueOut.push(itemOut);
34
+ errorItems.push(null);
35
+ }
36
+ else {
37
+ valueOut.push(null);
38
+ errorItems.push(itemErrors);
39
+ }
40
+ }
41
+ if (errorItems.some((x) => x != null)) {
42
+ return {
43
+ error: { description: 'Error on some items', items: errorItems },
44
+ };
45
+ }
46
+ return {
47
+ value: valueOut,
48
+ };
49
+ }
50
+
51
+ export { validateArray };