@open-formulieren/formio-builder
Version:
An opinionated Formio webform builder for Open Forms
68 lines (67 loc) • 2.58 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const zod_1 = require("zod");
const validation_1 = require("../../registry/validation");
// Reference: formio's file component translateScalars method, but without the weird
// units that don't make sense for files...
const TRANSFORMATIONS = {
B: Math.pow(1024, 0),
KB: Math.pow(1024, 1),
MB: Math.pow(1024, 2),
GB: Math.pow(1024, 3),
};
const getSizeInBytes = (filesize) => {
const match = /^(\d+)\s*(B|KB|MB|GB)?$/i.exec(filesize);
if (match === null) {
return null;
}
const size = parseInt(match[1], 10);
const unit = (match[2] || 'B').toUpperCase();
return size * TRANSFORMATIONS[unit];
};
const imgSize = zod_1.z.number().int().positive();
const ofSchema = zod_1.z.object({
image: zod_1.z
.object({
resize: zod_1.z
.object({
apply: zod_1.z.boolean().optional(),
width: imgSize.optional(),
height: imgSize.optional(),
})
.optional(),
})
.optional(),
});
const buildFileMaxSizeSchema = (intl, builderContext) => {
var _a;
const { serverUploadLimit } = builderContext;
const serverLimitInBytes = (_a = getSizeInBytes(serverUploadLimit)) !== null && _a !== void 0 ? _a : Number.MAX_SAFE_INTEGER;
return zod_1.z
.string()
.transform((val, ctx) => {
const sizeInBytes = getSizeInBytes(val);
if (sizeInBytes === null) {
ctx.addIssue({
code: zod_1.z.ZodIssueCode.custom,
message: intl.formatMessage({ id: "QW32Dd", defaultMessage: [{ type: 0, value: "Specify a positive, non-zero file size without decimals, e.g. 10MB." }] }),
});
return zod_1.z.NEVER;
}
return sizeInBytes;
})
.refine(value => value <= serverLimitInBytes, {
message: intl.formatMessage({ id: "5/jkH9", defaultMessage: [{ type: 0, value: "Specify a file size less than or equal to the server upload limit." }] }),
});
};
const buildFileSchema = (intl, builderContext) => zod_1.z.object({
of: ofSchema.optional(),
maxNumberOfFiles: zod_1.z.union([zod_1.z.null(), zod_1.z.number().int().positive().optional()]),
fileMaxSize: buildFileMaxSizeSchema(intl, builderContext).optional(),
});
const schema = ({ intl, builderContext }) => {
const common = (0, validation_1.buildCommonSchema)(intl);
const fileSpecific = buildFileSchema(intl, builderContext);
return common.and(fileSpecific);
};
exports.default = schema;