Save current BZZZ config-ui state before CHORUS branding update

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
anthonyrawlins
2025-08-19 00:19:00 +10:00
parent 6a6a49b7b1
commit c177363a19
16410 changed files with 1789161 additions and 230 deletions

View File

@@ -0,0 +1,17 @@
{
"name": "@hookform/resolvers/joi",
"amdName": "hookformResolversJoi",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: joi",
"main": "dist/joi.js",
"module": "dist/joi.module.js",
"umd:main": "dist/joi.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": "^7.0.0",
"@hookform/resolvers": "^2.0.0"
}
}

View File

@@ -0,0 +1,85 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import * as Joi from 'joi';
import React from 'react';
import { useForm } from 'react-hook-form';
import { joiResolver } from '..';
const schema = Joi.object({
username: Joi.string().required(),
password: Joi.string().required(),
});
interface FormData {
username: string;
password: string;
}
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: joiResolver(schema),
shouldUseNativeValidation: true,
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />
<input {...register('password')} placeholder="password" />
<button type="submit">submit</button>
</form>
);
}
test("form's native validation with Joi", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
await user.click(screen.getByText(/submit/i));
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe(
'"username" is not allowed to be empty',
);
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(
'"password" is not allowed to be empty',
);
await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});

View File

@@ -0,0 +1,59 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import * as Joi from 'joi';
import React from 'react';
import { useForm } from 'react-hook-form';
import { joiResolver } from '..';
const schema = Joi.object({
username: Joi.string().required(),
password: Joi.string().required(),
});
interface FormData {
username: string;
password: string;
}
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
formState: { errors },
handleSubmit,
} = useForm<FormData>({
resolver: joiResolver(schema), // Useful to check TypeScript regressions
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
}
test("form's validation with Joi and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
expect(screen.queryAllByRole('alert')).toHaveLength(0);
await user.click(screen.getByText(/submit/i));
expect(
screen.getByText(/"username" is not allowed to be empty/i),
).toBeInTheDocument();
expect(
screen.getByText(/"password" is not allowed to be empty/i),
).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

View File

@@ -0,0 +1,85 @@
import * as Joi from 'joi';
import { Field, InternalFieldName } from 'react-hook-form';
export const schema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string()
.pattern(new RegExp('.*[A-Z].*'), 'One uppercase character')
.pattern(new RegExp('.*[a-z].*'), 'One lowercase character')
.pattern(new RegExp('.*\\d.*'), 'One number')
.pattern(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
'One special character',
)
.min(8)
.required(),
repeatPassword: Joi.ref('password'),
accessToken: [Joi.string(), Joi.number()],
birthYear: Joi.number().integer().min(1900).max(2013),
email: Joi.string().email({
minDomainSegments: 2,
tlds: { allow: ['com', 'net'] },
}),
tags: Joi.array().items(Joi.string()).required(),
enabled: Joi.boolean().required(),
like: Joi.array()
.items(
Joi.object({ id: Joi.number(), name: Joi.string().length(4).regex(/a/) }),
)
.optional(),
});
interface Data {
username: string;
password: string;
repeatPassword: string;
accessToken?: number | string;
birthYear?: number;
email?: string;
tags: string[];
enabled: boolean;
like: { id: number; name: string }[];
}
export const validData: Data = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
like: [
{
id: 1,
name: 'name',
},
],
};
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z', name: 'r' }],
};
export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
name: 'username',
},
password: {
ref: { name: 'password' },
name: 'password',
},
email: {
ref: { name: 'email' },
name: 'email',
},
birthday: {
ref: { name: 'birthday' },
name: 'birthday',
},
};

View File

@@ -0,0 +1,293 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`joiResolver > should return a single error from joiResolver when validation fails 1`] = `
{
"errors": {
"birthYear": {
"message": ""birthYear" must be a number",
"ref": undefined,
"type": "number.base",
},
"email": {
"message": ""email" is not allowed to be empty",
"ref": {
"name": "email",
},
"type": "string.empty",
},
"enabled": {
"message": ""enabled" is required",
"ref": undefined,
"type": "any.required",
},
"like": [
{
"id": {
"message": ""like[0].id" must be a number",
"ref": undefined,
"type": "number.base",
},
"name": {
"message": ""like[0].name" length must be 4 characters long",
"ref": undefined,
"type": "string.length",
},
},
],
"password": {
"message": ""password" with value "___" fails to match the One uppercase character pattern",
"ref": {
"name": "password",
},
"type": "string.pattern.name",
},
"tags": {
"message": ""tags" is required",
"ref": undefined,
"type": "any.required",
},
"username": {
"message": ""username" is required",
"ref": {
"name": "username",
},
"type": "any.required",
},
},
"values": {},
}
`;
exports[`joiResolver > should return a single error from joiResolver with \`mode: sync\` when validation fails 1`] = `
{
"errors": {
"birthYear": {
"message": ""birthYear" must be a number",
"ref": undefined,
"type": "number.base",
},
"email": {
"message": ""email" is not allowed to be empty",
"ref": {
"name": "email",
},
"type": "string.empty",
},
"enabled": {
"message": ""enabled" is required",
"ref": undefined,
"type": "any.required",
},
"like": [
{
"id": {
"message": ""like[0].id" must be a number",
"ref": undefined,
"type": "number.base",
},
"name": {
"message": ""like[0].name" length must be 4 characters long",
"ref": undefined,
"type": "string.length",
},
},
],
"password": {
"message": ""password" with value "___" fails to match the One uppercase character pattern",
"ref": {
"name": "password",
},
"type": "string.pattern.name",
},
"tags": {
"message": ""tags" is required",
"ref": undefined,
"type": "any.required",
},
"username": {
"message": ""username" is required",
"ref": {
"name": "username",
},
"type": "any.required",
},
},
"values": {},
}
`;
exports[`joiResolver > should return all the errors from joiResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
{
"errors": {
"birthYear": {
"message": ""birthYear" must be a number",
"ref": undefined,
"type": "number.base",
"types": {
"number.base": ""birthYear" must be a number",
},
},
"email": {
"message": ""email" is not allowed to be empty",
"ref": {
"name": "email",
},
"type": "string.empty",
"types": {
"string.empty": ""email" is not allowed to be empty",
},
},
"enabled": {
"message": ""enabled" is required",
"ref": undefined,
"type": "any.required",
"types": {
"any.required": ""enabled" is required",
},
},
"like": [
{
"id": {
"message": ""like[0].id" must be a number",
"ref": undefined,
"type": "number.base",
"types": {
"number.base": ""like[0].id" must be a number",
},
},
"name": {
"message": ""like[0].name" length must be 4 characters long",
"ref": undefined,
"type": "string.length",
"types": {
"string.length": ""like[0].name" length must be 4 characters long",
"string.pattern.base": ""like[0].name" with value "r" fails to match the required pattern: /a/",
},
},
},
],
"password": {
"message": ""password" with value "___" fails to match the One uppercase character pattern",
"ref": {
"name": "password",
},
"type": "string.pattern.name",
"types": {
"string.min": ""password" length must be at least 8 characters long",
"string.pattern.name": [
""password" with value "___" fails to match the One uppercase character pattern",
""password" with value "___" fails to match the One lowercase character pattern",
""password" with value "___" fails to match the One number pattern",
],
},
},
"tags": {
"message": ""tags" is required",
"ref": undefined,
"type": "any.required",
"types": {
"any.required": ""tags" is required",
},
},
"username": {
"message": ""username" is required",
"ref": {
"name": "username",
},
"type": "any.required",
"types": {
"any.required": ""username" is required",
},
},
},
"values": {},
}
`;
exports[`joiResolver > should return all the errors from joiResolver when validation fails with \`validateAllFieldCriteria\` set to true and \`mode: sync\` 1`] = `
{
"errors": {
"birthYear": {
"message": ""birthYear" must be a number",
"ref": undefined,
"type": "number.base",
"types": {
"number.base": ""birthYear" must be a number",
},
},
"email": {
"message": ""email" is not allowed to be empty",
"ref": {
"name": "email",
},
"type": "string.empty",
"types": {
"string.empty": ""email" is not allowed to be empty",
},
},
"enabled": {
"message": ""enabled" is required",
"ref": undefined,
"type": "any.required",
"types": {
"any.required": ""enabled" is required",
},
},
"like": [
{
"id": {
"message": ""like[0].id" must be a number",
"ref": undefined,
"type": "number.base",
"types": {
"number.base": ""like[0].id" must be a number",
},
},
"name": {
"message": ""like[0].name" length must be 4 characters long",
"ref": undefined,
"type": "string.length",
"types": {
"string.length": ""like[0].name" length must be 4 characters long",
"string.pattern.base": ""like[0].name" with value "r" fails to match the required pattern: /a/",
},
},
},
],
"password": {
"message": ""password" with value "___" fails to match the One uppercase character pattern",
"ref": {
"name": "password",
},
"type": "string.pattern.name",
"types": {
"string.min": ""password" length must be at least 8 characters long",
"string.pattern.name": [
""password" with value "___" fails to match the One uppercase character pattern",
""password" with value "___" fails to match the One lowercase character pattern",
""password" with value "___" fails to match the One number pattern",
],
},
},
"tags": {
"message": ""tags" is required",
"ref": undefined,
"type": "any.required",
"types": {
"any.required": ""tags" is required",
},
},
"username": {
"message": ""username" is required",
"ref": {
"name": "username",
},
"type": "any.required",
"types": {
"any.required": ""username" is required",
},
},
},
"values": {},
}
`;

View File

@@ -0,0 +1,98 @@
import { joiResolver } from '..';
import { fields, invalidData, schema, validData } from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('joiResolver', () => {
it('should return values from joiResolver when validation pass', async () => {
const validateAsyncSpy = vi.spyOn(schema, 'validateAsync');
const validateSpy = vi.spyOn(schema, 'validate');
const result = await joiResolver(schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(validateSpy).not.toHaveBeenCalled();
expect(validateAsyncSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return values from joiResolver with `mode: sync` when validation pass', async () => {
const validateAsyncSpy = vi.spyOn(schema, 'validateAsync');
const validateSpy = vi.spyOn(schema, 'validate');
const result = await joiResolver(schema, undefined, {
mode: 'sync',
})(validData, undefined, { fields, shouldUseNativeValidation });
expect(validateAsyncSpy).not.toHaveBeenCalled();
expect(validateSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return a single error from joiResolver when validation fails', async () => {
const result = await joiResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return a single error from joiResolver with `mode: sync` when validation fails', async () => {
const validateAsyncSpy = vi.spyOn(schema, 'validateAsync');
const validateSpy = vi.spyOn(schema, 'validate');
const result = await joiResolver(schema, undefined, {
mode: 'sync',
})(invalidData, undefined, { fields, shouldUseNativeValidation });
expect(validateAsyncSpy).not.toHaveBeenCalled();
expect(validateSpy).toHaveBeenCalledTimes(1);
expect(result).toMatchSnapshot();
});
it('should return all the errors from joiResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
const result = await joiResolver(schema)(invalidData, undefined, {
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return all the errors from joiResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
const result = await joiResolver(schema, undefined, { mode: 'sync' })(
invalidData,
undefined,
{
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should return values from joiResolver when validation pass and pass down the Joi context', async () => {
const context = { value: 'context' };
const validateAsyncSpy = vi.spyOn(schema, 'validateAsync');
const validateSpy = vi.spyOn(schema, 'validate');
const result = await joiResolver(schema)(validData, context, {
fields,
shouldUseNativeValidation,
});
expect(validateSpy).not.toHaveBeenCalled();
expect(validateAsyncSpy).toHaveBeenCalledTimes(1);
expect(validateAsyncSpy).toHaveBeenCalledWith(validData, {
abortEarly: false,
context,
});
expect(result).toEqual({ errors: {}, values: validData });
});
});

View File

@@ -0,0 +1,2 @@
export * from './joi';
export * from './types';

View File

@@ -0,0 +1,81 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import type { ValidationError } from 'joi';
import { FieldError, appendErrors } from 'react-hook-form';
import { Resolver } from './types';
const parseErrorSchema = (
error: ValidationError,
validateAllFieldCriteria: boolean,
) =>
error.details.length
? error.details.reduce<Record<string, FieldError>>((previous, error) => {
const _path = error.path.join('.');
if (!previous[_path]) {
previous[_path] = { message: error.message, type: error.type };
}
if (validateAllFieldCriteria) {
const types = previous[_path].types;
const messages = types && types[error.type!];
previous[_path] = appendErrors(
_path,
validateAllFieldCriteria,
previous,
error.type,
messages
? ([] as string[]).concat(messages as string[], error.message)
: error.message,
) as FieldError;
}
return previous;
}, {})
: {};
export const joiResolver: Resolver =
(
schema,
schemaOptions = {
abortEarly: false,
},
resolverOptions = {},
) =>
async (values, context, options) => {
const _schemaOptions = Object.assign({}, schemaOptions, {
context,
});
let result: Record<string, any> = {};
if (resolverOptions.mode === 'sync') {
result = schema.validate(values, _schemaOptions);
} else {
try {
result.value = await schema.validateAsync(values, _schemaOptions);
} catch (e) {
result.error = e;
}
}
if (result.error) {
return {
values: {},
errors: toNestErrors(
parseErrorSchema(
result.error,
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
};
}
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return {
errors: {},
values: result.value,
};
};

View File

@@ -0,0 +1,12 @@
import type { AsyncValidationOptions, Schema } from 'joi';
import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
export type Resolver = <T extends Schema>(
schema: T,
schemaOptions?: AsyncValidationOptions,
factoryOptions?: { mode?: 'async' | 'sync' },
) => <TFieldValues extends FieldValues, TContext>(
values: TFieldValues,
context: TContext | undefined,
options: ResolverOptions<TFieldValues>,
) => Promise<ResolverResult<TFieldValues>>;