import { BodyType } from './functions/send-crisp-message.js' type CamelCase = S extends `${infer P1}_${infer P2}${infer P3}` ? `${Lowercase}${Uppercase}${CamelCase}` : Lowercase const snakeToCamelCase = (str: T) => str .replace(/_/g, ' ') .replace(/(? (+m === 0 ? '' : m.toUpperCase())) .replace(/^./, (m) => m?.toLowerCase()) as CamelCase export type KeysToCamelCase = { [K in keyof T as CamelCase]: T[K] } export const snakeToCamelCaseKeys = (object: T) => Object.fromEntries( Object.entries(object).map( ([key, value]) => [snakeToCamelCase(key), value], {} ) ) as KeysToCamelCase export const shuffleArray = (array: T[]) => { const shuffle = [...array] for (let i = shuffle.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)) const [shuffleI, shuffleJ] = [shuffle[i], shuffle[j]] shuffle[i] = shuffleJ shuffle[j] = shuffleI } return shuffle } const isStringAndNotEmpty = (value: string) => value !== undefined && value !== '' && typeof value === 'string' const SHORT_MAX_LENGTH = 254 export const validateCrispBody = (body: BodyType): BodyType => { const { subject, message, email } = body || {} if ( isStringAndNotEmpty(subject) && subject.length <= SHORT_MAX_LENGTH && isStringAndNotEmpty(message) && isStringAndNotEmpty(email) && email.length <= SHORT_MAX_LENGTH ) { return body } throw Error('Body validation failed.') }