Skip to content

Commit

Permalink
feat: apply browser and script validations to form
Browse files Browse the repository at this point in the history
  • Loading branch information
VikaCep committed Jul 17, 2024
1 parent a2c93cb commit ccb8d20
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 23 deletions.
10 changes: 7 additions & 3 deletions src/schemas/forms/BrowserCheckSchema.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import { z, ZodType } from 'zod';

import { CheckFormValuesBrowser, CheckType } from 'types';
import { BrowserSettings, CheckFormValuesBrowser, CheckType } from 'types';

import { maxSizeValidation, validateBrowserScript } from './script/validation';
import { BaseCheckSchema } from './BaseCheckSchema';
import { ScriptedSettingsSchema } from './ScriptedCheckSchema';

const BrowserSettingsSchema: ZodType<BrowserSettings> = z.object({
script: z.string().min(1, `Script is required.`).superRefine(maxSizeValidation).superRefine(validateBrowserScript),
});

const BrowserSchemaValues = z.object({
target: z.string().min(3, `Instance must be at lesat 3 characters long.`),
checkType: z.literal(CheckType.Browser),
settings: z.object({
browser: ScriptedSettingsSchema,
browser: BrowserSettingsSchema,
}),
});

Expand Down
22 changes: 2 additions & 20 deletions src/schemas/forms/ScriptedCheckSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,11 @@ import { z, ZodType } from 'zod';

import { CheckFormValuesScripted, CheckType, ScriptedSettings } from 'types';

import { maxSizeValidation, validateNonBrowserScript } from './script/validation';
import { BaseCheckSchema } from './BaseCheckSchema';

const MAX_SCRIPT_IN_KB = 128;

/** Important: this schema is also used in `BrowserCheckSchema.ts`
* If you change this schema, make sure to update the other file as well (if they start to diverge).
* */
export const ScriptedSettingsSchema: ZodType<ScriptedSettings> = z.object({
script: z
.string()
.min(1, `Script is required.`)
.superRefine((val, ctx) => {
const textBlob = new Blob([val], { type: 'text/plain' });
const sizeInBytes = textBlob.size;
const sizeInKb = sizeInBytes / 1024;

if (sizeInKb > MAX_SCRIPT_IN_KB) {
return ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Script is too big (${sizeInKb.toFixed(2)}kb). Maximum size is ${MAX_SCRIPT_IN_KB}kb.`,
});
}
}),
script: z.string().min(1, `Script is required.`).superRefine(maxSizeValidation).superRefine(validateNonBrowserScript),
});

const ScriptedSchemaValues = z.object({
Expand Down

0 comments on commit ccb8d20

Please sign in to comment.