@wabot-dev/framework 0.1.0-beta.11 → 0.1.0-beta.12

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.
@@ -1,8 +1,8 @@
1
1
  import '../../core/chat/repository/IChatRepository.js';
2
- import { Persistent } from '../../core/Persistent.js';
2
+ import { Entity } from '../../core/Entity.js';
3
3
  import '../../core/user/IUserRepository.js';
4
4
 
5
- class WhatsApp extends Persistent {
5
+ class WhatsApp extends Entity {
6
6
  getVerifyToken() {
7
7
  return this.data.verifyToken;
8
8
  }
@@ -13,6 +13,15 @@ class WhatsAppSender {
13
13
  this.chatResolver = chatResolver;
14
14
  this.whatsAppRepository = whatsAppRepository;
15
15
  }
16
+ handleSendRequest(request) {
17
+ throw new Error('Not implemented');
18
+ }
19
+ handleSendTemplateRequest(request) {
20
+ throw new Error('Not implemented');
21
+ }
22
+ handleGetWhatsAppTemplate(request) {
23
+ throw new Error('Not implemented');
24
+ }
16
25
  async sendWhatsApp(request, options) {
17
26
  try {
18
27
  await this.handleSendRequest(request);
@@ -73,7 +82,7 @@ class WhatsAppSender {
73
82
  channelName: 'WhatsAppChannel',
74
83
  };
75
84
  const chat = await this.chatResolver.resolve(chatConnection);
76
- const chatMemory = await this.chatRepository.findMemory(chat.getId());
85
+ const chatMemory = await this.chatRepository.findMemory(chat.id);
77
86
  const chatItem = new ChatItem({
78
87
  type: 'BOT_MESSAGE',
79
88
  content: message,
@@ -1,14 +1,13 @@
1
1
  import { __decorate, __metadata } from 'tslib';
2
2
  import { Logger } from '../../logger/Logger.js';
3
3
  import { WhatsAppSender } from './WhatsAppSender.js';
4
- import { ChatRepository } from '../../core/chat/repository/IChatRepository.js';
5
- import '../../core/user/IUserRepository.js';
6
4
  import { ChatResolver } from '../../controller/channel/ChatResolver.js';
7
5
  import '../../controller/channel/UserResolver.js';
8
- import { singleton, container } from '../../injection/index.js';
6
+ import { singleton } from '../../injection/index.js';
9
7
  import '../../controller/metadata/ControllerMetadataStore.js';
8
+ import { ChatRepository } from '../../core/chat/repository/IChatRepository.js';
9
+ import '../../core/user/IUserRepository.js';
10
10
  import { WhatsAppRepository } from './WhatsAppRepository.js';
11
- import { WabotDevConnection } from '../wabot/WabotDevConnection.js';
12
11
 
13
12
  let WhatsAppSenderByCloudApi = class WhatsAppSenderByCloudApi extends WhatsAppSender {
14
13
  constructor(chatRepository, chatResolver, whatsAppRepository) {
@@ -115,10 +114,5 @@ WhatsAppSenderByCloudApi = __decorate([
115
114
  ChatResolver,
116
115
  WhatsAppRepository])
117
116
  ], WhatsAppSenderByCloudApi);
118
- if (!WabotDevConnection.isTokenAvailable()) {
119
- container.register(WhatsAppSender, {
120
- useClass: WhatsAppSenderByCloudApi,
121
- });
122
- }
123
117
 
124
118
  export { WhatsAppSenderByCloudApi };
@@ -1,14 +1,14 @@
1
1
  import { __decorate, __metadata } from 'tslib';
2
2
  import { WhatsAppSender } from './WhatsAppSender.js';
3
- import { WabotDevConnection } from '../wabot/WabotDevConnection.js';
4
- import { devEmitEvent } from '../wabot/WabotDevSocketContracts.js';
5
- import { Logger } from '../../logger/Logger.js';
6
- import { ChatRepository } from '../../core/chat/repository/IChatRepository.js';
7
- import '../../core/user/IUserRepository.js';
8
- import { singleton, container } from '../../injection/index.js';
9
3
  import { ChatResolver } from '../../controller/channel/ChatResolver.js';
10
4
  import '../../controller/channel/UserResolver.js';
5
+ import { singleton } from '../../injection/index.js';
11
6
  import '../../controller/metadata/ControllerMetadataStore.js';
7
+ import { ChatRepository } from '../../core/chat/repository/IChatRepository.js';
8
+ import '../../core/user/IUserRepository.js';
9
+ import { Logger } from '../../logger/Logger.js';
10
+ import { WabotDevConnection } from '../wabot/WabotDevConnection.js';
11
+ import { devEmitEvent } from '../wabot/WabotDevSocketContracts.js';
12
12
  import { WhatsAppRepository } from './WhatsAppRepository.js';
13
13
 
14
14
  let WhatsAppSenderByDevConnection = class WhatsAppSenderByDevConnection extends WhatsAppSender {
@@ -52,10 +52,5 @@ WhatsAppSenderByDevConnection = __decorate([
52
52
  ChatResolver,
53
53
  WhatsAppRepository])
54
54
  ], WhatsAppSenderByDevConnection);
55
- if (WabotDevConnection.isTokenAvailable()) {
56
- container.register(WhatsAppSender, {
57
- useClass: WhatsAppSenderByDevConnection,
58
- });
59
- }
60
55
 
61
56
  export { WhatsAppSenderByDevConnection };
@@ -1,22 +1,32 @@
1
- class Persistent {
2
- data;
3
- constructor(data) {
4
- this.data = data;
5
- }
6
- getId() {
1
+ import { Storable } from './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;
@@ -33,5 +43,10 @@ class Persistent {
33
43
  this.data.discardedAt = new Date().getTime();
34
44
  }
35
45
  }
46
+ /**
47
+ * @deprecated Should use Entity
48
+ */
49
+ class PersistentData extends Entity {
50
+ }
36
51
 
37
- export { Persistent };
52
+ export { Entity, PersistentData };
@@ -0,0 +1,8 @@
1
+ class Storable {
2
+ data;
3
+ constructor(data) {
4
+ this.data = data;
5
+ }
6
+ }
7
+
8
+ export { Storable };
@@ -1,6 +1,6 @@
1
- import { Persistent } from '../Persistent.js';
1
+ import { Entity } from '../Entity.js';
2
2
 
3
- class Chat extends Persistent {
3
+ class Chat extends Entity {
4
4
  constructor(data) {
5
5
  super(data);
6
6
  }
@@ -1,6 +1,6 @@
1
- import { Persistent } from '../Persistent.js';
1
+ import { Entity } from '../Entity.js';
2
2
 
3
- class ChatItem extends Persistent {
3
+ class ChatItem extends Entity {
4
4
  getType() {
5
5
  return this.data.type;
6
6
  }
@@ -1,6 +1,6 @@
1
- import { Persistent } from '../Persistent.js';
1
+ import { Entity } from '../Entity.js';
2
2
 
3
- class User extends Persistent {
3
+ class User extends Entity {
4
4
  constructor(data) {
5
5
  super(data);
6
6
  }
@@ -2,6 +2,7 @@ class CustomError extends Error {
2
2
  humanMessage;
3
3
  code;
4
4
  httpCode;
5
+ info;
5
6
  constructor(data) {
6
7
  super(data.message, { cause: data.cause });
7
8
  this.humanMessage = data.humanMessage;
@@ -2,10 +2,10 @@ import InjectionToken from 'tsyringe/dist/typings/providers/injection-token';
2
2
  import DependencyContainer, { PreResolutionInterceptorCallback, PostResolutionInterceptorCallback } from 'tsyringe/dist/typings/types/dependency-container';
3
3
  import InterceptionOptions from 'tsyringe/dist/typings/types/interceptor-options';
4
4
  import { Server } from 'http';
5
- import { Express } from 'express';
5
+ import { Express, Request, Response } from 'express';
6
6
  import { Server as Server$1 } from 'socket.io';
7
- import { Socket } from 'socket.io-client';
8
7
  import { Pool } from 'pg';
8
+ import { Socket } from 'socket.io-client';
9
9
  import * as tsyringe from 'tsyringe';
10
10
  import { DependencyContainer as DependencyContainer$1 } from 'tsyringe';
11
11
  export { DependencyContainer } from 'tsyringe';
@@ -26,33 +26,58 @@ interface IMindsetFunctionDecoration {
26
26
  decorationConfig: any;
27
27
  }
28
28
 
29
- interface IPersistentData {
29
+ type IPrimitive = null | number | string | boolean | undefined;
30
+ type IStorableData = {
31
+ [key: string]: IPrimitive | IPrimitive[] | IStorableData | IStorableData[];
32
+ };
33
+ declare class Storable<D extends IStorableData> {
34
+ protected data: D;
35
+ constructor(data: D);
36
+ }
37
+
38
+ interface IEntityData extends IStorableData {
30
39
  id?: string;
31
40
  createdAt?: number | null;
32
41
  discardedAt?: number | null;
33
42
  }
34
- declare class Persistent<D extends IPersistentData = IPersistentData> {
35
- protected data: D;
36
- constructor(data: D);
43
+ declare class Entity<D extends IEntityData> extends Storable<D> {
44
+ get id(): string;
45
+ /**
46
+ * @deprecated use id
47
+ */
37
48
  getId(): string;
49
+ get createdAt(): Date;
50
+ /**
51
+ * @deprecated use createdAt
52
+ */
38
53
  getCreatedAt(): Date;
39
- update(newData: D): void;
54
+ update(newData: Omit<D, 'id' | 'createdAt' | 'discardedAt'>): void;
40
55
  wasCreated(): boolean;
41
56
  validate(): void;
42
57
  discard(): void;
43
58
  }
59
+ /**
60
+ * @deprecated Should use IEntityData
61
+ */
62
+ interface IPersistentData extends IEntityData {
63
+ }
64
+ /**
65
+ * @deprecated Should use Entity
66
+ */
67
+ declare class PersistentData<D extends IPersistentData> extends Entity<D> {
68
+ }
44
69
 
45
70
  type IChatType = 'PRIVATE' | 'GROUP';
46
- interface IChatConnection {
71
+ interface IChatConnection extends IStorableData {
47
72
  chatType: IChatType;
48
73
  channelName: string;
49
74
  id: string;
50
75
  }
51
- interface IChatData extends IPersistentData {
76
+ interface IChatData extends IEntityData {
52
77
  type: IChatType;
53
78
  connections: IChatConnection[];
54
79
  }
55
- declare class Chat extends Persistent<IChatData> {
80
+ declare class Chat extends Entity<IChatData> {
56
81
  constructor(data: IChatData);
57
82
  isPrivate(): boolean;
58
83
  isGroup(): boolean;
@@ -62,24 +87,24 @@ declare class Chat extends Persistent<IChatData> {
62
87
  validate(): void;
63
88
  }
64
89
 
65
- interface IChatDocument {
90
+ interface IChatDocument extends IStorableData {
66
91
  }
67
92
 
68
- interface IChatImage {
93
+ interface IChatImage extends IStorableData {
69
94
  }
70
95
 
71
- interface IUserConnection {
96
+ interface IUserConnection extends IStorableData {
72
97
  channelName: string;
73
98
  id: string;
74
99
  }
75
- interface IUserData extends IPersistentData {
100
+ interface IUserData extends IEntityData {
76
101
  shortName: string;
77
102
  connections: IUserConnection[];
78
103
  keyValueData: {
79
104
  [key: string]: string;
80
105
  };
81
106
  }
82
- declare class User extends Persistent<IUserData> {
107
+ declare class User extends Entity<IUserData> {
83
108
  constructor(data: IUserData);
84
109
  hasConnection(connection: IUserConnection): boolean;
85
110
  getValue(key: string): string;
@@ -87,7 +112,7 @@ declare class User extends Persistent<IUserData> {
87
112
  addConnection(connection: IUserConnection): void;
88
113
  }
89
114
 
90
- interface IChatMessage {
115
+ interface IChatMessage extends IStorableData {
91
116
  text?: string;
92
117
  documents?: IChatDocument[];
93
118
  images?: IChatImage[];
@@ -118,12 +143,9 @@ type ISystemFunctionCallItem = {
118
143
  type: 'FUNCTION_CALL';
119
144
  content: IChatFunctionCall;
120
145
  };
121
- type IChatItemData = {
122
- id?: string;
123
- createdAt?: number;
124
- } & (ISystemMessageItem | IReceivedMessageItem | ISystemFunctionCallItem);
146
+ type IChatItemData = IEntityData & (ISystemMessageItem | IReceivedMessageItem | ISystemFunctionCallItem);
125
147
  type IChatItemType = IChatItemData['type'];
126
- declare class ChatItem extends Persistent<IChatItemData> {
148
+ declare class ChatItem extends Entity<IChatItemData> {
127
149
  getType(): "BOT_MESSAGE" | "CONNECTION_MESSAGE" | "FUNCTION_CALL";
128
150
  getContent(): IChatMessage | IConnectionChatMessage | IChatFunctionCall;
129
151
  getData(): IChatItemData;
@@ -172,11 +194,6 @@ declare class MessageContext implements IMessageContext {
172
194
  constructor(message: IConnectionChatMessage, chat: Chat, user: User | null);
173
195
  }
174
196
 
175
- interface IReversibleMapper<T1, T2> {
176
- map(input: T1): T2;
177
- rev(input: T2): T1;
178
- }
179
-
180
197
  type IConstructor<T> = new (...args: any[]) => T;
181
198
 
182
199
  interface IMindsetIdentity {
@@ -532,6 +549,54 @@ declare class WhatsappChannelConfig implements IWhatsappChannelConfig {
532
549
 
533
550
  declare function whatsapp(config: IWhatsappChannelConfig): (target: object, propertyKey: string | symbol) => void;
534
551
 
552
+ interface IWhatsAppBusinessNumber extends IStorableData {
553
+ id: string;
554
+ number: string;
555
+ }
556
+ interface IWhatsAppBusinessAccount extends IStorableData {
557
+ id: string;
558
+ }
559
+ interface IWhatsAppData extends IEntityData {
560
+ slug: string;
561
+ verifyToken: string;
562
+ appSecret: string;
563
+ accessToken: string;
564
+ businessAccount: IWhatsAppBusinessAccount;
565
+ businessNumbers: IWhatsAppBusinessNumber[];
566
+ }
567
+ declare class WhatsApp extends Entity<IWhatsAppData> {
568
+ getVerifyToken(): string;
569
+ getSlug(): string;
570
+ getBusinessAccount(): IWhatsAppBusinessAccount;
571
+ getAppSecret(): string;
572
+ getBusinessNumbers(): IWhatsAppBusinessNumber[];
573
+ getAccessToken(): string;
574
+ hasBusinessNumber(number: string): boolean;
575
+ getBussinessNumber(number: string): IWhatsAppBusinessNumber | null;
576
+ }
577
+
578
+ interface IWhatsAppRepository {
579
+ findBySlug(slug: string): Promise<WhatsApp | null>;
580
+ findByBusinessNumber(number: string): Promise<WhatsApp | null>;
581
+ }
582
+
583
+ type IWabotEnvType = 'development' | 'staging' | 'testing' | 'production';
584
+ declare class WabotEnv {
585
+ private envType;
586
+ constructor();
587
+ isDevelopment(): boolean;
588
+ isProduction(): boolean;
589
+ requireString(varName: string): string;
590
+ }
591
+
592
+ declare class EnvWhatsAppRepository implements IWhatsAppRepository {
593
+ private env;
594
+ constructor(env: WabotEnv);
595
+ findBySlug(slug: string): Promise<WhatsApp | null>;
596
+ findByBusinessNumber(number: string): Promise<WhatsApp | null>;
597
+ private getFromEnvVars;
598
+ }
599
+
535
600
  type IWhatsAppTemplateParameter = {
536
601
  type: 'text';
537
602
  text: string;
@@ -555,6 +620,32 @@ interface IWhatsAppTemplateMessage {
555
620
  parameters: IWhatsAppTemplateParameter[];
556
621
  }
557
622
 
623
+ interface IWhatsAppTemplateResponse {
624
+ data: IWhatsAppTemplate[];
625
+ paging: IWhatsAppApiPaging;
626
+ }
627
+ interface IWhatsAppTemplate {
628
+ name: string;
629
+ parameter_format: 'POSITIONAL' | 'OTHER';
630
+ components: IWhatsAppTemplateComponent[];
631
+ language: string;
632
+ status: string;
633
+ category: string;
634
+ id: string;
635
+ }
636
+ interface IWhatsAppTemplateComponent {
637
+ type: 'HEADER' | 'BODY' | 'FOOTER';
638
+ format?: 'TEXT';
639
+ text?: string;
640
+ }
641
+ interface IWhatsAppApiPaging {
642
+ cursors: IWhatsAppApiCursors;
643
+ }
644
+ interface IWhatsAppApiCursors {
645
+ before: string;
646
+ after: string;
647
+ }
648
+
558
649
  interface IWhatsAppWebhookPayload {
559
650
  object: 'whatsapp_business_account';
560
651
  entry: IEntry[];
@@ -607,30 +698,70 @@ interface IAudioMessage extends IBaseMessage {
607
698
  };
608
699
  }
609
700
 
610
- interface IWhatsAppBusinessNumber {
611
- id: string;
612
- number: string;
701
+ interface ICrudRepository<T> {
702
+ find(id: string): Promise<T | null>;
703
+ findOrThrow(id: string): Promise<T>;
704
+ findAll(id: string): Promise<T[]>;
705
+ create(item: T): Promise<void>;
706
+ update(item: T): Promise<void>;
707
+ discard(item: T): Promise<void>;
613
708
  }
614
- interface IWhatsAppBusinessAccount {
615
- id: string;
709
+
710
+ type IPgRepositoryConfig<P extends Entity<IEntityData>> = {
711
+ schema?: string;
712
+ table: string;
713
+ constructor: IConstructor<P>;
714
+ add?: {
715
+ columns: {
716
+ [column: string]: {
717
+ type: string;
718
+ value: (item: P) => boolean | number | string | null | Date;
719
+ };
720
+ };
721
+ };
722
+ };
723
+
724
+ declare class PgRepositoryBase<P extends Entity<IEntityData>> {
725
+ protected pool: Pool;
726
+ protected config: IPgRepositoryConfig<any>;
727
+ private tableIsCreated;
728
+ protected schema: string;
729
+ protected table: string;
730
+ protected columnsList: string[];
731
+ protected columnsAndTypes: string;
732
+ protected columns: string;
733
+ protected vars: string;
734
+ protected updates: string;
735
+ addColumns: {
736
+ [columns: string]: {
737
+ type: string;
738
+ value: (item: P) => number | boolean | string | null | Date;
739
+ };
740
+ };
741
+ constructor(pool: Pool, config: IPgRepositoryConfig<any>);
742
+ protected values(item: P): (string | number | boolean | Date | null)[];
743
+ protected exec(sql: string, values: any[]): Promise<void>;
744
+ protected query(sql: string, values: any[]): Promise<any[]>;
745
+ protected connect(): Promise<Pool>;
746
+ protected ensureTable(): Promise<void>;
747
+ protected ensureColumns(): Promise<void>;
616
748
  }
617
- interface IWhatsAppData extends IPersistentData {
618
- slug: string;
619
- verifyToken: string;
620
- appSecret: string;
621
- accessToken: string;
622
- businessAccount: IWhatsAppBusinessAccount;
623
- businessNumbers: IWhatsAppBusinessNumber[];
749
+
750
+ declare class PgCrudRepository<P extends Entity<IEntityData>> extends PgRepositoryBase<P> implements ICrudRepository<P> {
751
+ protected readonly config: IPgRepositoryConfig<P>;
752
+ constructor(pool: Pool, config: IPgRepositoryConfig<P>);
753
+ find(id: string): Promise<P | null>;
754
+ findOrThrow(id: string): Promise<P>;
755
+ findAll(): Promise<P[]>;
756
+ create(item: P): Promise<void>;
757
+ update(item: P): Promise<void>;
758
+ discard(item: P): Promise<void>;
624
759
  }
625
- declare class WhatsApp extends Persistent<IWhatsAppData> {
626
- getVerifyToken(): string;
627
- getSlug(): string;
628
- getBusinessAccount(): IWhatsAppBusinessAccount;
629
- getAppSecret(): string;
630
- getBusinessNumbers(): IWhatsAppBusinessNumber[];
631
- getAccessToken(): string;
632
- hasBusinessNumber(number: string): boolean;
633
- getBussinessNumber(number: string): IWhatsAppBusinessNumber | null;
760
+
761
+ declare class PgWhatsAppRepository extends PgCrudRepository<WhatsApp> implements IWhatsAppRepository {
762
+ constructor(pool: Pool);
763
+ findBySlug(slug: string): Promise<WhatsApp | null>;
764
+ findByBusinessNumber(number: string): Promise<WhatsApp | null>;
634
765
  }
635
766
 
636
767
  declare class Logger {
@@ -660,31 +791,11 @@ declare abstract class WhatsAppReceiver {
660
791
  private emmitMessage;
661
792
  }
662
793
 
663
- interface IWhatsAppRepository {
664
- findBySlug(slug: string): Promise<WhatsApp | null>;
665
- findByBusinessNumber(number: string): Promise<WhatsApp | null>;
666
- }
667
-
668
794
  declare class WhatsAppRepository implements IWhatsAppRepository {
669
795
  findBySlug(slug: string): Promise<WhatsApp | null>;
670
796
  findByBusinessNumber(number: string): Promise<WhatsApp | null>;
671
797
  }
672
798
 
673
- interface IWhatsAppTemplate {
674
- name: string;
675
- parameter_format: 'POSITIONAL' | 'OTHER';
676
- components: IWhatsAppTemplateComponent[];
677
- language: string;
678
- status: string;
679
- category: string;
680
- id: string;
681
- }
682
- interface IWhatsAppTemplateComponent {
683
- type: 'HEADER' | 'BODY' | 'FOOTER';
684
- format?: 'TEXT';
685
- text?: string;
686
- }
687
-
688
799
  interface ISendWhatsAppRequest {
689
800
  from: string;
690
801
  to: string;
@@ -704,15 +815,15 @@ interface IGetWhatsAppTemplateRequest {
704
815
  interface IWhatsAppSenderOptions {
705
816
  writeChatMemory?: boolean;
706
817
  }
707
- declare abstract class WhatsAppSender {
818
+ declare class WhatsAppSender {
708
819
  protected logger: Logger;
709
820
  protected chatRepository: ChatRepository;
710
821
  protected chatResolver: ChatResolver;
711
822
  protected whatsAppRepository: WhatsAppRepository;
712
823
  constructor(logger: Logger, chatRepository: ChatRepository, chatResolver: ChatResolver, whatsAppRepository: WhatsAppRepository);
713
- protected abstract handleSendRequest(request: ISendWhatsAppRequest): Promise<void>;
714
- protected abstract handleSendTemplateRequest(request: ISendWhatsAppTemplateRequest): Promise<void>;
715
- protected abstract handleGetWhatsAppTemplate(request: IGetWhatsAppTemplateRequest): Promise<IWhatsAppTemplate | null>;
824
+ protected handleSendRequest(request: ISendWhatsAppRequest): Promise<void>;
825
+ protected handleSendTemplateRequest(request: ISendWhatsAppTemplateRequest): Promise<void>;
826
+ protected handleGetWhatsAppTemplate(request: IGetWhatsAppTemplateRequest): Promise<IWhatsAppTemplate | null>;
716
827
  sendWhatsApp(request: ISendWhatsAppRequest, options?: IWhatsAppSenderOptions): Promise<void>;
717
828
  sendWhatsAppTemplate(request: ISendWhatsAppTemplateRequest, options?: IWhatsAppSenderOptions): Promise<void>;
718
829
  getWhatsAppTemplate(request: IGetWhatsAppTemplateRequest): Promise<IWhatsAppTemplate | null>;
@@ -758,126 +869,37 @@ declare class WhatsAppReceiverByWebHook extends WhatsAppReceiver {
758
869
  connect(): Promise<void>;
759
870
  }
760
871
 
761
- declare class WhatsAppSenderByDevConnection extends WhatsAppSender {
762
- private wabotDevConnection;
763
- constructor(wabotDevConnection: WabotDevConnection, chatRepository: ChatRepository, chatResolver: ChatResolver, whatsAppRepository: WhatsAppRepository);
872
+ declare class WhatsAppSenderByCloudApi extends WhatsAppSender {
873
+ constructor(chatRepository: ChatRepository, chatResolver: ChatResolver, whatsAppRepository: WhatsAppRepository);
764
874
  handleSendRequest(request: ISendWhatsAppRequest): Promise<void>;
765
875
  handleSendTemplateRequest(request: ISendWhatsAppTemplateRequest): Promise<void>;
766
876
  handleGetWhatsAppTemplate(request: IGetWhatsAppTemplateRequest): Promise<IWhatsAppTemplate | null>;
767
877
  }
768
878
 
769
- declare class WhatsAppSenderByCloudApi extends WhatsAppSender {
770
- constructor(chatRepository: ChatRepository, chatResolver: ChatResolver, whatsAppRepository: WhatsAppRepository);
879
+ declare class WhatsAppSenderByDevConnection extends WhatsAppSender {
880
+ private wabotDevConnection;
881
+ constructor(wabotDevConnection: WabotDevConnection, chatRepository: ChatRepository, chatResolver: ChatResolver, whatsAppRepository: WhatsAppRepository);
771
882
  handleSendRequest(request: ISendWhatsAppRequest): Promise<void>;
772
883
  handleSendTemplateRequest(request: ISendWhatsAppTemplateRequest): Promise<void>;
773
884
  handleGetWhatsAppTemplate(request: IGetWhatsAppTemplateRequest): Promise<IWhatsAppTemplate | null>;
774
885
  }
775
886
 
776
- interface ICrudRepository<T> {
777
- find(id: string): Promise<T | null>;
778
- findOrThrow(id: string): Promise<T>;
779
- findAll(id: string): Promise<T[]>;
780
- create(item: T): Promise<void>;
781
- update(item: T): Promise<void>;
782
- discard(item: T): Promise<void>;
783
- }
784
-
785
- type IPgRepositoryConfig<P extends Persistent> = {
786
- schema?: string;
787
- table: string;
788
- constructor: IConstructor<P>;
789
- add?: {
790
- columns: {
791
- [column: string]: {
792
- type: string;
793
- value: (item: P) => boolean | number | string | null | Date;
794
- };
795
- };
796
- };
797
- };
798
-
799
- declare class PgRepositoryBase<P extends Persistent> {
800
- protected pool: Pool;
801
- protected config: IPgRepositoryConfig<any>;
802
- private tableIsCreated;
803
- schema: string;
804
- table: string;
805
- columnsList: string[];
806
- columnsAndTypes: string;
807
- columns: string;
808
- vars: string;
809
- updates: string;
810
- addColumns: {
811
- [columns: string]: {
812
- type: string;
813
- value: (item: P) => number | boolean | string | null | Date;
814
- };
815
- };
816
- constructor(pool: Pool, config: IPgRepositoryConfig<any>);
817
- values(item: P): (string | number | boolean | Date | null)[];
818
- protected exec(sql: string, values: any[]): Promise<void>;
819
- protected query(sql: string, values: any[]): Promise<any[]>;
820
- protected connect(): Promise<Pool>;
821
- protected ensureTable(): Promise<void>;
822
- protected ensureColumns(): Promise<void>;
887
+ interface ICustomErrorData {
888
+ message: string;
889
+ humanMessage?: string;
890
+ code?: string;
891
+ httpCode?: number;
892
+ cause?: Error;
893
+ info?: any;
823
894
  }
824
-
825
- declare class PgCrudRepository<P extends Persistent> extends PgRepositoryBase<P> implements ICrudRepository<P> {
826
- protected readonly config: IPgRepositoryConfig<P>;
827
- constructor(pool: Pool, config: IPgRepositoryConfig<P>);
828
- find(id: string): Promise<P | null>;
829
- findOrThrow(id: string): Promise<P>;
830
- findAll(): Promise<P[]>;
831
- create(item: P): Promise<void>;
832
- update(item: P): Promise<void>;
833
- discard(item: P): Promise<void>;
895
+ declare class CustomError extends Error {
896
+ humanMessage?: string;
897
+ code?: string;
898
+ httpCode?: number;
899
+ info?: any;
900
+ constructor(data: ICustomErrorData);
834
901
  }
835
902
 
836
- declare class PgWhatsAppRepository extends PgCrudRepository<WhatsApp> implements IWhatsAppRepository {
837
- constructor(pool: Pool);
838
- findBySlug(slug: string): Promise<WhatsApp | null>;
839
- findByBusinessNumber(number: string): Promise<WhatsApp | null>;
840
- }
841
-
842
- type IWabotEnvType = 'development' | 'staging' | 'testing' | 'production';
843
- declare class WabotEnv {
844
- private envType;
845
- constructor();
846
- isDevelopment(): boolean;
847
- isProduction(): boolean;
848
- requireString(varName: string): string;
849
- }
850
-
851
- declare class EnvWhatsAppRepository implements IWhatsAppRepository {
852
- private env;
853
- constructor(env: WabotEnv);
854
- findBySlug(slug: string): Promise<WhatsApp | null>;
855
- findByBusinessNumber(number: string): Promise<WhatsApp | null>;
856
- private getFromEnvVars;
857
- }
858
-
859
- declare function prepareChatContainer(container: DependencyContainer$1, context: IMessageContext, mindsetCtor?: IConstructor<IMindset>): Promise<DependencyContainer$1>;
860
-
861
- interface IrunChannelProps {
862
- channel: IConstructor<IChatChannel>;
863
- channelConfig?: object;
864
- mindset: IConstructor<IMindset>;
865
- chatRepository: IConstructor<IChatRepository>;
866
- chatBotAdapter: IConstructor<IChatBotAdapter>;
867
- }
868
- declare function runChannel(props: IrunChannelProps): void;
869
-
870
- interface IServerProvider<T, ST extends T> {
871
- replace: IConstructor<T>;
872
- with: IConstructor<ST>;
873
- singleton?: true;
874
- }
875
- interface IServerConfig {
876
- controllers: IConstructor<any>[];
877
- providers?: IServerProvider<unknown, unknown>[];
878
- }
879
- declare function runServer(config: IServerConfig): void;
880
-
881
903
  declare class SendOneTimePasswordRequest {
882
904
  fromEmail: string;
883
905
  toEmail: string;
@@ -986,6 +1008,12 @@ interface IGetConfig {
986
1008
 
987
1009
  declare function get(config?: IGetConfig): (target: object, propertyKey: string | symbol) => void;
988
1010
 
1011
+ interface IMiddleware {
1012
+ handle(req: Request, res: Response, container: DependencyContainer$1): Promise<void>;
1013
+ }
1014
+
1015
+ declare function middleware(middlewareConstructor: IConstructor<IMiddleware>): (target: object, propertyKey: string | symbol) => void;
1016
+
989
1017
  interface IPostConfig {
990
1018
  path?: string;
991
1019
  }
@@ -1006,6 +1034,12 @@ interface IEndPointMetadata {
1006
1034
  paramsTypes: any[];
1007
1035
  }
1008
1036
 
1037
+ interface IMiddlewareMetadata {
1038
+ controllerConstructor: IConstructor<any>;
1039
+ functionName: string;
1040
+ middlewareConstructor: IConstructor<IMiddleware>;
1041
+ }
1042
+
1009
1043
  interface IRestControllerMetadata {
1010
1044
  controllerConstructor: IConstructor<any>;
1011
1045
  path: string;
@@ -1013,10 +1047,13 @@ interface IRestControllerMetadata {
1013
1047
 
1014
1048
  declare class RestControllerMetadataStore {
1015
1049
  private endPoints;
1050
+ private middlewares;
1016
1051
  private restControllers;
1017
1052
  saveControllerMetadata(controllerMetadata: IRestControllerMetadata): void;
1018
1053
  saveEndPointMetadata(endPointMetadata: IEndPointMetadata): void;
1054
+ saveMiddlewareMetadata(middlewareMetadata: IMiddlewareMetadata): void;
1019
1055
  getControllerEndPointsInfo(controllerConstructor: IConstructor<any>): {
1056
+ middlewares: IMiddlewareMetadata[];
1020
1057
  controller: IRestControllerMetadata;
1021
1058
  method: "get" | "post";
1022
1059
  path?: string;
@@ -1028,10 +1065,34 @@ declare class RestControllerMetadataStore {
1028
1065
 
1029
1066
  declare function runRestControllers(controllers: IConstructor<any>[], container: DependencyContainer$1): void;
1030
1067
 
1068
+ declare function prepareChatContainer(container: DependencyContainer$1, context: IMessageContext, mindsetCtor?: IConstructor<IMindset>): Promise<DependencyContainer$1>;
1069
+
1070
+ interface IrunChannelProps {
1071
+ channel: IConstructor<IChatChannel>;
1072
+ channelConfig?: object;
1073
+ mindset: IConstructor<IMindset>;
1074
+ chatRepository: IConstructor<IChatRepository>;
1075
+ chatBotAdapter: IConstructor<IChatBotAdapter>;
1076
+ }
1077
+ declare function runChannel(props: IrunChannelProps): void;
1078
+
1079
+ interface IServerProvider<T, ST extends T> {
1080
+ replace: IConstructor<T>;
1081
+ with: IConstructor<ST>;
1082
+ singleton?: true;
1083
+ }
1084
+ interface IServerConfig {
1085
+ controllers: IConstructor<any>[];
1086
+ providers?: IServerProvider<unknown, unknown>[];
1087
+ }
1088
+ declare function runServer(config: IServerConfig): void;
1089
+
1031
1090
  declare function isBoolean(): (target: object, propertyKey: string | symbol) => void;
1032
1091
 
1033
1092
  declare function isDate(): (target: object, propertyKey: string | symbol) => void;
1034
1093
 
1094
+ declare function isModel(model: IConstructor<any>): (target: object, propertyKey: string | symbol) => void;
1095
+
1035
1096
  declare function isNotEmpty(): (target: object, propertyKey: string | symbol) => void;
1036
1097
 
1037
1098
  declare function isNumber(): (target: object, propertyKey: string | symbol) => void;
@@ -1049,8 +1110,7 @@ declare function min(limit: any): (target: object, propertyKey: string | symbol)
1049
1110
  interface IValidationError {
1050
1111
  description: string;
1051
1112
  }
1052
- interface IModelValidationError {
1053
- model: IValidationError[];
1113
+ interface IModelValidationError extends IValidationError {
1054
1114
  properties: {
1055
1115
  name: string;
1056
1116
  errors: IValidationError[];
@@ -1119,4 +1179,4 @@ declare function validateModel<V>(value: any, info: IModelValidatorsInfo<V>): IM
1119
1179
 
1120
1180
  declare function validate<V>(value: any, modelConstructor: IConstructor<V>): IModelValidationResult<V>;
1121
1181
 
1122
- export { AuthenticationModule, Chat, ChatBot, ChatBotAdapter, ChatBotMetadataStore, ChatItem, ChatMemory, ChatRepository, ChatResolver, CmdChannel, Container, ControllerMetadataStore, DeepSeekChatBotAdapter, EmailService, EnvWhatsAppRepository, ExpressProvider, HtmlModule, HttpServerProvider, type IChannelMetadata, type IChatBot, type IChatBotAdapter, type IChatBotMetadata, type IChatChannel, type IChatConnection, type IChatControllerMetadata, type IChatData, type IChatFunctionCall, type IChatItemData, type IChatItemType, type IChatMemory, type IChatMessage, type IChatRepository, type IChatType, type IConnectionChatMessage, type IConstructor, type ICrudRepository, type IEmailService, type IEndPointMetadata, type IGetConfig, type IGetWhatsAppTemplateRequest, type IHtmlModuleOptions, type IListenWhatsAppMessageRequest, type IMessageContext, type IMessageMetadata, type IMindset, type IMindsetDecoration, type IMindsetFunctionConfig, type IMindsetFunctionDecoration, type IMindsetFunctionMetadata, type IMindsetFunctionParamMetadata, type IMindsetIdentity, type IMindsetMetadata, type IMindsetModuleConfig, type IMindsetModuleDecoration, type IMindsetModuleMetadata, type IModelValidationError, type IModelValidationResult, type IModelValidatorsInfo, type IOtpService, type IParamConfig, type IParamDecoration, type IPersistentData, type IPgRepositoryConfig, type IPostConfig, type IPropertyValidatorInfo, type IReceivedMessage, type IReceivedMessageItem, type IRestControllerConfig, type IRestControllerMetadata, type IReversibleMapper, type ISendEmailRequest, type ISendWhatsAppRequest, type ISendWhatsAppTemplateRequest, type IServerConfig, type IServerProvider, type ISocketChannelConfig, type ISocketChannelReceivedMessage, type ISystemFunctionCallItem, type ISystemMessageItem, type ITelegramChannelConfig, type IUserConnection, type IUserData, type IUserRepository, type IValidateMaxOptions, type IValidateMinOptions, type IValidationError, type IValidationResult, type IValidator, type IValidatorMetadata, type IWabotEnvType, type IWhatsAppBusinessAccount, type IWhatsAppBusinessNumber, type IWhatsAppContact, type IWhatsAppData, type IWhatsAppMessage, type IWhatsAppMessageListener, type IWhatsAppRepository, type IWhatsAppSenderOptions, type IWhatsAppTemplateMessage, type IWhatsAppTemplateParameter, type IWhatsAppWebhookPayload, type IWhatsappChannelConfig, type IchatControllerConfig, type IrunChannelProps, Logger, MINDSET_DECORATION_MINDSET, MINDSET_FUNCTION_DECORATION_FUNCTION, MINDSET_MODULE_DECORATION_MODULE, MessageContext, Mindset, MindsetMetadataStore, MindsetOperator, OpenaiChatBotAdapter, OtpService, PARAM_DECORATION_IS_OPTIONAL, PARAM_DECORATION_PARAM, Persistent, PgChatMemory, PgChatRepository, PgCrudRepository, PgRepositoryBase, PgUserRepository, PgWhatsAppRepository, RamChatMemory, RamChatRepository, RamUserRepository, RegisterUserModule, RegisterUserWithEmailRequest, RestControllerMetadataStore, SendOneTimePasswordRequest, SocketChannel, SocketChannelConfig, SocketServerProvider, TelegramChannel, TelegramChannelConfig, User, UserRepository, UserResolver, ValidateOneTimePasswordRequest, ValidationMetadataStore, WabotEnv, WhatsApp, WhatsAppChannel, WhatsAppReceiver, WhatsAppReceiverByDevConnection, WhatsAppReceiverByWebHook, WhatsAppRepository, WhatsAppSender, WhatsAppSenderByCloudApi, WhatsAppSenderByDevConnection, WhatsappChannelConfig, chatBot, chatController, cmd, container, get, inject, injectable, isBoolean, isDate, isNotEmpty, isNumber, isOptional, isPresent, isString, max, min, mindset, mindsetFunction, mindsetModule, param, post, prepareChatContainer, restController, runChannel, runRestControllers, runServer, singleton, socket, telegram, validate, validateIsBoolean, validateIsDate, validateIsNotEmpty, validateIsNumber, validateIsPresent, validateIsString, validateMax, validateMin, validateModel, whatsapp };
1182
+ export { AuthenticationModule, Chat, ChatBot, ChatBotAdapter, ChatBotMetadataStore, ChatItem, ChatMemory, ChatRepository, ChatResolver, CmdChannel, Container, ControllerMetadataStore, CustomError, DeepSeekChatBotAdapter, EmailService, Entity, EnvWhatsAppRepository, ExpressProvider, HtmlModule, HttpServerProvider, type IChannelMetadata, type IChatBot, type IChatBotAdapter, type IChatBotMetadata, type IChatChannel, type IChatConnection, type IChatControllerMetadata, type IChatData, type IChatFunctionCall, type IChatItemData, type IChatItemType, type IChatMemory, type IChatMessage, type IChatRepository, type IChatType, type IConnectionChatMessage, type IConstructor, type ICrudRepository, type ICustomErrorData, type IEmailService, type IEndPointMetadata, type IEntityData, type IGetConfig, type IGetWhatsAppTemplateRequest, type IHtmlModuleOptions, type IListenWhatsAppMessageRequest, type IMessageContext, type IMessageMetadata, type IMiddlewareMetadata, type IMindset, type IMindsetDecoration, type IMindsetFunctionConfig, type IMindsetFunctionDecoration, type IMindsetFunctionMetadata, type IMindsetFunctionParamMetadata, type IMindsetIdentity, type IMindsetMetadata, type IMindsetModuleConfig, type IMindsetModuleDecoration, type IMindsetModuleMetadata, type IModelValidationError, type IModelValidationResult, type IModelValidatorsInfo, type IOtpService, type IParamConfig, type IParamDecoration, type IPersistentData, type IPgRepositoryConfig, type IPostConfig, type IPropertyValidatorInfo, type IReceivedMessage, type IReceivedMessageItem, type IRestControllerConfig, type IRestControllerMetadata, type ISendEmailRequest, type ISendWhatsAppRequest, type ISendWhatsAppTemplateRequest, type IServerConfig, type IServerProvider, type ISocketChannelConfig, type ISocketChannelReceivedMessage, type ISystemFunctionCallItem, type ISystemMessageItem, type ITelegramChannelConfig, type IUserConnection, type IUserData, type IUserRepository, type IValidateMaxOptions, type IValidateMinOptions, type IValidationError, type IValidationResult, type IValidator, type IValidatorMetadata, type IWabotEnvType, type IWhatsAppBusinessAccount, type IWhatsAppBusinessNumber, type IWhatsAppContact, type IWhatsAppData, type IWhatsAppMessage, type IWhatsAppMessageListener, type IWhatsAppRepository, type IWhatsAppSenderOptions, type IWhatsAppTemplate, type IWhatsAppTemplateComponent, type IWhatsAppTemplateMessage, type IWhatsAppTemplateParameter, type IWhatsAppTemplateResponse, type IWhatsAppWebhookPayload, type IWhatsappChannelConfig, type IchatControllerConfig, type IrunChannelProps, Logger, MINDSET_DECORATION_MINDSET, MINDSET_FUNCTION_DECORATION_FUNCTION, MINDSET_MODULE_DECORATION_MODULE, MessageContext, Mindset, MindsetMetadataStore, MindsetOperator, OpenaiChatBotAdapter, OtpService, PARAM_DECORATION_IS_OPTIONAL, PARAM_DECORATION_PARAM, PersistentData, PgChatMemory, PgChatRepository, PgCrudRepository, PgRepositoryBase, PgUserRepository, PgWhatsAppRepository, RamChatMemory, RamChatRepository, RamUserRepository, RegisterUserModule, RegisterUserWithEmailRequest, RestControllerMetadataStore, SendOneTimePasswordRequest, SocketChannel, SocketChannelConfig, SocketServerProvider, TelegramChannel, TelegramChannelConfig, User, UserRepository, UserResolver, ValidateOneTimePasswordRequest, ValidationMetadataStore, WabotEnv, WhatsApp, WhatsAppChannel, WhatsAppReceiver, WhatsAppReceiverByDevConnection, WhatsAppReceiverByWebHook, WhatsAppRepository, WhatsAppSender, WhatsAppSenderByCloudApi, WhatsAppSenderByDevConnection, WhatsappChannelConfig, chatBot, chatController, cmd, container, get, inject, injectable, isBoolean, isDate, isModel, isNotEmpty, isNumber, isOptional, isPresent, isString, max, middleware, min, mindset, mindsetFunction, mindsetModule, param, post, prepareChatContainer, restController, runChannel, runRestControllers, runServer, singleton, socket, telegram, validate, validateIsBoolean, validateIsDate, validateIsNotEmpty, validateIsNumber, validateIsPresent, validateIsString, validateMax, validateMin, validateModel, whatsapp };
package/dist/src/index.js CHANGED
@@ -12,6 +12,8 @@ export { telegram } from './channels/telegram/@telegram.js';
12
12
  export { TelegramChannelConfig } from './channels/telegram/TelegramChannelConfig.js';
13
13
  export { TelegramChannel } from './channels/telegram/TelegramChannel.js';
14
14
  export { whatsapp } from './channels/whatsapp/@whatsapp.js';
15
+ export { EnvWhatsAppRepository } from './channels/whatsapp/EnvWhatsAppRepository.js';
16
+ export { PgWhatsAppRepository } from './channels/whatsapp/PgWhatsAppRepository.js';
15
17
  export { WhatsApp } from './channels/whatsapp/WhatsApp.js';
16
18
  export { WhatsAppChannel } from './channels/whatsapp/WhatsAppChannel.js';
17
19
  export { WhatsappChannelConfig } from './channels/whatsapp/WhatsAppChannelConfig.js';
@@ -20,10 +22,8 @@ export { WhatsAppReceiverByDevConnection } from './channels/whatsapp/WhatsAppRec
20
22
  export { WhatsAppReceiverByWebHook } from './channels/whatsapp/WhatsAppReceiverByWebHook.js';
21
23
  export { WhatsAppRepository } from './channels/whatsapp/WhatsAppRepository.js';
22
24
  export { WhatsAppSender } from './channels/whatsapp/WhatsAppSender.js';
23
- export { WhatsAppSenderByDevConnection } from './channels/whatsapp/WhatsAppSenderByDevConnection.js';
24
25
  export { WhatsAppSenderByCloudApi } from './channels/whatsapp/WhatsAppSenderByCloudApi.js';
25
- export { PgWhatsAppRepository } from './channels/whatsapp/PgWhatsAppRepository.js';
26
- export { EnvWhatsAppRepository } from './channels/whatsapp/EnvWhatsAppRepository.js';
26
+ export { WhatsAppSenderByDevConnection } from './channels/whatsapp/WhatsAppSenderByDevConnection.js';
27
27
  export { chatBot } from './chatbot/metadata/@chatBot.js';
28
28
  export { ChatBotMetadataStore } from './chatbot/metadata/ChatBotMetadataStore.js';
29
29
  export { ChatBot } from './chatbot/ChatBot.js';
@@ -39,8 +39,11 @@ export { ChatItem } from './core/chat/ChatItem.js';
39
39
  export { User } from './core/user/User.js';
40
40
  export { UserRepository } from './core/user/IUserRepository.js';
41
41
  export { MessageContext } from './core/IMessageContext.js';
42
- export { Persistent } from './core/Persistent.js';
42
+ export { Entity, PersistentData } from './core/Entity.js';
43
+ export { WabotEnv } from './env/WabotEnv.js';
44
+ export { CustomError } from './error/CustomError.js';
43
45
  export { container, inject, injectable, singleton } from './injection/index.js';
46
+ export { Logger } from './logger/Logger.js';
44
47
  export { mindsetFunction } from './mindset/metadata/functions/@mindsetFunction.js';
45
48
  export { MINDSET_FUNCTION_DECORATION_FUNCTION } from './mindset/metadata/functions/decoratorNames.js';
46
49
  export { mindset } from './mindset/metadata/mindsets/@mindset.js';
@@ -52,9 +55,6 @@ export { PARAM_DECORATION_IS_OPTIONAL, PARAM_DECORATION_PARAM } from './mindset/
52
55
  export { MindsetMetadataStore } from './mindset/metadata/MindsetMetadataStore.js';
53
56
  export { Mindset } from './mindset/IMindset.js';
54
57
  export { MindsetOperator } from './mindset/MindsetOperator.js';
55
- export { prepareChatContainer } from './server/prepareChatContainer.js';
56
- export { runChannel } from './server/runChannel.js';
57
- export { runServer } from './server/runServer.js';
58
58
  export { SendOneTimePasswordRequest } from './pre-made/module/authentication/requests/SendOneTimePasswordRequest.js';
59
59
  export { ValidateOneTimePasswordRequest } from './pre-made/module/authentication/requests/ValidateOneTimePasswordRequest.js';
60
60
  export { AuthenticationModule } from './pre-made/module/authentication/AuthenticationModule.js';
@@ -71,15 +71,18 @@ export { RamChatMemory } from './pre-made/repository/chat/ram/RamChatMemory.js';
71
71
  export { RamChatRepository } from './pre-made/repository/chat/ram/RamChatRepository.js';
72
72
  export { PgCrudRepository } from './repository/pg/PgCrudRepository.js';
73
73
  export { PgRepositoryBase } from './repository/pg/PgRepositoryBase.js';
74
- export { Logger } from './logger/Logger.js';
75
- export { WabotEnv } from './env/WabotEnv.js';
76
74
  export { get } from './rest-controller/metadata/@get.js';
75
+ export { middleware } from './rest-controller/metadata/@middleware.js';
77
76
  export { post } from './rest-controller/metadata/@post.js';
78
77
  export { restController } from './rest-controller/metadata/@restController.js';
79
78
  export { RestControllerMetadataStore } from './rest-controller/metadata/RestControllerMetadataStore.js';
80
79
  export { runRestControllers } from './rest-controller/runRestControllers.js';
80
+ export { prepareChatContainer } from './server/prepareChatContainer.js';
81
+ export { runChannel } from './server/runChannel.js';
82
+ export { runServer } from './server/runServer.js';
81
83
  export { isBoolean } from './validation/metadata/@isBoolean.js';
82
84
  export { isDate } from './validation/metadata/@isDate.js';
85
+ export { isModel } from './validation/metadata/@isModel.js';
83
86
  export { isNotEmpty } from './validation/metadata/@isNotEmpty.js';
84
87
  export { isNumber } from './validation/metadata/@isNumber.js';
85
88
  export { isOptional } from './validation/metadata/@isOptional.js';
@@ -16,7 +16,7 @@ let RamChatRepository = class RamChatRepository {
16
16
  this.items.push(chat);
17
17
  const memory = {
18
18
  memory: new RamChatMemory(),
19
- chatId: chat.getId(),
19
+ chatId: chat.id,
20
20
  };
21
21
  this.memories.push(memory);
22
22
  }
@@ -57,10 +57,10 @@ class PgCrudRepository extends PgRepositoryBase {
57
57
  SET ${this.updates}
58
58
  WHERE id = $${this.columnsList.length + 1}
59
59
  `;
60
- await this.exec(sql, [...this.values(item), item.getId()]);
60
+ await this.exec(sql, [...this.values(item), item.id]);
61
61
  }
62
62
  async discard(item) {
63
- const _item = await this.find(item.getId());
63
+ const _item = await this.find(item.id);
64
64
  if (!_item) {
65
65
  throw new Error('Not found');
66
66
  }
@@ -32,8 +32,8 @@ class PgRepositoryBase {
32
32
  }
33
33
  values(item) {
34
34
  return [
35
- item.getId(),
36
- item.getCreatedAt(),
35
+ item.id,
36
+ item.createdAt,
37
37
  JSON.stringify(item['data']),
38
38
  ...this.columnsList.slice(3).map((x) => this.addColumns[x].value(item)),
39
39
  ];
@@ -0,0 +1,16 @@
1
+ import { container } from '../../injection/index.js';
2
+ import { RestControllerMetadataStore } from './RestControllerMetadataStore.js';
3
+
4
+ function middleware(middlewareConstructor) {
5
+ return function (target, propertyKey) {
6
+ const functionName = propertyKey.toString();
7
+ const store = container.resolve(RestControllerMetadataStore);
8
+ store.saveMiddlewareMetadata({
9
+ controllerConstructor: target.constructor,
10
+ functionName,
11
+ middlewareConstructor: middlewareConstructor,
12
+ });
13
+ };
14
+ }
15
+
16
+ export { middleware };
@@ -3,6 +3,7 @@ import { singleton } from 'tsyringe';
3
3
 
4
4
  let RestControllerMetadataStore = class RestControllerMetadataStore {
5
5
  endPoints = new Map();
6
+ middlewares = new Map();
6
7
  restControllers = new Map();
7
8
  saveControllerMetadata(controllerMetadata) {
8
9
  this.restControllers.set(controllerMetadata.controllerConstructor, controllerMetadata);
@@ -14,6 +15,17 @@ let RestControllerMetadataStore = class RestControllerMetadataStore {
14
15
  }
15
16
  controllerEndPoints.set(endPointMetadata.functionName, endPointMetadata);
16
17
  }
18
+ saveMiddlewareMetadata(middlewareMetadata) {
19
+ let controllerMiddlewares = this.middlewares.get(middlewareMetadata.controllerConstructor);
20
+ if (!controllerMiddlewares) {
21
+ this.middlewares.set(middlewareMetadata.controllerConstructor, (controllerMiddlewares = new Map()));
22
+ }
23
+ let methodMiddlewares = controllerMiddlewares.get(middlewareMetadata.functionName);
24
+ if (!methodMiddlewares) {
25
+ controllerMiddlewares.set(middlewareMetadata.functionName, (methodMiddlewares = []));
26
+ }
27
+ methodMiddlewares.unshift(middlewareMetadata);
28
+ }
17
29
  getControllerEndPointsInfo(controllerConstructor) {
18
30
  const controller = this.restControllers.get(controllerConstructor);
19
31
  if (!controller) {
@@ -26,6 +38,7 @@ let RestControllerMetadataStore = class RestControllerMetadataStore {
26
38
  }
27
39
  return [...endPoints.values()].map((endPoint) => ({
28
40
  ...endPoint,
41
+ middlewares: this.middlewares.get(endPoint.controllerConstructor)?.get(endPoint.functionName) ?? [],
29
42
  controller: this.restControllers.get(endPoint.controllerConstructor),
30
43
  }));
31
44
  }
@@ -10,19 +10,20 @@ import '../channels/socket/SocketChannelConfig.js';
10
10
  import '../channels/socket/SocketServerProvider.js';
11
11
  import '../channels/telegram/TelegramChannel.js';
12
12
  import '../channels/whatsapp/WhatsAppChannel.js';
13
+ import '../channels/whatsapp/EnvWhatsAppRepository.js';
14
+ import '../channels/whatsapp/PgWhatsAppRepository.js';
13
15
  import '../core/chat/repository/IChatRepository.js';
14
16
  import '../core/user/IUserRepository.js';
15
17
  import '../channels/whatsapp/WhatsAppReceiverByDevConnection.js';
16
18
  import '../channels/whatsapp/WhatsAppReceiverByWebHook.js';
17
- import '../channels/whatsapp/WhatsAppSenderByDevConnection.js';
18
19
  import '../channels/whatsapp/WhatsAppSenderByCloudApi.js';
19
- import '../channels/whatsapp/PgWhatsAppRepository.js';
20
- import '../channels/whatsapp/EnvWhatsAppRepository.js';
20
+ import '../channels/whatsapp/WhatsAppSenderByDevConnection.js';
21
21
  import { Logger } from '../logger/Logger.js';
22
22
  import '../validation/metadata/ValidationMetadataStore.js';
23
23
  import { validate } from '../validation/validate.js';
24
24
  import path from 'path';
25
25
  import { RestControllerMetadataStore } from './metadata/RestControllerMetadataStore.js';
26
+ import { CustomError } from '../error/CustomError.js';
26
27
 
27
28
  function buildRequest(req) {
28
29
  return Object.assign({}, req.body, req.query, req.params);
@@ -40,42 +41,49 @@ function runRestControllers(controllers, container) {
40
41
  logger.info(`config ${endPoint.method.toUpperCase()} ${route}`);
41
42
  expressApp[method](route, async (req, res) => {
42
43
  const requestContainer = container.createChildContainer();
43
- const controllerInstance = requestContainer.resolve(endPoint.controllerConstructor);
44
- const endPointArgs = [];
45
- let defaultArgFound = false;
46
- for (let paramIndex = 0; paramIndex < endPoint.paramsTypes.length; paramIndex++) {
47
- const paramType = endPoint.paramsTypes[paramIndex];
48
- if (defaultArgFound) {
49
- throw new Error(`Cant determine de parameter ${paramIndex} value`);
44
+ try {
45
+ const middlewares = endPoint.middlewares.map((x) => requestContainer.resolve(x.middlewareConstructor));
46
+ for (const middleware of middlewares) {
47
+ await middleware.handle(req, res, requestContainer);
50
48
  }
51
- defaultArgFound = true;
52
- if (typeof paramType === 'function') {
53
- const { value, error } = validate(buildRequest(req), paramType);
54
- if (error) {
55
- res.status(400).json({ error });
56
- return;
49
+ const controllerInstance = requestContainer.resolve(endPoint.controllerConstructor);
50
+ const endPointArgs = [];
51
+ let defaultArgFound = false;
52
+ for (let paramIndex = 0; paramIndex < endPoint.paramsTypes.length; paramIndex++) {
53
+ const paramType = endPoint.paramsTypes[paramIndex];
54
+ if (defaultArgFound) {
55
+ throw new Error(`Cant determine de parameter ${paramIndex} value`);
56
+ }
57
+ defaultArgFound = true;
58
+ if (typeof paramType === 'function') {
59
+ const { value, error } = validate(buildRequest(req), paramType);
60
+ if (error) {
61
+ throw new CustomError({ httpCode: 400, message: error.description, info: error });
62
+ }
63
+ endPointArgs.push(value);
57
64
  }
58
- endPointArgs.push(value);
59
65
  }
60
- }
61
- try {
62
66
  const response = await controllerInstance[endPoint.functionName].apply(controllerInstance, endPointArgs);
63
67
  res.status(200).json(response);
64
68
  }
65
69
  catch (err) {
66
70
  if (err instanceof Error) {
67
71
  const keys = Object.keys(err).filter((key) => !['message', 'stack'].includes(key));
68
- const info = keys.reduce((acc, key) => {
72
+ const { httpCode, ...info } = keys.reduce((acc, key) => {
69
73
  acc[key] = err[key];
70
74
  return acc;
71
75
  }, {});
72
- res.status(500).json({ error: { message: err.message, stack: err.stack, ...info } });
76
+ res
77
+ .status(httpCode ?? 500)
78
+ .json({ error: { message: err.message, stack: err.stack, ...info } });
73
79
  }
74
80
  else {
75
81
  res.status(500).json({ error: { message: 'Unknown error' } });
76
82
  }
77
83
  }
78
- requestContainer.dispose();
84
+ finally {
85
+ requestContainer.dispose();
86
+ }
79
87
  });
80
88
  });
81
89
  });
@@ -19,9 +19,9 @@ async function prepareChatContainer(container, context, mindsetCtor) {
19
19
  useValue: new MessageContext(context.message, context.chat, context.user),
20
20
  });
21
21
  const chatRepository = container.resolve(ChatRepository);
22
- const chatMemory = await chatRepository.findMemory(context.chat.getId());
22
+ const chatMemory = await chatRepository.findMemory(context.chat.id);
23
23
  if (!chatMemory) {
24
- throw new Error('Not found Chat Memory for Chat with Id=' + context.chat.getId());
24
+ throw new Error('Not found Chat Memory for Chat with Id=' + context.chat.id);
25
25
  }
26
26
  chatContainer.register(ChatMemory, { useValue: chatMemory });
27
27
  const chatBotMetadataStore = container.resolve(ChatBotMetadataStore);
@@ -0,0 +1,18 @@
1
+ import { container } from '../../injection/index.js';
2
+ import { validateModel } from '../validators/validateModel.js';
3
+ import { ValidationMetadataStore } from './ValidationMetadataStore.js';
4
+
5
+ function isModel(model) {
6
+ return function (target, propertyKey) {
7
+ const propertyName = propertyKey.toString();
8
+ const store = container.resolve(ValidationMetadataStore);
9
+ store.saveValidatorMetadata({
10
+ modelConstructor: target.constructor,
11
+ propertyName,
12
+ validator: validateModel,
13
+ validatorOptions: store.getModelValidatorsInfo(model),
14
+ });
15
+ };
16
+ }
17
+
18
+ export { isModel };
@@ -2,11 +2,7 @@ function validateModel(value, info) {
2
2
  const result = {};
3
3
  if (typeof value !== 'object') {
4
4
  result.error = {
5
- model: [
6
- {
7
- description: `the value should be an object`,
8
- },
9
- ],
5
+ description: 'the value should be an object',
10
6
  properties: [],
11
7
  };
12
8
  return result;
@@ -26,7 +22,7 @@ function validateModel(value, info) {
26
22
  if (propertyValidatorResult.error) {
27
23
  let resultError = result.error;
28
24
  if (!resultError) {
29
- resultError = { model: [], properties: [] };
25
+ resultError = { description: `Error on properties`, properties: [] };
30
26
  result.error = resultError;
31
27
  }
32
28
  let propertyErrors = resultError.properties.find((x) => x.name === propertyName);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wabot-dev/framework",
3
- "version": "0.1.0-beta.11",
3
+ "version": "0.1.0-beta.12",
4
4
  "description": "Framework for IA Chat Bots",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",