@wabot-dev/framework 0.5.1 → 0.5.2

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.
@@ -46,6 +46,9 @@ class Entity extends Storable {
46
46
  throw new Error('createdAt is required');
47
47
  }
48
48
  }
49
+ lockerKey() {
50
+ return this.id;
51
+ }
49
52
  }
50
53
  /**
51
54
  * @deprecated Should use Entity
@@ -17,23 +17,47 @@ let Async = class Async {
17
17
  this.jobScheduler = jobScheduler;
18
18
  }
19
19
  async runCommand(ctor, data) {
20
+ const job = await this.scheduleCommand(ctor, data, new Date());
21
+ this.jobScheduler.tryExecuteNow(job);
22
+ return job;
23
+ }
24
+ async scheduleCommand(ctor, data, scheduledAt) {
20
25
  const commandName = this.metadataStore.getCommandName(ctor);
21
26
  if (!commandName) {
22
27
  throw new Error(`${ctor.name} is not registered as command`);
23
28
  }
24
29
  const { error, value: commandData } = validateAndTransform(data, ctor);
25
- if (!commandData) {
26
- throw new Error('Invalid command data');
30
+ if (error) {
31
+ throw new Error(`Validation failed: ${error.description}`);
27
32
  }
33
+ const scheduledDate = this.resolveScheduledDate(scheduledAt);
28
34
  const job = new Job({
29
35
  commandName,
30
36
  commandData,
31
- scheduledAt: new Date().getTime(),
37
+ scheduledAt: scheduledDate.getTime(),
32
38
  });
33
39
  await this.jobRepository.create(job);
34
- this.jobScheduler.tryExecuteNow(job);
35
40
  return job;
36
41
  }
42
+ resolveScheduledDate(scheduledAt) {
43
+ if (scheduledAt instanceof Date) {
44
+ return scheduledAt;
45
+ }
46
+ const now = new Date();
47
+ if ('seconds' in scheduledAt) {
48
+ return new Date(now.getTime() + scheduledAt.seconds * 1000);
49
+ }
50
+ if ('minutes' in scheduledAt) {
51
+ return new Date(now.getTime() + scheduledAt.minutes * 60 * 1000);
52
+ }
53
+ if ('hours' in scheduledAt) {
54
+ return new Date(now.getTime() + scheduledAt.hours * 60 * 60 * 1000);
55
+ }
56
+ if ('days' in scheduledAt) {
57
+ return new Date(now.getTime() + scheduledAt.days * 24 * 60 * 60 * 1000);
58
+ }
59
+ throw new Error('Invalid schedule delay format');
60
+ }
37
61
  };
38
62
  Async = __decorate([
39
63
  singleton(),
@@ -9,7 +9,7 @@ let PgLocker = class PgLocker {
9
9
  this.pool = pool;
10
10
  }
11
11
  withKey(key) {
12
- return new PgLockKey(key, this.pool);
12
+ return new PgLockKey(typeof key === 'object' ? key.lockerKey() : key, this.pool);
13
13
  }
14
14
  };
15
15
  PgLocker = __decorate([
@@ -30,6 +30,21 @@ declare class Auth<D> {
30
30
  wasOverrided(): boolean;
31
31
  }
32
32
 
33
+ interface ILockKey {
34
+ run<T>(fn: () => Promise<T>): Promise<T>;
35
+ tryRun<T>(fn: () => Promise<T>): Promise<T | undefined>;
36
+ }
37
+
38
+ interface ILockerKey {
39
+ lockerKey(): string | number;
40
+ }
41
+ interface ILocker {
42
+ withKey(key: string | number | ILockerKey): ILockKey;
43
+ }
44
+ declare class Locker implements ILocker {
45
+ withKey(key: string | number | ILockerKey): ILockKey;
46
+ }
47
+
33
48
  type IStorableData<O extends object> = {
34
49
  [K in keyof O]: IStorableType<O[K]>;
35
50
  };
@@ -44,7 +59,7 @@ interface IEntityData {
44
59
  createdAt?: number | null;
45
60
  discardedAt?: number | null;
46
61
  }
47
- declare class Entity<D extends IEntityData> extends Storable<D> {
62
+ declare class Entity<D extends IEntityData> extends Storable<D> implements ILockerKey {
48
63
  get id(): NonNullable<IStorableType<D["id"]>>;
49
64
  /**
50
65
  * @deprecated use id
@@ -58,6 +73,7 @@ declare class Entity<D extends IEntityData> extends Storable<D> {
58
73
  update(newData: Partial<Omit<D, 'id' | 'createdAt' | 'discardedAt'>>): void;
59
74
  wasCreated(): boolean;
60
75
  validate(): void;
76
+ lockerKey(): string | number;
61
77
  }
62
78
  /**
63
79
  * @deprecated Should use IEntityData
@@ -367,18 +383,6 @@ declare class DescriptionMetadataStore {
367
383
  getModelDescriptions(model: IConstructor<any>): IDescriptionMetadata[];
368
384
  }
369
385
 
370
- interface ILockKey {
371
- run<T>(fn: () => Promise<T>): Promise<T>;
372
- tryRun<T>(fn: () => Promise<T>): Promise<T | undefined>;
373
- }
374
-
375
- interface ILocker {
376
- withKey(key: string | number): ILockKey;
377
- }
378
- declare class Locker implements ILocker {
379
- withKey(key: string | number): ILockKey;
380
- }
381
-
382
386
  interface ICommandConfig {
383
387
  name: string;
384
388
  }
@@ -533,12 +537,24 @@ declare class JobScheduler {
533
537
  private tick;
534
538
  }
535
539
 
540
+ type IScheduleDelay = {
541
+ seconds: number;
542
+ } | {
543
+ minutes: number;
544
+ } | {
545
+ hours: number;
546
+ } | {
547
+ days: number;
548
+ };
549
+ type IScheduleAt = Date | IScheduleDelay;
536
550
  declare class Async {
537
551
  private jobRepository;
538
552
  private metadataStore;
539
553
  private jobScheduler;
540
554
  constructor(jobRepository: JobRepository, metadataStore: AsyncMetadataStore, jobScheduler: JobScheduler);
541
555
  runCommand<T>(ctor: IConstructor<T>, data: IValidateInputShape<T>): Promise<Job>;
556
+ scheduleCommand<T>(ctor: IConstructor<T>, data: IValidateInputShape<T>, scheduledAt: IScheduleAt): Promise<Job>;
557
+ private resolveScheduledDate;
542
558
  }
543
559
 
544
560
  interface ICronJobData extends IEntityData {
@@ -1071,7 +1087,7 @@ declare class PgCrudRepository<P extends Entity<IEntityData>> extends PgReposito
1071
1087
  declare class PgLocker implements ILocker {
1072
1088
  private readonly pool;
1073
1089
  constructor(pool: Pool);
1074
- withKey(key: string | number): ILockKey;
1090
+ withKey(key: string | number | ILockerKey): ILockKey;
1075
1091
  }
1076
1092
 
1077
1093
  declare class PgLockKey implements ILockKey {
@@ -1917,4 +1933,4 @@ declare function HtmlModule(options: IHtmlModuleOptions): {
1917
1933
  new (): {};
1918
1934
  };
1919
1935
 
1920
- export { AnthropicChatAdapter, ApiKey, ApiKeyGuardMiddleware, ApiKeyHandshakeGuardMiddleware, ApiKeyRepository, Async, AsyncMetadataStore, Auth, Chat, ChatAdapter, ChatBot, ChatBotMetadataStore, ChatItem, ChatMemory, ChatRepository, ChatResolver, type ClientMap, CmdChannel, Container, ControllerMetadataStore, CronJob, CronJobRepository, CustomError, DeepSeekChatAdapter, DescriptionMetadataStore, EXPRESS_REQ, EXPRESS_RES, Entity, Env, EnvWhatsAppRepository, type ErrorSeverity, ExpressProvider, GoogleChatAdapter, type GoogleChatAdapterV2Options, HtmlModule, HttpServerProvider, type IApiKeyData, type IApiKeyRepository, type IArrayValidationError, type IArrayValidationResult, type IBotMessageItem, type IChannelMessage, type IChannelMetadata, type IChatAdapter, type IChatAdapterNextItemsReq, type IChatAdapterNextItemsRes, type IChatAssociation, type IChatBot, type IChatBotMetadata, type IChatChannel, type IChatConnection, type IChatControllerMetadata, type IChatData, type IChatItem, type IChatItemData, type IChatItemType, type IChatMemory, type IChatMessage, type IChatRepository, type IChatType, type ICommandConfig, type ICommandHandler, type ICommandHandlerConfig, type IConstructor, type ICronConfig, type ICronJobData, type ICrudRepository, type ICustomErrorData, type IDescriptionMetadata, type IEndPointConfig, type IEndPointMetadata, type IEntityData, type IEnvType, type IErrorHandlersConfig, type IErrorMonitor, type IErrorMonitorContext, type IFunctionCall, type IFunctionCallItem, type IGenerateApiKeyReq, type IGenerateApiKeyRes, type IGetWhatsAppTemplateRequest, type IHandshakeMiddleware, type IHandshakeMiddlewareMetadata, type IHtmlModuleOptions, type IHumanMessageItem, type IJobData, type IJobRepository, type IJwtRefreshTokenData, type IJwtRefreshTokenRepository, type ILanguageModelUsage, type IListenWhatsAppMessageRequest, type ILockKey, type ILocker, type IMessageContext, type IMiddleware, type IMiddlewareMetadata, type IMindset, type IMindsetConfig, type IMindsetIdentity, type IMindsetLlm, type IMindsetMetadata, type IMindsetModuleConfig, type IMindsetModuleMetadata, type IMindsetTool, type IMindsetToolParameter, type IModelValidationError, type IModelValidationResult, type IModelValidatorsInfo, type IMoneyData, type IPersistentData, type IPgRepositoryConfig, type IPropertyValidatorInfo, type IReceivedMessage, type IRemoteApiKeyFetcher, type IRestControllerConfig, type IRestControllerMetadata, type ISendWhatsAppRequest, type ISendWhatsAppTemplateRequest, type ISocketChannelConfig, type ISocketChannelReceivedMessage, type ISocketControllerConfig, type ISocketControllerMetadata, type ISocketEventConfig, type ISocketEventMetadata, type IStorableData, type ITelegramChannelConfig, type IValidateArrayOptions, type IValidateArrayOptionsWithItemsValidators, type IValidateInputShape, type IValidateIsInOptions, type IValidateIsRecordOptions, type IValidateMaxOptions, type IValidateMinOptions, type IValidationError, type IValidationResult, type IValidator, type IValidatorMetadata, type IWhatsAppBusinessAccount, type IWhatsAppBusinessNumber, type IWhatsAppCloudContact, type IWhatsAppCloudMessage, type IWhatsAppCloudMessageMetadata, type IWhatsAppCloudTemplate, type IWhatsAppCloudTemplateComponent, type IWhatsAppCloudTemplateMessage, type IWhatsAppCloudTemplateParameter, type IWhatsAppCloudTemplateResponse, type IWhatsAppCloudWebhookPayload, type IWhatsAppData, type IWhatsAppMessageListener, type IWhatsAppProxyListenMessageEventData, type IWhatsAppProxyListenMessageEventReq, type IWhatsAppProxyMessage, type IWhatsAppProxyMessageContent, type IWhatsAppProxyMessageEventReq, type IWhatsAppProxySendMessageEventReq, type IWhatsAppRepository, type IWhatsAppSenderOptions, type IWhatsappChannelConfig, type IchatControllerConfig, Job, JobRepository, JobRunner, Jwt, JwtAccessAndRefreshTokenDto, JwtConfig, JwtGuardMiddleware, JwtHandshakeGuardMiddleware, JwtRefreshToken, JwtRefreshTokenRepository, JwtSigner, JwtTokenDto, Lifecycle, Locker, Logger, Mapper, Mindset, MindsetMetadataStore, MindsetOperator, Money, MoneyDto, OpenaiChatAdapter, Password, type PasswordHashOptions, Persistent, PgApiKeyRepository, PgChatMemory, PgChatRepository, PgCronJobRepository, PgCrudRepository, PgJobRepository, PgJwtRefreshTokenRepository, PgLockKey, PgLocker, PgRepositoryBase, PgWhatsAppRepository, RamChatMemory, RamChatRepository, Random, RemoteApiKeyRepository, RestControllerMetadataStore, RestRequest, SocketChannel, SocketChannelConfig, SocketChannelReceivedMessage, SocketControllerMetadataStore, SocketServerConfig, SocketServerProvider, Storable, TelegramChannel, TelegramChannelConfig, ValidationMetadataStore, WHATSAPP_MESSAGE_EVENT, WHATSAPP_PROXY_LISTEN_MESSAGE_EVENT, WHATSAPP_PROXY_SEND_MESSAGE_EVENT, WabotChatAdapter, WhatsApp, WhatsAppChannel, WhatsAppReceiver, WhatsAppReceiverByCloudApi, WhatsAppReceiverByWabotProxy, WhatsAppRepository, WhatsAppSender, WhatsAppSenderByCloudApi, WhatsAppSenderByWabotProxy, WhatsAppWabotProxyConnection, WhatsappChannelConfig, apiKeyGuard, apiKeyHandshakeGuard, chatBot, chatController, chatItemTypeOptions, cmd, command, commandHandler, container, cron, description, getClientMap, getPgClient, handshakeMiddlewares, inject, injectable, isArray, isBoolean, isDate, isIn, isModel, isNotEmpty, isNumber, isOptional, isPresent, isRecord, isString, jwtGuard, jwtHandshakeGuard, max, middleware, min, mindset, mindsetModule, modelInfo, onDelete, onGet, onPost, onPut, onSocketEvent, pgStorage, readJsonFromFile, restController, runChatControllers, runCommandHandlers, runCronHandlers, runRestControllers, runSocketControllers, safeJsonParse, scoped, setupErrorHandlers, singleton, socket, socketController, stopCommandHandlers, stopCronHandlers, telegram, validateAndTransform, validateArray, validateIsBoolean, validateIsDate, validateIsIn, validateIsNotEmpty, validateIsNumber, validateIsPresent, validateIsRecord, validateIsString, validateMax, validateMin, validateModel, whatsApp, withPgClient, withPgTransaction, writeJsonToFile };
1936
+ export { AnthropicChatAdapter, ApiKey, ApiKeyGuardMiddleware, ApiKeyHandshakeGuardMiddleware, ApiKeyRepository, Async, AsyncMetadataStore, Auth, Chat, ChatAdapter, ChatBot, ChatBotMetadataStore, ChatItem, ChatMemory, ChatRepository, ChatResolver, type ClientMap, CmdChannel, Container, ControllerMetadataStore, CronJob, CronJobRepository, CustomError, DeepSeekChatAdapter, DescriptionMetadataStore, EXPRESS_REQ, EXPRESS_RES, Entity, Env, EnvWhatsAppRepository, type ErrorSeverity, ExpressProvider, GoogleChatAdapter, type GoogleChatAdapterV2Options, HtmlModule, HttpServerProvider, type IApiKeyData, type IApiKeyRepository, type IArrayValidationError, type IArrayValidationResult, type IBotMessageItem, type IChannelMessage, type IChannelMetadata, type IChatAdapter, type IChatAdapterNextItemsReq, type IChatAdapterNextItemsRes, type IChatAssociation, type IChatBot, type IChatBotMetadata, type IChatChannel, type IChatConnection, type IChatControllerMetadata, type IChatData, type IChatItem, type IChatItemData, type IChatItemType, type IChatMemory, type IChatMessage, type IChatRepository, type IChatType, type ICommandConfig, type ICommandHandler, type ICommandHandlerConfig, type IConstructor, type ICronConfig, type ICronJobData, type ICrudRepository, type ICustomErrorData, type IDescriptionMetadata, type IEndPointConfig, type IEndPointMetadata, type IEntityData, type IEnvType, type IErrorHandlersConfig, type IErrorMonitor, type IErrorMonitorContext, type IFunctionCall, type IFunctionCallItem, type IGenerateApiKeyReq, type IGenerateApiKeyRes, type IGetWhatsAppTemplateRequest, type IHandshakeMiddleware, type IHandshakeMiddlewareMetadata, type IHtmlModuleOptions, type IHumanMessageItem, type IJobData, type IJobRepository, type IJwtRefreshTokenData, type IJwtRefreshTokenRepository, type ILanguageModelUsage, type IListenWhatsAppMessageRequest, type ILockKey, type ILocker, type ILockerKey, type IMessageContext, type IMiddleware, type IMiddlewareMetadata, type IMindset, type IMindsetConfig, type IMindsetIdentity, type IMindsetLlm, type IMindsetMetadata, type IMindsetModuleConfig, type IMindsetModuleMetadata, type IMindsetTool, type IMindsetToolParameter, type IModelValidationError, type IModelValidationResult, type IModelValidatorsInfo, type IMoneyData, type IPersistentData, type IPgRepositoryConfig, type IPropertyValidatorInfo, type IReceivedMessage, type IRemoteApiKeyFetcher, type IRestControllerConfig, type IRestControllerMetadata, type IScheduleAt, type IScheduleDelay, type ISendWhatsAppRequest, type ISendWhatsAppTemplateRequest, type ISocketChannelConfig, type ISocketChannelReceivedMessage, type ISocketControllerConfig, type ISocketControllerMetadata, type ISocketEventConfig, type ISocketEventMetadata, type IStorableData, type ITelegramChannelConfig, type IValidateArrayOptions, type IValidateArrayOptionsWithItemsValidators, type IValidateInputShape, type IValidateIsInOptions, type IValidateIsRecordOptions, type IValidateMaxOptions, type IValidateMinOptions, type IValidationError, type IValidationResult, type IValidator, type IValidatorMetadata, type IWhatsAppBusinessAccount, type IWhatsAppBusinessNumber, type IWhatsAppCloudContact, type IWhatsAppCloudMessage, type IWhatsAppCloudMessageMetadata, type IWhatsAppCloudTemplate, type IWhatsAppCloudTemplateComponent, type IWhatsAppCloudTemplateMessage, type IWhatsAppCloudTemplateParameter, type IWhatsAppCloudTemplateResponse, type IWhatsAppCloudWebhookPayload, type IWhatsAppData, type IWhatsAppMessageListener, type IWhatsAppProxyListenMessageEventData, type IWhatsAppProxyListenMessageEventReq, type IWhatsAppProxyMessage, type IWhatsAppProxyMessageContent, type IWhatsAppProxyMessageEventReq, type IWhatsAppProxySendMessageEventReq, type IWhatsAppRepository, type IWhatsAppSenderOptions, type IWhatsappChannelConfig, type IchatControllerConfig, Job, JobRepository, JobRunner, Jwt, JwtAccessAndRefreshTokenDto, JwtConfig, JwtGuardMiddleware, JwtHandshakeGuardMiddleware, JwtRefreshToken, JwtRefreshTokenRepository, JwtSigner, JwtTokenDto, Lifecycle, Locker, Logger, Mapper, Mindset, MindsetMetadataStore, MindsetOperator, Money, MoneyDto, OpenaiChatAdapter, Password, type PasswordHashOptions, Persistent, PgApiKeyRepository, PgChatMemory, PgChatRepository, PgCronJobRepository, PgCrudRepository, PgJobRepository, PgJwtRefreshTokenRepository, PgLockKey, PgLocker, PgRepositoryBase, PgWhatsAppRepository, RamChatMemory, RamChatRepository, Random, RemoteApiKeyRepository, RestControllerMetadataStore, RestRequest, SocketChannel, SocketChannelConfig, SocketChannelReceivedMessage, SocketControllerMetadataStore, SocketServerConfig, SocketServerProvider, Storable, TelegramChannel, TelegramChannelConfig, ValidationMetadataStore, WHATSAPP_MESSAGE_EVENT, WHATSAPP_PROXY_LISTEN_MESSAGE_EVENT, WHATSAPP_PROXY_SEND_MESSAGE_EVENT, WabotChatAdapter, WhatsApp, WhatsAppChannel, WhatsAppReceiver, WhatsAppReceiverByCloudApi, WhatsAppReceiverByWabotProxy, WhatsAppRepository, WhatsAppSender, WhatsAppSenderByCloudApi, WhatsAppSenderByWabotProxy, WhatsAppWabotProxyConnection, WhatsappChannelConfig, apiKeyGuard, apiKeyHandshakeGuard, chatBot, chatController, chatItemTypeOptions, cmd, command, commandHandler, container, cron, description, getClientMap, getPgClient, handshakeMiddlewares, inject, injectable, isArray, isBoolean, isDate, isIn, isModel, isNotEmpty, isNumber, isOptional, isPresent, isRecord, isString, jwtGuard, jwtHandshakeGuard, max, middleware, min, mindset, mindsetModule, modelInfo, onDelete, onGet, onPost, onPut, onSocketEvent, pgStorage, readJsonFromFile, restController, runChatControllers, runCommandHandlers, runCronHandlers, runRestControllers, runSocketControllers, safeJsonParse, scoped, setupErrorHandlers, singleton, socket, socketController, stopCommandHandlers, stopCronHandlers, telegram, validateAndTransform, validateArray, validateIsBoolean, validateIsDate, validateIsIn, validateIsNotEmpty, validateIsNumber, validateIsPresent, validateIsRecord, validateIsString, validateMax, validateMin, validateModel, whatsApp, withPgClient, withPgTransaction, writeJsonToFile };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wabot-dev/framework",
3
- "version": "0.5.1",
3
+ "version": "0.5.2",
4
4
  "description": "Framework for IA Chat Bots",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",