feat: zod validation message

This commit is contained in:
abdou6666 2025-02-04 11:05:22 +01:00
parent 42c7d110a2
commit af536a9f48
8 changed files with 356 additions and 226 deletions

View File

@ -6,14 +6,24 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/ */
/*
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { z } from 'zod';
import { PluginName } from '@/plugins/types'; import { PluginName } from '@/plugins/types';
import { Message } from '../message.schema'; import { Message } from '../message.schema';
import { AttachmentPayload } from './attachment'; import { attachmentPayloadSchema } from './attachment';
import { Button } from './button'; import { buttonSchema } from './button';
import { ContentOptions } from './options'; import { contentOptionsSchema } from './options';
import { StdQuickReply } from './quick-reply'; import { QuickReplyType, stdQuickReplySchema } from './quick-reply';
/** /**
* StdEventType enum is declared, and currently not used * StdEventType enum is declared, and currently not used
@ -41,6 +51,10 @@ export enum IncomingMessageType {
unknown = '', unknown = '',
} }
export const incomingMessageType = z.nativeEnum(IncomingMessageType);
export type IncomingMessageTypeLiteral = z.infer<typeof incomingMessageType>;
export enum OutgoingMessageFormat { export enum OutgoingMessageFormat {
text = 'text', text = 'text',
quickReplies = 'quickReplies', quickReplies = 'quickReplies',
@ -50,6 +64,12 @@ export enum OutgoingMessageFormat {
carousel = 'carousel', carousel = 'carousel',
} }
export const outgoingMessageFormatSchema = z.nativeEnum(OutgoingMessageFormat);
export type OutgoingMessageFormatLiteral = z.infer<
typeof outgoingMessageFormatSchema
>;
/** /**
* FileType enum is declared, and currently not used * FileType enum is declared, and currently not used
**/ **/
@ -61,6 +81,10 @@ export enum FileType {
unknown = 'unknown', unknown = 'unknown',
} }
export const fileTypeSchema = z.nativeEnum(FileType);
export type FileTypeLiteral = z.infer<typeof fileTypeSchema>;
export enum PayloadType { export enum PayloadType {
location = 'location', location = 'location',
attachments = 'attachments', attachments = 'attachments',
@ -68,85 +92,151 @@ export enum PayloadType {
button = 'button', button = 'button',
} }
export type StdOutgoingTextMessage = { text: string }; export const payloadTypeSchema = z.nativeEnum(PayloadType);
export type StdOutgoingQuickRepliesMessage = { export type PayloadTypeLiteral = z.infer<typeof payloadTypeSchema>;
text: string;
quickReplies: StdQuickReply[];
};
export type StdOutgoingButtonsMessage = { export const stdOutgoingTextMessageSchema = z.object({
text: string; text: z.string(),
buttons: Button[]; });
};
export type ContentElement = { id: string; title: string } & Record< export type StdOutgoingTextMessage = z.infer<
string, typeof stdOutgoingTextMessageSchema
any
>; >;
export type StdOutgoingListMessage = { export const stdOutgoingQuickRepliesMessageSchema = z.object({
options: ContentOptions; text: z.string(),
elements: ContentElement[]; quickReplies: z.array(stdQuickReplySchema),
pagination: { });
total: number;
skip: number;
limit: number;
};
};
export type StdOutgoingAttachmentMessage = { export type StdOutgoingQuickRepliesMessage = z.infer<
// Stored in DB as `AttachmentPayload`, `Attachment` when populated for channels relaying typeof stdOutgoingQuickRepliesMessageSchema
attachment: AttachmentPayload; >;
quickReplies?: StdQuickReply[];
};
export type StdPluginMessage = { export const stdOutgoingButtonsMessageSchema = z.object({
plugin: PluginName; text: z.string(),
args: { [key: string]: any }; buttons: z.array(buttonSchema),
}; });
export type BlockMessage = export type StdOutgoingButtonsMessage = z.infer<
| string[] typeof stdOutgoingButtonsMessageSchema
| StdOutgoingTextMessage >;
| StdOutgoingQuickRepliesMessage
| StdOutgoingButtonsMessage
| StdOutgoingListMessage
| StdOutgoingAttachmentMessage
| StdPluginMessage;
export type StdOutgoingMessage = export const contentElementSchema = z
| StdOutgoingTextMessage .object({
| StdOutgoingQuickRepliesMessage id: z.string(),
| StdOutgoingButtonsMessage title: z.string(),
| StdOutgoingListMessage })
| StdOutgoingAttachmentMessage; .catchall(z.any());
type StdIncomingTextMessage = { text: string }; export type ContentElement = z.infer<typeof contentElementSchema>;
export type StdIncomingPostBackMessage = StdIncomingTextMessage & { export const stdOutgoingListMessageSchema = z.object({
postback: string; options: contentOptionsSchema,
}; elements: z.array(contentElementSchema),
pagination: z.object({
total: z.number(),
skip: z.number(),
limit: z.number(),
}),
});
export type StdIncomingLocationMessage = { export type StdOutgoingListMessage = z.infer<
type: PayloadType.location; typeof stdOutgoingListMessageSchema
coordinates: { >;
lat: number;
lon: number;
};
};
export type StdIncomingAttachmentMessage = { export const stdOutgoingAttachmentMessageSchema = z.object({
type: PayloadType.attachments; attachment: attachmentPayloadSchema,
serialized_text: string; quickReplies: z.array(stdQuickReplySchema).optional(),
attachment: AttachmentPayload | AttachmentPayload[]; });
};
export type StdIncomingMessage = export type StdOutgoingAttachmentMessage = z.infer<
| StdIncomingTextMessage typeof stdOutgoingAttachmentMessageSchema
| StdIncomingPostBackMessage >;
| StdIncomingLocationMessage
| StdIncomingAttachmentMessage; export const pluginNameSchema = z.object({
name: z.string().regex(/-plugin$/) as z.ZodType<PluginName>,
});
export const stdPluginMessageSchema = z.object({
plugin: pluginNameSchema,
args: z.record(z.any()),
});
export type StdPluginMessage = z.infer<typeof stdPluginMessageSchema>;
export const BlockMessageSchema = z.union([
z.array(z.string()),
stdOutgoingTextMessageSchema,
stdOutgoingQuickRepliesMessageSchema,
stdOutgoingButtonsMessageSchema,
stdOutgoingListMessageSchema,
stdOutgoingAttachmentMessageSchema,
stdPluginMessageSchema,
]);
export type BlockMessage = z.infer<typeof BlockMessageSchema>;
export const StdOutgoingMessageSchema = z.union([
stdOutgoingTextMessageSchema,
stdOutgoingQuickRepliesMessageSchema,
stdOutgoingButtonsMessageSchema,
stdOutgoingListMessageSchema,
stdOutgoingAttachmentMessageSchema,
]);
export type StdOutgoingMessage = z.infer<typeof StdOutgoingMessageSchema>;
export const stdIncomingTextMessageSchema = z.object({
text: z.string(),
});
export type StdIncomingTextMessage = z.infer<
typeof stdIncomingTextMessageSchema
>;
export const stdIncomingPostBackMessageSchema =
stdIncomingTextMessageSchema.extend({
postback: z.string(),
});
export type StdIncomingPostBackMessage = z.infer<
typeof stdIncomingPostBackMessageSchema
>;
export const stdIncomingLocationMessageSchema = z.object({
type: z.literal(PayloadType.location),
coordinates: z.object({
lat: z.number(),
lon: z.number(),
}),
});
export type StdIncomingLocationMessage = z.infer<
typeof stdIncomingLocationMessageSchema
>;
export const stdIncomingAttachmentMessageSchema = z.object({
type: z.literal(PayloadType.attachments),
serialized_text: z.string(),
attachment: z.union([
attachmentPayloadSchema,
z.array(attachmentPayloadSchema),
]),
});
export type StdIncomingAttachmentMessage = z.infer<
typeof stdIncomingAttachmentMessageSchema
>;
export const stdIncomingMessageSchema = z.union([
stdIncomingTextMessageSchema,
stdIncomingPostBackMessageSchema,
stdIncomingLocationMessageSchema,
stdIncomingAttachmentMessageSchema,
]);
export type StdIncomingMessage = z.infer<typeof stdIncomingMessageSchema>;
export interface IncomingMessage extends Omit<Message, 'recipient' | 'sentBy'> { export interface IncomingMessage extends Omit<Message, 'recipient' | 'sentBy'> {
message: StdIncomingMessage; message: StdIncomingMessage;
@ -162,34 +252,121 @@ export interface OutgoingMessage extends Omit<Message, 'sender'> {
export type AnyMessage = IncomingMessage | OutgoingMessage; export type AnyMessage = IncomingMessage | OutgoingMessage;
export interface StdOutgoingTextEnvelope { export const stdOutgoingTextEnvelopeSchema = z.object({
format: OutgoingMessageFormat.text; format: z.literal(OutgoingMessageFormat.text),
message: StdOutgoingTextMessage; message: stdOutgoingTextMessageSchema,
} });
export interface StdOutgoingQuickRepliesEnvelope { export type StdOutgoingTextEnvelope = z.infer<
format: OutgoingMessageFormat.quickReplies; typeof stdOutgoingTextEnvelopeSchema
message: StdOutgoingQuickRepliesMessage; >;
}
export interface StdOutgoingButtonsEnvelope { export const stdOutgoingQuickRepliesEnvelopeSchema = z.object({
format: OutgoingMessageFormat.buttons; format: z.literal(OutgoingMessageFormat.quickReplies),
message: StdOutgoingButtonsMessage; message: stdOutgoingQuickRepliesMessageSchema,
} });
export interface StdOutgoingListEnvelope { export type StdOutgoingQuickRepliesEnvelope = z.infer<
format: OutgoingMessageFormat.list | OutgoingMessageFormat.carousel; typeof stdOutgoingQuickRepliesEnvelopeSchema
message: StdOutgoingListMessage; >;
}
export interface StdOutgoingAttachmentEnvelope { export const stdOutgoingButtonsEnvelopeSchema = z.object({
format: OutgoingMessageFormat.attachment; format: z.literal(OutgoingMessageFormat.buttons),
message: StdOutgoingAttachmentMessage; message: stdOutgoingButtonsMessageSchema,
} });
export type StdOutgoingEnvelope = export type StdOutgoingButtonsEnvelope = z.infer<
| StdOutgoingTextEnvelope typeof stdOutgoingButtonsEnvelopeSchema
| StdOutgoingQuickRepliesEnvelope >;
| StdOutgoingButtonsEnvelope
| StdOutgoingListEnvelope export const stdOutgoingListEnvelopeSchema = z.object({
| StdOutgoingAttachmentEnvelope; format: z.union([
z.literal(OutgoingMessageFormat.list),
z.literal(OutgoingMessageFormat.carousel),
]),
message: stdOutgoingListMessageSchema,
});
export type StdOutgoingListEnvelope = z.infer<
typeof stdOutgoingListEnvelopeSchema
>;
export const stdOutgoingAttachmentEnvelopeSchema = z.object({
format: z.literal(OutgoingMessageFormat.attachment),
message: stdOutgoingAttachmentMessageSchema,
});
export type StdOutgoingAttachmentEnvelope = z.infer<
typeof stdOutgoingAttachmentEnvelopeSchema
>;
export const stdOutgoingEnvelopeSchema = z.union([
stdOutgoingTextEnvelopeSchema,
stdOutgoingQuickRepliesEnvelopeSchema,
stdOutgoingButtonsEnvelopeSchema,
stdOutgoingListEnvelopeSchema,
stdOutgoingAttachmentEnvelopeSchema,
]);
export type StdOutgoingEnvelope = z.infer<typeof stdOutgoingEnvelopeSchema>;
// is-valid-message-text validation
export const validMessageTextSchema = z.object({
message: z.string(),
});
// is-message validation
const MESSAGE_REGEX = /^function \(context\) \{[^]+\}/;
export const messageRegexSchema = z.string().regex(MESSAGE_REGEX);
export const textSchema = z.array(z.string().max(1000));
const quickReplySchema = z
.object({
content_type: z.nativeEnum(QuickReplyType),
title: z.string().max(20).optional(),
payload: z.string().max(1000).optional(),
})
.superRefine((data, ctx) => {
// When content_type is 'text', title and payload are required.
if (data.content_type === QuickReplyType.text) {
if (data.title == null) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Title is required when content_type is 'text'",
path: ['title'],
});
}
if (data.payload == null) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Payload is required when content_type is 'text'",
path: ['payload'],
});
}
}
});
// Attachment Message Schema
export const objectSchema = z.object({
text: z.string().max(1000).optional(),
attachment: z
.object({
type: z.nativeEnum(FileType),
payload: z.object({
url: z.string().url().optional(),
id: z.string().optional(),
}),
})
.optional(),
elements: z.boolean().optional(),
cards: z
.object({
default_action: buttonSchema,
buttons: z.array(buttonSchema).max(3),
})
.optional(),
buttons: z.array(buttonSchema).max(3).optional(),
quickReplies: z.array(quickReplySchema).max(11).optional(),
});

View File

@ -1,42 +1,47 @@
/* /*
* Copyright © 2024 Hexastack. All rights reserved. * Copyright © 2025 Hexastack. All rights reserved.
* *
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/ */
import { Button } from './button'; import { z } from 'zod';
import { buttonSchema } from './button';
import { OutgoingMessageFormat } from './message'; import { OutgoingMessageFormat } from './message';
export interface ContentOptions { export const contentOptionsSchema = z.object({
display: OutgoingMessageFormat.list | OutgoingMessageFormat.carousel; display: z.nativeEnum(OutgoingMessageFormat),
fields: { fields: z.object({
title: string; title: z.string(),
subtitle: string | null; subtitle: z.string().nullable(),
image_url: string | null; image_url: z.string().nullable(),
url?: string; url: z.string().optional(),
action_title?: string; action_title: z.string().optional(),
action_payload?: string; action_payload: z.string().optional(),
}; }),
buttons: Button[]; buttons: z.array(buttonSchema),
limit: number; limit: z.number().finite(),
query?: any; // Waterline model criteria query: z.any().optional(),
entity?: string | number; // ContentTypeID entity: z.union([z.string(), z.number().finite()]).optional(),
top_element_style?: 'large' | 'compact'; top_element_style: z.enum(['large', 'compact']).optional(),
} });
export interface BlockOptions { export type ContentOptions = z.infer<typeof contentOptionsSchema>;
typing?: number;
// In case of carousel/list message export const BlockOptionsSchema = z.object({
content?: ContentOptions; typing: z.number().optional(),
// Only if the block has next blocks content: contentOptionsSchema.optional(),
fallback?: { fallback: z
active: boolean; .object({
message: string[]; active: z.boolean(),
max_attempts: number; message: z.array(z.string()),
}; max_attempts: z.number().finite(),
assignTo?: string; })
// plugins effects .optional(),
effects?: string[]; assignTo: z.string().optional(),
} effects: z.array(z.string()).optional(),
});
export type BlockOptions = z.infer<typeof BlockOptionsSchema>;

View File

@ -9,7 +9,6 @@
import { z } from 'zod'; import { z } from 'zod';
import { attachmentPayloadSchema } from './attachment'; import { attachmentPayloadSchema } from './attachment';
import { PayloadType } from './message';
export enum QuickReplyType { export enum QuickReplyType {
text = 'text', text = 'text',
@ -25,11 +24,11 @@ export const cordinatesSchema = z.object({
export const payloadSchema = z.discriminatedUnion('type', [ export const payloadSchema = z.discriminatedUnion('type', [
z.object({ z.object({
type: z.literal(PayloadType.location), type: z.literal('location'),
coordinates: cordinatesSchema, coordinates: cordinatesSchema,
}), }),
z.object({ z.object({
type: z.literal(PayloadType.attachments), type: z.literal('attachments'),
attachment: attachmentPayloadSchema, attachment: attachmentPayloadSchema,
}), }),
]); ]);

View File

@ -6,6 +6,14 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/ */
/*
* Copyright © 2025 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { AttachmentService } from '@/attachment/services/attachment.service'; import { AttachmentService } from '@/attachment/services/attachment.service';
@ -224,7 +232,8 @@ export class BlockService extends BaseService<
} else if ( } else if (
typeof pattern === 'object' && typeof pattern === 'object' &&
'label' in pattern && 'label' in pattern &&
text.trim().toLowerCase() === pattern.label.toLowerCase() text.trim().toLowerCase() ===
(pattern.label as unknown as string).toLowerCase()
) { ) {
// Payload (quick reply) // Payload (quick reply)
return [text]; return [text];
@ -568,15 +577,13 @@ export class BlockService extends BaseService<
contentBlockOptions, contentBlockOptions,
skip, skip,
); );
const envelope = {
const envelope: StdOutgoingEnvelope = {
format: contentBlockOptions.display, format: contentBlockOptions.display,
message: { message: {
...results, ...results,
options: contentBlockOptions, options: contentBlockOptions,
}, },
}; } as StdOutgoingEnvelope;
return envelope; return envelope;
} catch (err) { } catch (err) {
this.logger.error( this.logger.error(
@ -588,7 +595,7 @@ export class BlockService extends BaseService<
} else if (blockMessage && 'plugin' in blockMessage) { } else if (blockMessage && 'plugin' in blockMessage) {
const plugin = this.pluginService.findPlugin( const plugin = this.pluginService.findPlugin(
PluginType.block, PluginType.block,
blockMessage.plugin as PluginName, blockMessage.plugin as unknown as PluginName,
); );
// Process custom plugin block // Process custom plugin block
try { try {

View File

@ -12,103 +12,43 @@ import {
ValidatorConstraint, ValidatorConstraint,
ValidatorConstraintInterface, ValidatorConstraintInterface,
} from 'class-validator'; } from 'class-validator';
import Joi from 'joi';
import { BlockMessage } from '../schemas/types/message'; import {
BlockMessage,
messageRegexSchema,
objectSchema,
textSchema,
} from '../schemas/types/message';
/* eslint-disable no-console */
export function isValidMessage(msg: any) { export function isValidMessage(msg: any) {
if (typeof msg === 'string' && msg !== '') { if (typeof msg === 'string' && msg !== '') {
// Custom code const result = messageRegexSchema.safeParse(msg);
const MESSAGE_REGEX = /^function \(context\) \{[^]+\}/; if (!result.success) {
if (!MESSAGE_REGEX.test(msg)) { console.error('Block Model: Invalid custom code.', result.error);
// eslint-disable-next-line
console.error('Block Model : Invalid custom code.', msg);
return false; return false;
} else {
return true;
} }
return true;
} else if (Array.isArray(msg)) { } else if (Array.isArray(msg)) {
// Simple text message const result = textSchema.safeParse(msg);
const textSchema = Joi.array().items(Joi.string().max(1000).required()); if (!result.success) {
const textCheck = textSchema.validate(msg); console.error('Block Model: Invalid text message array.', result.error);
return !textCheck.error; }
} else if (typeof msg === 'object') { return result.success;
} else if (typeof msg === 'object' && msg !== null) {
if ('plugin' in msg) { if ('plugin' in msg) {
return true; return true;
} else {
const buttonsSchema = Joi.array().items(
Joi.object().keys({
type: Joi.string().valid('postback', 'web_url').required(),
title: Joi.string().max(20),
payload: Joi.alternatives().conditional('type', {
is: 'postback',
then: Joi.string().max(1000).required(),
otherwise: Joi.forbidden(),
}),
url: Joi.alternatives().conditional('type', {
is: 'web_url',
then: Joi.string().uri(),
otherwise: Joi.forbidden(),
}),
messenger_extensions: Joi.alternatives().conditional('type', {
is: 'web_url',
then: Joi.boolean(),
otherwise: Joi.forbidden(),
}),
webview_height_ratio: Joi.alternatives().conditional('type', {
is: 'web_url',
then: Joi.string().valid('compact', 'tall', 'full'),
otherwise: Joi.forbidden(),
}),
}),
);
// Attachment message
const objectSchema = Joi.object().keys({
text: Joi.string().max(1000),
attachment: Joi.object().keys({
type: Joi.string()
.valid('image', 'audio', 'video', 'file', 'unknown')
.required(),
payload: Joi.object().keys({
url: Joi.string().uri(),
id: Joi.string().allow(null),
}),
}),
elements: Joi.boolean(),
cards: Joi.object().keys({
default_action: buttonsSchema.max(1),
buttons: buttonsSchema.max(3),
}),
buttons: buttonsSchema.max(3),
quickReplies: Joi.array()
.items(
Joi.object().keys({
content_type: Joi.string()
.valid('text', 'location', 'user_phone_number', 'user_email')
.required(),
title: Joi.alternatives().conditional('content_type', {
is: 'text',
then: Joi.string().max(20).required(),
}),
payload: Joi.alternatives().conditional('content_type', {
is: 'text',
then: Joi.string().max(1000).required(),
}),
}),
)
.max(11),
});
const objectCheck = objectSchema.validate(msg);
if (objectCheck.error) {
// eslint-disable-next-line
console.log('Message validation failed! ', objectCheck);
} }
return !objectCheck.error; const result = objectSchema.safeParse(msg);
if (!result.success) {
console.error('Block Model: Object validation failed!', result.error);
} }
} else { return result.success;
}
console.log('Validation reached default false');
return false; return false;
}
} }
/* eslint-enable no-console */
@ValidatorConstraint({ async: false }) @ValidatorConstraint({ async: false })
export class MessageValidator implements ValidatorConstraintInterface { export class MessageValidator implements ValidatorConstraintInterface {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Hexastack. All rights reserved. * Copyright © 2025 Hexastack. All rights reserved.
* *
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
@ -11,6 +11,7 @@ import { registerDecorator, ValidationOptions } from 'class-validator';
import { import {
StdIncomingMessage, StdIncomingMessage,
StdOutgoingTextMessage, StdOutgoingTextMessage,
validMessageTextSchema,
} from '../schemas/types/message'; } from '../schemas/types/message';
export function IsValidMessageText(validationOptions?: ValidationOptions) { export function IsValidMessageText(validationOptions?: ValidationOptions) {
@ -21,7 +22,7 @@ export function IsValidMessageText(validationOptions?: ValidationOptions) {
options: validationOptions, options: validationOptions,
validator: { validator: {
validate(message: StdOutgoingTextMessage | StdIncomingMessage) { validate(message: StdOutgoingTextMessage | StdIncomingMessage) {
return !!(message as StdOutgoingTextMessage).text; return validMessageTextSchema.safeParse(message).success;
}, },
}, },
}); });

View File

@ -9,6 +9,7 @@
import { EventEmitter2 } from '@nestjs/event-emitter'; import { EventEmitter2 } from '@nestjs/event-emitter';
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from '@nestjs/testing';
import { BlockMessage } from '@/chat/schemas/types/message';
import { I18nService } from '@/i18n/services/i18n.service'; import { I18nService } from '@/i18n/services/i18n.service';
import { BasePlugin } from '@/plugins/base-plugin.service'; import { BasePlugin } from '@/plugins/base-plugin.service';
import { PluginService } from '@/plugins/plugins.service'; import { PluginService } from '@/plugins/plugins.service';
@ -154,7 +155,7 @@ describe('TranslationService', () => {
model: 'String 1', model: 'String 1',
context: ['String 2', 'String 3'], context: ['String 2', 'String 3'],
}, },
}, } as unknown as BlockMessage,
options: {}, options: {},
attachedBlock: null, attachedBlock: null,
}; };

View File

@ -11,7 +11,7 @@ import { OnEvent } from '@nestjs/event-emitter';
import { I18nService } from '@/i18n/services/i18n.service'; import { I18nService } from '@/i18n/services/i18n.service';
import { PluginService } from '@/plugins/plugins.service'; import { PluginService } from '@/plugins/plugins.service';
import { PluginType } from '@/plugins/types'; import { PluginName, PluginType } from '@/plugins/types';
import { SettingService } from '@/setting/services/setting.service'; import { SettingService } from '@/setting/services/setting.service';
import { BaseService } from '@/utils/generics/base-service'; import { BaseService } from '@/utils/generics/base-service';
@ -54,7 +54,7 @@ export class TranslationService extends BaseService<Translation> {
if ('plugin' in block.message) { if ('plugin' in block.message) {
const plugin = this.pluginService.getPlugin( const plugin = this.pluginService.getPlugin(
PluginType.block, PluginType.block,
block.message.plugin, block.message.plugin as unknown as PluginName,
); );
// plugin // plugin