"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IsGreaterThanOrEqualTo = exports.IsGreaterThanOrEqualToConstraint = exports.isValidInteger = exports.toSanitized = exports.toEmail = exports.IsCronExpression = exports.ValidateEnum = exports.ValidateBoolean = exports.ValidateString = exports.ValidateDate = exports.ValidateHexColor = exports.PinCode = exports.FilenameParamDto = exports.UUIDAssetIDParamDto = exports.UUIDParamDto = exports.IsUniqueEditActions = exports.ValidateUUID = exports.FileNotEmptyValidator = exports.ParseMeUUIDPipe = void 0;
exports.IsAxisAlignedRotation = IsAxisAlignedRotation;
exports.Optional = Optional;
exports.IsNotSiblingOf = IsNotSiblingOf;
exports.isDateStringFormat = isDateStringFormat;
exports.IsDateStringFormat = IsDateStringFormat;
exports.MaxDateString = MaxDateString;
exports.IsIPRange = IsIPRange;
const common_1 = require("@nestjs/common");
const swagger_1 = require("@nestjs/swagger");
const class_transformer_1 = require("class-transformer");
const class_validator_1 = require("class-validator");
const cron_1 = require("cron");
const luxon_1 = require("luxon");
const sanitize_filename_1 = __importDefault(require("sanitize-filename"));
const decorators_1 = require("./decorators");
const validator_1 = require("validator");
let ParseMeUUIDPipe = class ParseMeUUIDPipe extends common_1.ParseUUIDPipe {
    async transform(value, metadata) {
        if (value == 'me') {
            return value;
        }
        return super.transform(value, metadata);
    }
};
exports.ParseMeUUIDPipe = ParseMeUUIDPipe;
exports.ParseMeUUIDPipe = ParseMeUUIDPipe = __decorate([
    (0, common_1.Injectable)()
], ParseMeUUIDPipe);
let FileNotEmptyValidator = class FileNotEmptyValidator extends common_1.FileValidator {
    requiredFields;
    constructor(requiredFields) {
        super({});
        this.requiredFields = requiredFields;
        this.requiredFields = requiredFields;
    }
    isValid(files) {
        if (!files) {
            return false;
        }
        return this.requiredFields.every((field) => files[field]);
    }
    buildErrorMessage() {
        return `Field(s) ${this.requiredFields.join(', ')} should not be empty`;
    }
};
exports.FileNotEmptyValidator = FileNotEmptyValidator;
exports.FileNotEmptyValidator = FileNotEmptyValidator = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [Array])
], FileNotEmptyValidator);
const ValidateUUID = (options) => {
    const { optional, each, nullable, ...apiPropertyOptions } = {
        optional: false,
        each: false,
        nullable: false,
        ...options,
    };
    return (0, common_1.applyDecorators)((0, class_validator_1.IsUUID)('4', { each }), (0, decorators_1.Property)({ format: 'uuid', ...apiPropertyOptions }), optional ? Optional({ nullable }) : (0, class_validator_1.IsNotEmpty)(), each ? (0, class_validator_1.IsArray)() : (0, class_validator_1.IsString)());
};
exports.ValidateUUID = ValidateUUID;
function IsAxisAlignedRotation() {
    return (0, class_validator_1.ValidateBy)({
        name: 'isAxisAlignedRotation',
        validator: {
            validate(value) {
                return [0, 90, 180, 270].includes(value);
            },
            defaultMessage: (0, class_validator_1.buildMessage)((eachPrefix) => eachPrefix + '$property must be one of the following values: 0, 90, 180, 270', {}),
        },
    }, {});
}
let UniqueEditActionsValidator = class UniqueEditActionsValidator {
    validate(edits) {
        if (!Array.isArray(edits)) {
            return true;
        }
        const actionSet = new Set();
        for (const edit of edits) {
            const key = edit.action === 'mirror' ? `${edit.action}-${JSON.stringify(edit.parameters)}` : edit.action;
            if (actionSet.has(key)) {
                return false;
            }
            actionSet.add(key);
        }
        return true;
    }
    defaultMessage() {
        return 'Duplicate edit actions are not allowed';
    }
};
UniqueEditActionsValidator = __decorate([
    (0, class_validator_1.ValidatorConstraint)({ name: 'uniqueEditActions' })
], UniqueEditActionsValidator);
const IsUniqueEditActions = () => (0, class_validator_1.Validate)(UniqueEditActionsValidator);
exports.IsUniqueEditActions = IsUniqueEditActions;
class UUIDParamDto {
    id;
}
exports.UUIDParamDto = UUIDParamDto;
__decorate([
    (0, class_validator_1.IsNotEmpty)(),
    (0, class_validator_1.IsUUID)('4'),
    (0, swagger_1.ApiProperty)({ format: 'uuid' }),
    __metadata("design:type", String)
], UUIDParamDto.prototype, "id", void 0);
class UUIDAssetIDParamDto {
    id;
    assetId;
}
exports.UUIDAssetIDParamDto = UUIDAssetIDParamDto;
__decorate([
    (0, exports.ValidateUUID)(),
    __metadata("design:type", String)
], UUIDAssetIDParamDto.prototype, "id", void 0);
__decorate([
    (0, exports.ValidateUUID)(),
    __metadata("design:type", String)
], UUIDAssetIDParamDto.prototype, "assetId", void 0);
class FilenameParamDto {
    filename;
}
exports.FilenameParamDto = FilenameParamDto;
__decorate([
    (0, class_validator_1.IsNotEmpty)(),
    (0, class_validator_1.IsString)(),
    (0, swagger_1.ApiProperty)({ format: 'string' }),
    (0, class_validator_1.Matches)(/^[a-zA-Z0-9_\-.]+$/, {
        message: 'Filename contains invalid characters',
    }),
    __metadata("design:type", String)
], FilenameParamDto.prototype, "filename", void 0);
const PinCode = (options) => {
    const { optional, nullable, emptyToNull, ...apiPropertyOptions } = {
        optional: false,
        nullable: false,
        emptyToNull: false,
        ...options,
    };
    const decorators = [
        (0, class_validator_1.IsString)(),
        (0, class_validator_1.IsNotEmpty)(),
        (0, class_validator_1.Matches)(/^\d{6}$/, { message: ({ property }) => `${property} must be a 6-digit numeric string` }),
        (0, swagger_1.ApiProperty)({ example: '123456', ...apiPropertyOptions }),
    ];
    if (optional) {
        decorators.push(Optional({ nullable, emptyToNull }));
    }
    return (0, common_1.applyDecorators)(...decorators);
};
exports.PinCode = PinCode;
function Optional({ nullable, emptyToNull, ...validationOptions } = {}) {
    const decorators = [];
    if (nullable === true) {
        decorators.push((0, class_validator_1.IsOptional)(validationOptions));
    }
    else {
        decorators.push((0, class_validator_1.ValidateIf)((object, v) => v !== undefined, validationOptions));
    }
    if (emptyToNull) {
        decorators.push((0, class_transformer_1.Transform)(({ value }) => (value === '' ? null : value)));
    }
    return (0, common_1.applyDecorators)(...decorators);
}
function IsNotSiblingOf(siblings, validationOptions) {
    return (0, class_validator_1.ValidateBy)({
        name: 'isNotSiblingOf',
        constraints: siblings,
        validator: {
            validate(value, args) {
                if (!(0, class_validator_1.isDefined)(value)) {
                    return true;
                }
                return args.constraints.filter((prop) => (0, class_validator_1.isDefined)(args.object[prop])).length === 0;
            },
            defaultMessage: (args) => {
                return `${args.property} cannot exist alongside any of the following properties: ${args.constraints.join(', ')}`;
            },
        },
    }, validationOptions);
}
const ValidateHexColor = () => {
    const decorators = [
        (0, class_validator_1.IsHexColor)(),
        (0, class_transformer_1.Transform)(({ value }) => (typeof value === 'string' && value[0] !== '#' ? `#${value}` : value)),
    ];
    return (0, common_1.applyDecorators)(...decorators);
};
exports.ValidateHexColor = ValidateHexColor;
const ValidateDate = (options) => {
    const { optional, nullable = false, emptyToNull = false, format = 'date-time', ...apiPropertyOptions } = options || {};
    return (0, common_1.applyDecorators)((0, decorators_1.Property)({ format, ...apiPropertyOptions }), (0, class_validator_1.IsDate)(), optional ? Optional({ nullable, emptyToNull }) : (0, class_validator_1.IsNotEmpty)(), (0, class_transformer_1.Transform)(({ key, value }) => {
        if (value === null || value === undefined) {
            return value;
        }
        if (!(0, class_validator_1.isDateString)(value)) {
            throw new common_1.BadRequestException(`${key} must be a date string`);
        }
        return new Date(value);
    }));
};
exports.ValidateDate = ValidateDate;
const ValidateString = (options) => {
    const { optional, nullable, emptyToNull, trim, ...apiPropertyOptions } = options || {};
    const decorators = [
        (0, swagger_1.ApiProperty)(apiPropertyOptions),
        (0, class_validator_1.IsString)(),
        optional ? Optional({ nullable, emptyToNull }) : (0, class_validator_1.IsNotEmpty)(),
    ];
    if (trim) {
        decorators.push((0, class_transformer_1.Transform)(({ value }) => value?.trim()));
    }
    return (0, common_1.applyDecorators)(...decorators);
};
exports.ValidateString = ValidateString;
const ValidateBoolean = (options) => {
    const { optional, nullable, emptyToNull, ...apiPropertyOptions } = options || {};
    const decorators = [
        (0, decorators_1.Property)(apiPropertyOptions),
        (0, class_validator_1.IsBoolean)(),
        (0, class_transformer_1.Transform)(({ value }) => {
            if (value == 'true') {
                return true;
            }
            else if (value == 'false') {
                return false;
            }
            return value;
        }),
        optional ? Optional({ nullable, emptyToNull }) : (0, class_validator_1.IsNotEmpty)(),
    ];
    return (0, common_1.applyDecorators)(...decorators);
};
exports.ValidateBoolean = ValidateBoolean;
const ValidateEnum = ({ name, enum: value, each, optional, nullable, default: defaultValue, description, }) => {
    return (0, common_1.applyDecorators)(optional ? Optional({ nullable }) : (0, class_validator_1.IsNotEmpty)(), (0, class_validator_1.IsEnum)(value, { each }), (0, swagger_1.ApiProperty)({ enumName: name, enum: value, isArray: each, default: defaultValue, description }));
};
exports.ValidateEnum = ValidateEnum;
let CronValidator = class CronValidator {
    validate(expression) {
        try {
            new cron_1.CronJob(expression, () => { });
            return true;
        }
        catch {
            return false;
        }
    }
};
CronValidator = __decorate([
    (0, class_validator_1.ValidatorConstraint)({ name: 'cronValidator' })
], CronValidator);
const IsCronExpression = () => (0, class_validator_1.Validate)(CronValidator, { message: 'Invalid cron expression' });
exports.IsCronExpression = IsCronExpression;
const toEmail = ({ value }) => (typeof value === 'string' ? value.toLowerCase() : value);
exports.toEmail = toEmail;
const toSanitized = ({ value }) => {
    const input = typeof value === 'string' ? value : '';
    return (0, sanitize_filename_1.default)(input.replaceAll('.', ''));
};
exports.toSanitized = toSanitized;
const isValidInteger = (value, options) => {
    const { min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER } = options;
    return Number.isInteger(value) && value >= min && value <= max;
};
exports.isValidInteger = isValidInteger;
function isDateStringFormat(value, format) {
    if (typeof value !== 'string') {
        return false;
    }
    return luxon_1.DateTime.fromFormat(value, format, { zone: 'utc' }).isValid;
}
function IsDateStringFormat(format, validationOptions) {
    return (0, class_validator_1.ValidateBy)({
        name: 'isDateStringFormat',
        constraints: [format],
        validator: {
            validate(value) {
                return isDateStringFormat(value, format);
            },
            defaultMessage: () => `$property must be a string in the format ${format}`,
        },
    }, validationOptions);
}
function maxDate(date, maxDate) {
    return date <= (maxDate instanceof luxon_1.DateTime ? maxDate : maxDate());
}
function MaxDateString(date, validationOptions) {
    return (0, class_validator_1.ValidateBy)({
        name: 'maxDateString',
        constraints: [date],
        validator: {
            validate: (value, args) => {
                const date = luxon_1.DateTime.fromISO(value, { zone: 'utc' });
                return maxDate(date, args?.constraints[0]);
            },
            defaultMessage: (0, class_validator_1.buildMessage)((eachPrefix) => 'maximal allowed date for ' + eachPrefix + '$property is $constraint1', validationOptions),
        },
    }, validationOptions);
}
function IsIPRange(options, validationOptions) {
    const { requireCIDR } = { requireCIDR: true, ...options };
    return (0, class_validator_1.ValidateBy)({
        name: 'isIPRange',
        validator: {
            validate: (value) => {
                if ((0, validator_1.isIPRange)(value)) {
                    return true;
                }
                if (!requireCIDR && (0, validator_1.isIP)(value)) {
                    return true;
                }
                return false;
            },
            defaultMessage: (0, class_validator_1.buildMessage)((eachPrefix) => eachPrefix + '$property must be an ip address, or ip address range', validationOptions),
        },
    }, validationOptions);
}
let IsGreaterThanOrEqualToConstraint = class IsGreaterThanOrEqualToConstraint {
    validate(value, args) {
        const relatedPropertyName = args.constraints?.[0];
        const relatedValue = args.object[relatedPropertyName];
        if (!Number.isFinite(value) || !Number.isFinite(relatedValue)) {
            return true;
        }
        return Number(value) >= Number(relatedValue);
    }
    defaultMessage(args) {
        const relatedPropertyName = args.constraints?.[0];
        return `${args.property} must be greater than or equal to ${relatedPropertyName}`;
    }
};
exports.IsGreaterThanOrEqualToConstraint = IsGreaterThanOrEqualToConstraint;
exports.IsGreaterThanOrEqualToConstraint = IsGreaterThanOrEqualToConstraint = __decorate([
    (0, class_validator_1.ValidatorConstraint)({ name: 'isGreaterThanOrEqualTo' })
], IsGreaterThanOrEqualToConstraint);
const IsGreaterThanOrEqualTo = (property, validationOptions) => {
    return (0, class_validator_1.Validate)(IsGreaterThanOrEqualToConstraint, [property], validationOptions);
};
exports.IsGreaterThanOrEqualTo = IsGreaterThanOrEqualTo;
//# sourceMappingURL=validation.js.map