📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
import { ApiProperty } from '@nestjs/swagger'
import {
IsArray,
IsNotEmpty,
IsString,
ValidateNested,
IsIn,
IsOptional,
IsInt,
IsBoolean,
IsUUID,
Min,
Max,
ArrayMaxSize,
MaxLength,
MinLength,
registerDecorator,
ValidationOptions,
ValidationArguments,
} from 'class-validator'
import { Type, Transform } from 'class-transformer'
const MAX_MESSAGES_PER_CHAT = 50
const MAX_MESSAGE_LENGTH = 5000
const MAX_CHAT_NAME_LENGTH = 200
const MAX_TOOL_CALLS_PER_MESSAGE = 50
const MAX_TOOL_NAME_LENGTH = 100
export const MAX_TAGS_PER_CHAT = 5
export const MAX_TAG_LENGTH = 30
const MAX_TOOL_ARGS_JSON_LENGTH = 4000
const MAX_TOOL_ARGS_DEPTH = 8
const measureJsonDepth = (value: unknown, depth = 0): number => {
if (depth > MAX_TOOL_ARGS_DEPTH) return depth
if (value === null || typeof value !== 'object') return depth
let max = depth
if (Array.isArray(value)) {
for (const item of value) {
const d = measureJsonDepth(item, depth + 1)
if (d > max) max = d
if (max > MAX_TOOL_ARGS_DEPTH) return max
}
return max
}
for (const key of Object.keys(value as Record<string, unknown>)) {
const d = measureJsonDepth(
(value as Record<string, unknown>)[key],
depth + 1,
)
if (d > max) max = d
if (max > MAX_TOOL_ARGS_DEPTH) return max
}
return max
}
/**
* Validates that a value is JSON-serialisable, has bounded serialised length,
* and bounded nesting depth. Used to defend the persisted chat payload from
* arbitrarily large/nested user-supplied tool args.
*/
function IsBoundedJson(validationOptions?: ValidationOptions) {
return function (object: object, propertyName: string) {
registerDecorator({
name: 'isBoundedJson',
target: object.constructor,
propertyName,
options: validationOptions,
validator: {
validate(value: unknown) {
if (value === undefined || value === null) return true
let json: string
try {
json = JSON.stringify(value)
} catch {
return false
}
if (typeof json !== 'string') return false
if (json.length > MAX_TOOL_ARGS_JSON_LENGTH) return false
if (measureJsonDepth(value) > MAX_TOOL_ARGS_DEPTH) return false
return true
},
defaultMessage(args: ValidationArguments) {
return `${args.property} must be JSON-serialisable, at most ${MAX_TOOL_ARGS_JSON_LENGTH} chars when stringified, and nested no deeper than ${MAX_TOOL_ARGS_DEPTH} levels`
},
},
})
}
}
class ChatMessageToolCallDto {
@ApiProperty({ description: 'Tool name that was invoked' })
@IsNotEmpty()
@IsString()
@MaxLength(MAX_TOOL_NAME_LENGTH)
toolName: string
@ApiProperty({
description: 'Arguments the tool was called with (arbitrary JSON)',
})
@IsOptional()
@IsBoundedJson()
args?: unknown
@ApiProperty({
required: false,
description: 'ISO timestamp when the tool call was issued',
})
@IsOptional()
@IsString()
@MaxLength(40)
timestamp?: string
}
class ChatMessageDto {
@ApiProperty({
enum: ['user', 'assistant'],
description: 'The role of the message sender',
})
@IsNotEmpty()
@IsIn(['user', 'assistant'])
role: 'user' | 'assistant'
@ApiProperty({
description: 'The content of the message',
})
@IsNotEmpty()
@IsString()
@MaxLength(MAX_MESSAGE_LENGTH)
content: string
@ApiProperty({
required: false,
type: [String],
description: 'AI-suggested follow-up prompts for this assistant message',
})
@IsOptional()
@IsArray()
@ArrayMaxSize(3)
@IsString({ each: true })
@MaxLength(140, { each: true })
followUps?: string[]
@ApiProperty({
required: false,
type: [ChatMessageToolCallDto],
description:
'Tool calls performed while producing this assistant message (used for the "How I got this" breakdown)',
})
@IsOptional()
@IsArray()
@ArrayMaxSize(MAX_TOOL_CALLS_PER_MESSAGE)
@ValidateNested({ each: true })
@Type(() => ChatMessageToolCallDto)
toolCalls?: ChatMessageToolCallDto[]
}
export class ChatDto {
@ApiProperty({
type: [ChatMessageDto],
description: 'Array of chat messages',
})
@IsArray()
@ArrayMaxSize(MAX_MESSAGES_PER_CHAT)
@ValidateNested({ each: true })
@Type(() => ChatMessageDto)
messages: ChatMessageDto[]
@ApiProperty({
required: false,
description: 'Timezone for date/time context',
})
@IsOptional()
@IsString()
timezone?: string
@ApiProperty({
required: false,
description: 'Chat ID to continue an existing conversation',
})
@IsOptional()
@IsString()
chatId?: string
}
export class CreateChatDto {
@ApiProperty({
type: [ChatMessageDto],
description: 'Array of chat messages',
})
@IsArray()
@ArrayMaxSize(MAX_MESSAGES_PER_CHAT)
@ValidateNested({ each: true })
@Type(() => ChatMessageDto)
messages: ChatMessageDto[]
@ApiProperty({
required: false,
description: 'Custom name for the chat',
})
@IsOptional()
@IsString()
@MaxLength(MAX_CHAT_NAME_LENGTH)
name?: string
@ApiProperty({
required: false,
description:
'ID of the chat this conversation was branched from. Must belong to the same project.',
})
@IsOptional()
@IsUUID()
parentChatId?: string
}
export class UpdateChatDto {
@ApiProperty({
type: [ChatMessageDto],
required: false,
description: 'Array of chat messages',
})
@IsOptional()
@IsArray()
@ArrayMaxSize(MAX_MESSAGES_PER_CHAT)
@ValidateNested({ each: true })
@Type(() => ChatMessageDto)
messages?: ChatMessageDto[]
@ApiProperty({
required: false,
description: 'Custom name for the chat',
})
@IsOptional()
@IsString()
@MaxLength(MAX_CHAT_NAME_LENGTH)
name?: string
}
const parseOptionalBool = ({ value }: { value: unknown }) => {
if (value === undefined || value === null || value === '') return undefined
if (typeof value === 'boolean') return value
const v = String(value).toLowerCase()
if (v === 'true' || v === '1') return true
if (v === 'false' || v === '0') return false
// Preserve the original value so @IsBoolean fails validation (400) instead
// of @IsOptional silently treating an invalid input as absent.
return value
}
export class GetRecentChatsQueryDto {
@ApiProperty({
required: false,
description: 'Maximum number of chats to return (1-100)',
default: 5,
})
@IsOptional()
@Transform(({ value }) => parseInt(value, 10))
@IsInt()
@Min(1)
@Max(100)
limit?: number
@ApiProperty({
required: false,
description: 'Number of chats to skip (0 or greater)',
})
@IsOptional()
@Transform(({ value }) => parseInt(value, 10))
@IsInt()
@Min(0)
@Max(10000)
skip?: number
@ApiProperty({
required: false,
description: 'Number of chats to return (1-100)',
})
@IsOptional()
@Transform(({ value }) => parseInt(value, 10))
@IsInt()
@Min(1)
@Max(100)
take?: number
@ApiProperty({
required: false,
description: 'Search query (matches chat names; falls back to messages)',
})
@IsOptional()
@Transform(({ value }) => (value === '' ? undefined : value))
@IsString()
@MinLength(2)
@MaxLength(100)
search?: string
@ApiProperty({
required: false,
description: 'Filter by tag (single tag string)',
})
@IsOptional()
@IsString()
@MaxLength(MAX_TAG_LENGTH)
tag?: string
@ApiProperty({
required: false,
description: 'When true, only pinned chats are returned',
})
@IsOptional()
@Transform(parseOptionalBool)
@IsBoolean()
pinned?: boolean
@ApiProperty({
required: false,
description:
'When false, results are sorted by recency only (ignoring pinned status). Defaults to true.',
})
@IsOptional()
@Transform(parseOptionalBool)
@IsBoolean()
orderByPinned?: boolean
}
export class UpdateChatMetaDto {
@ApiProperty({ required: false, description: 'Whether the chat is pinned' })
@IsOptional()
@IsBoolean()
pinned?: boolean
@ApiProperty({
required: false,
type: [String],
description: `User-defined tag labels (max ${MAX_TAGS_PER_CHAT}, ${MAX_TAG_LENGTH} chars each)`,
})
@IsOptional()
@IsArray()
@ArrayMaxSize(MAX_TAGS_PER_CHAT)
@IsString({ each: true })
@MaxLength(MAX_TAG_LENGTH, { each: true })
tags?: string[]
@ApiProperty({ required: false, description: 'Custom name for the chat' })
@IsOptional()
@IsString()
@MaxLength(MAX_CHAT_NAME_LENGTH)
name?: string
}
export class FeedbackDto {
@ApiProperty({
enum: ['good', 'bad'],
description: 'User feedback on the AI response',
})
@IsNotEmpty()
@IsIn(['good', 'bad'])
rating: 'good' | 'bad'
@ApiProperty({ required: false, description: 'Optional comment' })
@IsOptional()
@IsString()
@MaxLength(2000)
comment?: string
@ApiProperty({
required: false,
description: 'Index of the assistant message the rating refers to',
})
@IsOptional()
@IsInt()
@Min(0)
@Max(MAX_MESSAGES_PER_CHAT - 1)
messageIndex?: number
}
export class GetAllChatsQueryDto {
@ApiProperty({
required: false,
description: 'Number of chats to skip (0 or greater)',
default: 0,
})
@IsOptional()
@Transform(({ value }) => parseInt(value, 10))
@IsInt()
@Min(0)
@Max(10000)
skip?: number
@ApiProperty({
required: false,
description: 'Number of chats to return (1-100)',
default: 20,
})
@IsOptional()
@Transform(({ value }) => parseInt(value, 10))
@IsInt()
@Min(1)
@Max(100)
take?: number
}