denwa-nest-shared
Version:
Shared NestJS module for DTO validation, RBAC, TypeORM query building, and OpenAPI client
1,156 lines • 41.1 kB
JavaScript
import parsePhoneNumber from 'libphonenumber-js';
import { And, ArrayOverlap, ILike, In, LessThan, LessThanOrEqual, MoreThan, MoreThanOrEqual, } from 'typeorm';
import { JSDOM } from 'jsdom';
import { z } from 'zod';
import { GqlExecutionContext } from '@nestjs/graphql';
export const getError = ({ error, message }) => {
if (error)
console.error(error);
if (message)
console.error(message);
};
export const createPaginate = (page, count, limit, modelsNumber = 1, options) => {
const pages = Math.ceil(count / (limit * modelsNumber));
const paginate = {
page,
pages,
previous: page > 1 ? page - 1 : undefined,
next: page <= pages - 1 ? page + 1 : undefined,
count,
limit,
...(options?.cursor ? { cursor: options.cursor } : {}),
...(options?.hasNextPage !== undefined ? { hasNextPage: options.hasNextPage } : {}),
};
return paginate;
};
export const encodeCursor = (data) => {
return Buffer.from(JSON.stringify(data)).toString('base64url');
};
export const decodeCursor = (cursor) => {
try {
const json = Buffer.from(cursor, 'base64url').toString('utf8');
const parsed = JSON.parse(json);
if (parsed && (typeof parsed.id === 'string' || typeof parsed.id === 'number')) {
return {
id: parsed.id,
sortValue: parsed.sortValue,
sortValues: parsed.sortValues,
order: parsed.order,
field: parsed.field,
};
}
return null;
}
catch {
return null;
}
};
export const getPaginateSkip = (page, limit) => {
return (page - 1) * limit;
};
export const formatPhone = (phone) => {
const parsedPhone = parsePhoneNumber(phone);
if (!parsedPhone?.isValid())
return '';
return parsedPhone.number;
};
export const concatenateTwo32BitNumbers = (low, high) => {
return (high >>> 0) * Math.pow(2, 32) + (low >>> 0);
};
export const prepareTokenExp = (accessExp, refreshExp) => {
let access = accessExp;
let refresh = refreshExp;
if (typeof accessExp === 'object' && 'low' in accessExp && 'high' in accessExp) {
access = concatenateTwo32BitNumbers(accessExp.low, accessExp.high);
}
if (typeof refreshExp === 'object' && 'low' in refreshExp && 'high' in refreshExp) {
refresh = concatenateTwo32BitNumbers(refreshExp.low, refreshExp.high);
}
return { access, refresh };
};
export const checkPageAndLimit = (page, limit, maxLimit = 500, maxPage) => {
const paginationData = {
checkedPage: page,
checkedLimit: limit,
};
if (page < 1) {
paginationData.checkedPage = 1;
}
if (maxPage && page > maxPage) {
paginationData.checkedPage = maxPage;
}
if (limit < 1) {
paginationData.checkedLimit = 1;
}
if (limit > maxLimit) {
paginationData.checkedLimit = maxLimit;
}
return paginationData;
};
export const isCorrectOrder = (order) => {
return order.toLocaleLowerCase() === 'asc' || order.toLocaleLowerCase() === 'desc';
};
export const createQueryData = ({ page, limit, sortField, sortFields, sortOrder, filterType = 'and', searchType = 'or', filter, filters, search, fromToFields, oneEntryArrayFields, fields, relationsMap, searchFields, cursor, select, extraRow = false, maxPage, }) => {
const getFromToFields = (key, value, fromToMap) => {
if (fromToFields) {
const found = fromToFields.find((item) => {
let fromKey = '';
let toKey = '';
if (item.fromFieldName === key)
fromKey = key;
else if (item.toFieldName === key)
toKey = key;
if (!fromKey && !toKey)
return false;
const mapValue = fromToMap.get(item.originalFieldName);
if (mapValue) {
fromToMap.set(item.originalFieldName, {
fromFieldName: mapValue.fromFieldName ? mapValue.fromFieldName : fromKey,
fromFieldValue: mapValue.fromFieldValue
? mapValue.fromFieldValue
: fromKey
? value
: null,
toFieldName: mapValue.toFieldName ? mapValue.toFieldName : toKey,
toFieldValue: mapValue.toFieldValue ? mapValue.toFieldValue : toKey ? value : null,
});
return true;
}
fromToMap.set(item.originalFieldName, {
fromFieldName: fromKey,
fromFieldValue: fromKey ? value : null,
toFieldName: toKey,
toFieldValue: toKey ? value : null,
});
return true;
});
return Boolean(found);
}
return false;
};
const getOneEntryArrayFields = (key, value) => {
if (!!value.length && oneEntryArrayFields) {
const finded = oneEntryArrayFields.find((item) => item.key === key);
if (finded) {
return {
key: finded.originalKey,
value: ArrayOverlap(value),
};
}
else {
return {
key: '',
value: In(value),
};
}
}
return {
key: '',
value: In(value),
};
};
const { checkedPage, checkedLimit } = checkPageAndLimit(page, limit, 500, maxPage);
let parsedCursor = null;
if (typeof cursor === 'string') {
parsedCursor = decodeCursor(cursor);
}
else if (cursor &&
typeof cursor === 'object' &&
cursor.id !== undefined &&
cursor.id !== null) {
parsedCursor = cursor;
}
const queryData = {
skip: parsedCursor ? 0 : getPaginateSkip(checkedPage, checkedLimit),
take: extraRow ? checkedLimit + 1 : checkedLimit,
};
if (select) {
queryData.select = select;
}
let effectiveSortFields = [];
if (sortFields && sortFields.length > 0) {
effectiveSortFields = sortFields
.filter((sortItem) => isCorrectOrder(sortItem.order))
.map((sortItem) => ({
field: sortItem.field,
order: sortItem.order.toLowerCase(),
}));
}
else if (sortField) {
const orderStr = sortOrder || parsedCursor?.order || 'desc';
effectiveSortFields = [
{
field: sortField,
order: isCorrectOrder(orderStr) ? orderStr.toLowerCase() : 'desc',
},
];
}
else if (parsedCursor?.field) {
const orderStr = sortOrder || parsedCursor.order || 'desc';
effectiveSortFields = [
{
field: parsedCursor.field,
order: isCorrectOrder(orderStr) ? orderStr.toLowerCase() : 'desc',
},
];
}
if (parsedCursor) {
const hasId = effectiveSortFields.some((item) => item.field === 'id');
if (!hasId) {
const lastOrder = effectiveSortFields.length > 0
? effectiveSortFields[effectiveSortFields.length - 1].order
: 'desc';
effectiveSortFields.push({ field: 'id', order: lastOrder });
}
}
if (effectiveSortFields.length > 0) {
const orderObj = {};
for (const item of effectiveSortFields) {
orderObj[item.field] = item.order;
}
queryData.order = orderObj;
}
if (filters && filters.length > 0) {
const where = filters.map((item) => {
return getFilterWhere(item, 'and');
});
queryData.where = where;
}
else if (filter && !!Object.keys(filter).length) {
const where = getFilterWhere(filter, filterType);
queryData.where = where;
}
if (typeof search === 'string' && searchFields?.length) {
const searchTerm = search.trim();
if (searchTerm) {
const orConditions = searchFields.map((field) => ({
[field]: ILike(`%${searchTerm}%`),
}));
if (!queryData.where) {
queryData.where = orConditions;
}
else if (Array.isArray(queryData.where)) {
const combined = [];
for (const whereCond of queryData.where) {
for (const searchCond of orConditions) {
combined.push({
...whereCond,
...searchCond,
});
}
}
queryData.where = combined;
}
else {
queryData.where = orConditions.map((cond) => ({
...cond,
...queryData.where,
}));
}
}
}
else if (search && typeof search === 'object' && !!Object.keys(search).length) {
const searchWhereAnd = {};
const searchWhereOr = [];
for (const [key, value] of Object.entries(search)) {
if (searchType.toLowerCase() === 'and') {
searchWhereAnd[key] = ILike(`%${value}%`);
}
else {
searchWhereOr.push({
[key]: ILike(`%${value}%`),
});
}
}
if (!queryData.where) {
if (searchType.toLowerCase() === 'and')
queryData.where = searchWhereAnd;
else
queryData.where = searchWhereOr;
}
else if (Array.isArray(queryData.where)) {
if (searchType.toLowerCase() === 'and') {
queryData.where = queryData.where.map((cond) => ({
...cond,
...searchWhereAnd,
}));
}
else {
const combined = [];
for (const whereCond of queryData.where) {
for (const searchCond of searchWhereOr) {
combined.push({
...whereCond,
...searchCond,
});
}
}
queryData.where = combined;
}
}
else {
if (searchType.toLowerCase() === 'and')
queryData.where = { ...searchWhereAnd, ...queryData.where };
else
queryData.where = searchWhereOr.map((cond) => ({
...cond,
...queryData.where,
}));
}
}
function getFilterWhere(filter, filterType) {
let whereAnd = {};
let whereOr = [];
const fromToMap = new Map();
for (const [key, value] of Object.entries(filter)) {
let currentKey = key;
let currentValue;
if (typeof value === 'object' &&
value !== null &&
!Array.isArray(value) &&
typeof value?.getTime !== 'function') {
const obj = JSON.parse(JSON.stringify(value));
const valueObject = {};
const fromToInnerMap = new Map();
for (const [innerKey, innerValue] of Object.entries(obj)) {
if (typeof innerValue === 'boolean') {
valueObject[innerKey] = innerValue;
}
else {
const isFromTo = getFromToFields(innerKey, innerValue, fromToInnerMap);
if (Array.isArray(innerValue)) {
const findedOneEntry = getOneEntryArrayFields(innerKey, innerValue);
if (findedOneEntry.key) {
delete valueObject[innerKey];
valueObject[findedOneEntry.key] = findedOneEntry.value;
}
else {
valueObject[innerKey] = findedOneEntry.value;
}
}
else if (!isFromTo) {
valueObject[innerKey] = innerValue;
}
}
}
fromToInnerMap.forEach((item, innerKey) => {
if (item.fromFieldValue && item.toFieldValue) {
valueObject[innerKey] = And(MoreThanOrEqual(item.fromFieldValue), LessThanOrEqual(item.toFieldValue));
}
else if (item.fromFieldValue) {
valueObject[innerKey] = MoreThanOrEqual(item.fromFieldValue);
}
else if (item.toFieldValue) {
valueObject[innerKey] = LessThanOrEqual(item.toFieldValue);
}
});
currentValue = valueObject;
}
else if (typeof value === 'boolean') {
currentValue = value;
}
else {
const isFromTo = getFromToFields(key, value, fromToMap);
if (Array.isArray(value)) {
const findedOneEntry = getOneEntryArrayFields(key, value);
if (findedOneEntry.key) {
currentKey = findedOneEntry.key;
}
currentValue = findedOneEntry.value;
}
else if (!isFromTo) {
currentValue = value;
}
}
if (currentValue !== undefined) {
whereAnd = {
...whereAnd,
[currentKey]: currentValue,
};
whereOr = [
...whereOr,
{
[currentKey]: currentValue,
},
];
}
}
fromToMap.forEach((item, key) => {
if (item.fromFieldValue && item.toFieldValue) {
whereAnd = {
...whereAnd,
[key]: And(MoreThanOrEqual(item.fromFieldValue), LessThanOrEqual(item.toFieldValue)),
};
whereOr = [
...whereOr,
{ [key]: And(MoreThanOrEqual(item.fromFieldValue), LessThanOrEqual(item.toFieldValue)) },
];
}
else if (item.fromFieldValue) {
whereAnd = {
...whereAnd,
[key]: MoreThanOrEqual(item.fromFieldValue),
};
whereOr = [...whereOr, { [key]: MoreThanOrEqual(item.fromFieldValue) }];
}
else if (item.toFieldValue) {
whereAnd = {
...whereAnd,
[key]: LessThanOrEqual(item.toFieldValue),
};
whereOr = [...whereOr, { [key]: LessThanOrEqual(item.toFieldValue) }];
}
});
if (filterType?.toLowerCase() === 'or')
return whereOr;
else
return whereAnd;
}
if (parsedCursor) {
const getCursorVal = (fieldName, index) => {
if (fieldName === 'id') {
return parsedCursor.id;
}
if (parsedCursor.sortValues && parsedCursor.sortValues[fieldName] !== undefined) {
return parsedCursor.sortValues[fieldName];
}
if (index === 0 && parsedCursor.sortValue !== undefined) {
return parsedCursor.sortValue;
}
return undefined;
};
const cursorConditions = [];
const entriesWithValues = [];
effectiveSortFields.forEach((item, idx) => {
const val = getCursorVal(item.field, idx);
if (val !== undefined && val !== null) {
entriesWithValues.push({ field: item.field, order: item.order, value: val });
}
});
if (entriesWithValues.length === 0) {
entriesWithValues.push({
field: 'id',
order: (sortOrder || parsedCursor.order || 'desc').toLowerCase() === 'desc' ? 'desc' : 'asc',
value: parsedCursor.id,
});
}
for (let i = 0; i < entriesWithValues.length; i++) {
const branch = {};
for (let j = 0; j < i; j++) {
branch[entriesWithValues[j].field] = entriesWithValues[j].value;
}
const current = entriesWithValues[i];
branch[current.field] =
current.order === 'desc' ? LessThan(current.value) : MoreThan(current.value);
cursorConditions.push(branch);
}
if (!queryData.where) {
queryData.where = cursorConditions.length === 1 ? cursorConditions[0] : cursorConditions;
}
else if (Array.isArray(queryData.where)) {
const combined = [];
for (const whereCond of queryData.where) {
for (const cursorCond of cursorConditions) {
combined.push({
...whereCond,
...cursorCond,
});
}
}
queryData.where = combined;
}
else {
if (cursorConditions.length === 1) {
queryData.where = {
...queryData.where,
...cursorConditions[0],
};
}
else {
queryData.where = cursorConditions.map((cond) => ({
...queryData.where,
...cond,
}));
}
}
}
if (fields && relationsMap) {
const filterKeys = filter ? Object.keys(filter) : [];
const extraFilterKeys = filters?.flatMap((f) => Object.keys(f)) ?? [];
const allFilterKeys = [...new Set([...filterKeys, ...extraFilterKeys])];
const relations = [];
for (const [entityKey, relationValue] of Object.entries(relationsMap)) {
const inFields = fields.includes(`data.${entityKey}`);
const inFilterKeys = allFilterKeys.includes(entityKey);
if (inFields || inFilterKeys) {
if (Array.isArray(relationValue)) {
relations.push(...relationValue);
}
else {
relations.push(relationValue);
}
}
}
if (relations.length) {
queryData.relations = relations;
}
}
return queryData;
};
export const extractGraphqlFields = (info) => {
const processSelections = (selections, parentPath = '') => {
const fields = [];
selections.forEach((selection) => {
if (selection.kind === 'Field') {
const fieldName = selection.name.value;
const currentPath = parentPath ? `${parentPath}.${fieldName}` : fieldName;
fields.push(currentPath);
if (selection.selectionSet) {
fields.push(...processSelections(selection.selectionSet.selections, currentPath));
}
}
});
return fields;
};
const rootSelections = info.fieldNodes[0].selectionSet?.selections;
if (!rootSelections) {
return [];
}
return processSelections(rootSelections);
};
export const prepareTempImages = (files, tempImages) => {
const images = files
.map((item) => {
const { imageName, originalFileExtension, fileExtensions, prefixes, entityId, fullPathExample, } = item;
const finded = tempImages.find((tempImage) => tempImage.tempName === `${imageName}.${originalFileExtension}`);
if (!finded)
return null;
return {
name: imageName,
fileExtensions,
prefixes,
originalFileExtension,
entityId,
fullPathExample,
altRU: finded.altRU,
altEN: finded.altEN,
altAR: finded.altAR,
};
})
.filter((item) => item !== null);
return images;
};
export const getTempImagesInAllImages = (allImages) => {
if (!allImages)
return [];
const tempImages = allImages
.map((item) => {
if (!item.tempName)
return null;
return {
tempName: item.tempName,
altRU: item.altRU,
altEN: item.altEN,
altAR: item.altAR,
};
})
.filter((item) => item !== null);
return tempImages;
};
export const getTempFilesInAllFiles = (allFiles) => {
if (!allFiles)
return [];
const tempFiles = allFiles
.map((item) => {
if (!item.tempName)
return null;
return {
tempName: item.tempName,
};
})
.filter((item) => item !== null);
return tempFiles;
};
export const prepareImages = (images) => {
const schema = z
.object({
name: z.string(),
fileExtensions: z.string().array().optional(),
prefixes: z.string().array().optional(),
originalFileExtension: z.string(),
entityId: z.string().uuid(),
fullPathExample: z.string(),
folder: z.string().optional(),
altRU: z.string().optional().nullable(),
altEN: z.string().optional().nullable(),
altAR: z.string().optional().nullable(),
})
.array();
try {
const data = JSON.parse(images);
if (!Array.isArray(data))
return [];
schema.parse(data);
return data;
}
catch (error) {
getError({ error });
return [];
}
};
export const updateEntityImages = (entityImages, allImages, preparedTempImages) => {
if ((!entityImages && !preparedTempImages.length) || !allImages) {
return {
newImages: null,
deletedImages: null,
};
}
let correctedImages = [];
const deletedImages = [];
const allImagesAndOrders = allImages.map((item, index) => {
return {
...item,
order: index,
};
});
if (entityImages) {
let images = [];
try {
const parsed = JSON.parse(entityImages);
if (Array.isArray(parsed)) {
images = parsed;
}
}
catch {
images = [];
}
const schema = z.object({
name: z.string(),
fileExtensions: z.string().array().optional(),
prefixes: z.string().array().optional(),
originalFileExtension: z.string(),
entityId: z.string().uuid(),
fullPathExample: z.string(),
folder: z.string().optional(),
altRU: z.string().optional().nullable(),
altEN: z.string().optional().nullable(),
altAR: z.string().optional().nullable(),
});
if (!images.length) {
return {
newImages: null,
deletedImages: null,
};
}
correctedImages = images
.map((item) => {
try {
schema.parse(item);
}
catch {
return null;
}
const finded = allImagesAndOrders.find((element) => element.name === item.name);
if (!finded) {
deletedImages.push({
imageName: item.name,
fileExtensions: item.fileExtensions,
prefixes: item.prefixes,
entityId: item.entityId,
folder: item.folder,
fullPathExample: item.fullPathExample,
originalFileExtension: item.originalFileExtension,
});
return null;
}
return {
name: item.name,
fileExtensions: item.fileExtensions,
prefixes: item.prefixes,
originalFileExtension: item.originalFileExtension,
entityId: item.entityId,
fullPathExample: item.fullPathExample,
folder: item.folder,
altRU: finded.altRU,
altEN: finded.altEN,
altAR: finded.altAR,
order: finded.order,
};
})
.filter((item) => item !== null);
}
const preparedTempImagesAndOrder = preparedTempImages
.map((item) => {
const finded = allImagesAndOrders.find((element) => element.tempName === `${item.name}.${item.originalFileExtension}`);
if (!finded)
return null;
return {
...item,
order: finded.order,
};
})
.filter((item) => item !== null);
const newImages = [...correctedImages, ...preparedTempImagesAndOrder]
.sort((a, b) => a.order - b.order)
.map((item) => {
return {
name: item.name,
fileExtensions: item.fileExtensions,
prefixes: item.prefixes,
originalFileExtension: item.originalFileExtension,
entityId: item.entityId,
folder: item.folder,
fullPathExample: item.fullPathExample,
altRU: item.altRU,
altEN: item.altEN,
altAR: item.altAR,
};
});
return {
newImages: newImages.length ? newImages : null,
deletedImages: deletedImages.length ? deletedImages : null,
};
};
export const updateEntityFiles = (entityFiles, allFiles, preparedTempFiles) => {
if ((!entityFiles && !preparedTempFiles.length) || !allFiles) {
return {
newFiles: null,
deletedFiles: null,
};
}
let correctedFiles = [];
const deletedFiles = [];
const allFilesAndOrders = allFiles.map((item, index) => {
return {
...item,
order: index,
};
});
if (entityFiles) {
let files = [];
try {
const parsed = JSON.parse(entityFiles);
if (Array.isArray(parsed)) {
files = parsed;
}
}
catch {
files = [];
}
const schema = z.object({
name: z.string(),
fullName: z.string(),
extension: z.string(),
entityId: z.string().uuid(),
fullPathExample: z.string(),
folder: z.string().optional(),
});
if (!files.length) {
return {
newFiles: null,
deletedFiles: null,
};
}
correctedFiles = files
.map((item) => {
try {
schema.parse(item);
}
catch {
return null;
}
const finded = allFilesAndOrders.find((element) => element.name === item.name);
if (!finded) {
deletedFiles.push({
name: item.name,
fullName: item.fullName,
extension: item.extension,
entityId: item.entityId,
fullPathExample: item.fullPathExample,
folder: item.folder,
});
return null;
}
return {
name: item.name,
fullName: item.fullName,
extension: item.extension,
entityId: item.entityId,
fullPathExample: item.fullPathExample,
folder: item.folder,
order: finded.order,
};
})
.filter((item) => item !== null);
}
const preparedTempFilesAndOrder = preparedTempFiles
.map((item) => {
const finded = allFilesAndOrders.find((element) => element.tempName === item.fullName);
if (!finded)
return null;
return {
...item,
order: finded.order,
};
})
.filter((item) => item !== null);
const newFiles = [...correctedFiles, ...preparedTempFilesAndOrder]
.sort((a, b) => a.order - b.order)
.map((item) => {
return {
name: item.name,
fullName: item.fullName,
extension: item.extension,
entityId: item.entityId,
fullPathExample: item.fullPathExample,
folder: item.folder,
};
});
return {
newFiles: newFiles.length ? newFiles : null,
deletedFiles: deletedFiles.length ? deletedFiles : null,
};
};
export const translit = (word, isTrim = true) => {
const converter = {
а: 'a',
б: 'b',
в: 'v',
г: 'g',
д: 'd',
е: 'e',
ё: 'e',
ж: 'zh',
з: 'z',
и: 'i',
й: 'y',
к: 'k',
л: 'l',
м: 'm',
н: 'n',
о: 'o',
п: 'p',
р: 'r',
с: 's',
т: 't',
у: 'u',
ф: 'f',
х: 'h',
ц: 'c',
ч: 'ch',
ш: 'sh',
щ: 'sch',
ь: '',
ы: 'y',
ъ: '',
э: 'e',
ю: 'yu',
я: 'ya',
};
word = word.toLowerCase();
let answer = '';
for (let i = 0; i < word.length; ++i) {
if (converter[word[i]] == undefined) {
answer += word[i];
}
else {
answer += converter[word[i]];
}
}
answer = answer.replace(/[^-0-9a-z]/g, '-');
answer = answer.replace(/[-]+/g, '-');
if (isTrim)
answer = answer.replace(/^-|-$/g, '');
return answer;
};
export const checkTranslit = (string) => {
const cpuRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
return cpuRegex.test(string);
};
export const prepareRequestContext = (context) => {
const reqType = context.getType();
if (reqType === 'graphql') {
const gqlCtx = GqlExecutionContext.create(context);
const ctx = gqlCtx.getContext();
return ctx.req;
}
else {
const httpReq = context.switchToHttp().getRequest();
return httpReq;
}
};
export const getGuardAuthContext = (context) => {
const reqType = context.getType();
if (reqType === 'graphql') {
const gqlCtx = GqlExecutionContext.create(context);
const ctx = gqlCtx.getContext();
let authHeader;
if (ctx.connectionParams?.Authorization) {
authHeader = ctx.connectionParams.Authorization;
}
else if (ctx.req?.headers?.authorization) {
authHeader = ctx.req.headers.authorization;
}
return { request: ctx.req ?? {}, authHeader };
}
const request = context.switchToHttp().getRequest();
return { request, authHeader: request.headers?.authorization };
};
export const getRandomNumber = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
export const getUniqueNumber = () => {
const stringNumber = new Date()
.getTime()
.toString()
.replace(/(\d{4})(?=\d)/g, '$1-');
const array = stringNumber.split('-');
return `${array[0] ?? getRandomNumber(1_000, 9_999)}-${array[1] ?? getRandomNumber(1_000, 9_999)}-${array[2] ?? getRandomNumber(1_000, 9_999)}-${getRandomNumber(1_000, 9_999)}`;
};
export const createValue = (name, parameters, initialValue, isDateTime = true) => {
const isTranslitName = checkTranslit(name);
const dateTime = initialValue ? initialValue.split('-').at(-1) : new Date().getTime();
const correctName = isTranslitName
? name.toLocaleLowerCase().replace(/_/g, '-').replace(/ /g, '-')
: translit(name).toLocaleLowerCase().replace(/_/g, '-').replace(/ /g, '-');
const correctParameters = parameters
.map((item) => {
const isTranslitParameter = checkTranslit(item);
return isTranslitParameter
? item.toLocaleLowerCase().replace(/_/g, '-').replace(/ /g, '-')
: translit(item).toLocaleLowerCase().replace(/_/g, '-').replace(/ /g, '-');
})
.join('-');
return `${correctName}${correctParameters ? `-${correctParameters}` : ''}${isDateTime ? `-${dateTime}` : ''}`;
};
export const compareRolesPriority = ({ userRoles, comparedUserRoles, rolePriority, }) => {
const maxUserRolePriority = userRoles.reduce((acc, value) => {
const priority = rolePriority[value];
if (priority !== undefined && priority > acc) {
return priority;
}
return acc;
}, 0);
const maxComparedUserRolePriority = comparedUserRoles.reduce((acc, value) => {
const priority = rolePriority[value];
if (priority !== undefined && priority > acc) {
return priority;
}
return acc;
}, 0);
return {
maxUserRolePriority,
maxComparedUserRolePriority,
isPriorityHigher: maxUserRolePriority > maxComparedUserRolePriority,
isPriorityEqual: maxUserRolePriority === maxComparedUserRolePriority,
isPriorityLower: maxUserRolePriority < maxComparedUserRolePriority,
};
};
export const htmlToSlateString = (html) => {
try {
const dom = new JSDOM(html);
const paragraphs = dom.window.document.querySelectorAll('p');
return JSON.stringify([...paragraphs].map((p) => ({
type: 'paragraph',
children: [{ text: p.textContent?.trim() || '' }],
})));
}
catch {
return JSON.stringify([{ type: 'paragraph', children: [{ text: '' }] }]);
}
};
const getServerUploadImageUrl = ({ name, extension, entityId, bucketFolder, prefixe, uploadUrl, folder, }) => {
return `${uploadUrl}/${bucketFolder}/${entityId}${folder ? `/${folder}` : ''}/${name}-${prefixe}.${extension}`;
};
export const escapeHtml = (string) => {
const matchHtmlRegExp = /["'&<>]/;
const str = '' + string;
const match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
let escape;
let html = '';
let index;
let lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34:
escape = '"';
break;
case 38:
escape = '&';
break;
case 39:
escape = ''';
break;
case 60:
escape = '<';
break;
case 62:
escape = '>';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
};
export const serializeContentToHtml = ({ content, contentImages, uploadUrl, bucketFolder, }) => {
const serializeNode = (node) => {
if ('text' in node && typeof node.text === 'string') {
let string = escapeHtml(node.text);
if (node.bold) {
string = `<strong>${string}</strong>`;
}
if (node.italic) {
string = `<em>${string}</em>`;
}
if (node.underline) {
string = `<u>${string}</u>`;
}
return string;
}
const children = node.children?.map((n) => serializeNode(n)).join('') ?? '';
const style = node.align ? ` style="text-align: ${node.align}"` : '';
switch (node.type) {
case 'title':
return `<h2${style}>${children}</h2>`;
case 'subtitle':
return `<h3${style}>${children}</h3>`;
case 'note':
return `<p${style}>${children}</p>`;
case 'info':
return `<p${style}>${children}</p>`;
case 'paragraph':
return `<p${style}>${children}</p>`;
case 'bulleted-list':
return `<ul${style}>${children}</ul>`;
case 'numbered-list':
return `<ol${style}>${children}</ol>`;
case 'list-item':
return `<li${style}>${children}</li>`;
case 'link':
return `<a href="${escapeHtml(node.href ?? '')}">${children}</a>`;
case 'image': {
const alt = escapeHtml(node.alt ?? '');
const imageUrl = typeof node.url === 'string' ? node.url : '';
const matchedImage = contentImages.find((img) => {
if (!imageUrl)
return false;
return imageUrl.includes(`/${img.name}.`) || imageUrl.includes(img.name);
});
if (matchedImage) {
const originalPrefix = matchedImage.prefixes?.[0] ?? 'original';
const generateUrl = (extension, prefixe) => getServerUploadImageUrl({
name: matchedImage.name,
extension,
entityId: matchedImage.entityId,
bucketFolder,
prefixe,
uploadUrl,
folder: matchedImage.folder,
});
const image1x = generateUrl(matchedImage.originalFileExtension, originalPrefix);
const image1xWebp = matchedImage.fileExtensions?.includes('webp')
? generateUrl('webp', originalPrefix)
: '';
const image1xAvif = matchedImage.fileExtensions?.includes('avif')
? generateUrl('avif', originalPrefix)
: '';
const sources = [];
if (image1xAvif) {
sources.push(`<source srcset="${escapeHtml(image1xAvif)}" type="image/avif" />`);
}
if (image1xWebp) {
sources.push(`<source srcset="${escapeHtml(image1xWebp)}" type="image/webp" />`);
}
sources.push(`<source srcset="${escapeHtml(image1x)}" />`);
return `<picture>${sources.join('')}<img src="${escapeHtml(image1x)}" alt="${alt}" loading="lazy" /></picture>`;
}
return `<img src="${escapeHtml(imageUrl)}" alt="${alt}" />`;
}
default:
return children;
}
};
const parseContent = () => {
if (!content)
return [];
try {
const parsed = JSON.parse(content);
if (Array.isArray(parsed))
return parsed;
if (parsed && typeof parsed === 'object' && 'children' in parsed) {
return parsed.children;
}
return [];
}
catch {
return [];
}
};
const nodes = parseContent();
return nodes.map((node) => serializeNode(node)).join('');
};
export const extractImageUrlsFromContent = (contentJson) => {
if (!contentJson)
return [];
try {
const parsed = JSON.parse(contentJson);
let nodes;
if (Array.isArray(parsed)) {
nodes = parsed;
}
else if (parsed && typeof parsed === 'object' && 'children' in parsed) {
nodes = parsed.children;
}
else {
return [];
}
const urls = [];
const traverse = (items) => {
for (const node of items) {
if (node.type === 'image' && node.url) {
urls.push(node.url);
}
if (node.children?.length) {
traverse(node.children);
}
}
};
traverse(nodes);
return urls;
}
catch {
return [];
}
};
export const cleanContentImages = (contentJson, contentImages) => {
if (!contentJson || !contentImages)
return contentImages ?? null;
try {
const imageUrls = extractImageUrlsFromContent(contentJson);
if (!imageUrls.length)
return null;
const parsed = JSON.parse(contentImages);
if (!Array.isArray(parsed) || !parsed.length)
return null;
const cleaned = parsed.filter((img) => {
const name = img.name;
if (!name)
return false;
return imageUrls.some((url) => url.includes(`/${name}.`) || url.includes(name));
});
return cleaned.length ? JSON.stringify(cleaned) : null;
}
catch {
return contentImages ?? null;
}
};
//# sourceMappingURL=lib.js.map