All files / packages/validation/src adapters.ts

91.66% Statements 88/96
78.57% Branches 44/56
100% Functions 18/18
92.3% Lines 84/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265          1x   1x 1x 1x                           1x 1x 2x     1x 1x 1x           1x     1x         1x 2x 1x     1x       1x     1x       2x   2x 1x 1x     1x 1x 1x 1x       1x                               1x     4x   1x     2x       2x 2x 1x     1x       1x               3x       4x 4x   4x   4x 4x 4x 2x   2x 2x 1x   2x   2x             1x     2x           1x     2x               2x       2x 1x         1x                                 1x         2x 2x         2x   2x 3x   3x 2x 2x     1x 1x 1x     1x       1x     2x   2x 2x       2x           2x     1x     3x 3x   3x 1x           2x             2x 1x  
import {
  type FormValidator,
  validationFailure,
  type ValidationFieldErrors,
  validationSuccess,
} from "./types";
 
const ROOT_FIELD = "root";
const RHF_ERROR_TYPE = "manual";
const DEFAULT_EFFECT_ERROR_MESSAGE = "Schema validation failed";
 
type PathSegment = string | number;
 
export interface SchemaIssueInput {
  path?: ReadonlyArray<PathSegment>;
  message?: unknown;
}
 
interface NormalizedIssue {
  path: ReadonlyArray<PathSegment>;
  message: string;
}
 
const toFieldPath = (path: ReadonlyArray<PathSegment>): string =>
  path.length > 0
    ? path.map((segment) => String(segment)).join(".")
    : ROOT_FIELD;
 
const toIssueMessage = (value: unknown, fallback: string): string => {
  Eif (typeof value === "string" && value.trim().length > 0) {
    return value;
  }
 
  return fallback;
};
 
const normalizeIssue = (
  issue: SchemaIssueInput,
  fallbackMessage: string,
): NormalizedIssue => ({
  path: Array.isArray(issue.path) ? issue.path : [],
  message: toIssueMessage(issue.message, fallbackMessage),
});
 
const toErrorMessage = (error: unknown, fallbackMessage: string): string => {
  if (error instanceof Error && error.message.trim().length > 0) {
    return error.message;
  }
 
  Iif (typeof error === "string" && error.trim().length > 0) {
    return error;
  }
 
  return fallbackMessage;
};
 
const mapIssuesToFieldErrors = <T extends object>(
  issues: ReadonlyArray<NormalizedIssue>,
  fallbackMessage: string,
): ValidationFieldErrors<T> => {
  const fieldErrors: ValidationFieldErrors<T> = {};
 
  if (issues.length === 0) {
    fieldErrors.root = fallbackMessage;
    return fieldErrors;
  }
 
  for (const issue of issues) {
    const fieldPath = toFieldPath(issue.path) as keyof ValidationFieldErrors<T>;
    Eif (!fieldErrors[fieldPath]) {
      fieldErrors[fieldPath] = issue.message;
    }
  }
 
  return fieldErrors;
};
 
export interface EffectSchemaLike<T extends object> {
  decodeUnknownSync: (input: unknown) => T;
}
 
export type EffectSchemaSource<T extends object> =
  | EffectSchemaLike<T>
  | ((input: unknown) => T);
 
interface EffectErrorLike {
  issues?: ReadonlyArray<SchemaIssueInput>;
  errors?: ReadonlyArray<SchemaIssueInput>;
}
 
const getEffectDecoder = <T extends object>(
  schema: EffectSchemaSource<T>,
): ((input: unknown) => T) =>
  typeof schema === "function" ? schema : schema.decodeUnknownSync;
 
const defaultEffectIssueExtractor = (
  error: unknown,
): ReadonlyArray<SchemaIssueInput> => {
  Iif (!error || typeof error !== "object") {
    return [];
  }
 
  const effectError = error as EffectErrorLike;
  if (Array.isArray(effectError.issues)) {
    return effectError.issues;
  }
 
  Iif (Array.isArray(effectError.errors)) {
    return effectError.errors;
  }
 
  return [];
};
 
export interface EffectSchemaAdapterOptions {
  extractIssues?: (error: unknown) => ReadonlyArray<SchemaIssueInput>;
  fallbackMessage?: string;
}
 
export const fromEffectSchema = <T extends object>(
  schema: EffectSchemaSource<T>,
  options: EffectSchemaAdapterOptions = {},
): FormValidator<T> => {
  const decode = getEffectDecoder(schema);
  const extractIssues = options.extractIssues ?? defaultEffectIssueExtractor;
  const fallbackMessage =
    options.fallbackMessage ?? DEFAULT_EFFECT_ERROR_MESSAGE;
 
  return (data) => {
    try {
      decode(data);
      return validationSuccess<T>();
    } catch (error) {
      const rawIssues = extractIssues(error);
      const normalizedIssues = rawIssues.map((issue) =>
        normalizeIssue(issue, fallbackMessage),
      );
      const errorMessage = toErrorMessage(error, fallbackMessage);
 
      return validationFailure<T>(
        mapIssuesToFieldErrors<T>(normalizedIssues, errorMessage),
      );
    }
  };
};
 
const isEffectSchemaObject = <T extends object>(
  schema: unknown,
): schema is EffectSchemaLike<T> =>
  !!schema &&
  typeof schema === "object" &&
  "decodeUnknownSync" in schema &&
  typeof (schema as { decodeUnknownSync?: unknown }).decodeUnknownSync ===
    "function";
 
const isEffectSchema = <T extends object>(
  schema: unknown,
): schema is EffectSchemaSource<T> =>
  typeof schema === "function" || isEffectSchemaObject<T>(schema);
 
export type CreateSchemaValidatorOptions = EffectSchemaAdapterOptions;
 
/**
 * Single adapter entrypoint.
 * This layer currently supports Effect schema only.
 */
export const createSchemaValidator = <T extends object>(
  schema: unknown,
  options: CreateSchemaValidatorOptions = {},
): FormValidator<T> => {
  if (!isEffectSchema<T>(schema)) {
    throw new Error(
      "createSchemaValidator expected an effect-like schema with decodeUnknownSync()",
    );
  }
 
  return fromEffectSchema(schema, options);
};
 
interface ResolverFieldError {
  type: string;
  message: string;
}
 
export interface FormResolverResult<T extends object> {
  values: T | Record<string, never>;
  errors: Record<string, unknown>;
}
 
export type FormResolver<T extends object> = (
  values: T,
) => FormResolverResult<T> | Promise<FormResolverResult<T>>;
 
const setNestedValue = (
  target: Record<string, unknown>,
  path: string,
  value: ResolverFieldError,
): void => {
  const segments = path.split(".").filter(Boolean);
  Iif (segments.length === 0) {
    target[ROOT_FIELD] = value;
    return;
  }
 
  let cursor: Record<string, unknown> = target;
 
  for (const [index, segment] of segments.entries()) {
    const isLeaf = index === segments.length - 1;
 
    if (isLeaf) {
      cursor[segment] = value;
      return;
    }
 
    const next = cursor[segment];
    Eif (!next || typeof next !== "object") {
      cursor[segment] = {};
    }
 
    cursor = cursor[segment] as Record<string, unknown>;
  }
};
 
const toResolverErrors = <T extends object>(
  fieldErrors: ValidationFieldErrors<T>,
): Record<string, unknown> => {
  const errors: Record<string, unknown> = {};
 
  for (const [field, message] of Object.entries(fieldErrors)) {
    Iif (!message) {
      continue;
    }
 
    setNestedValue(errors, field, {
      type: RHF_ERROR_TYPE,
      message,
    });
  }
 
  return errors;
};
 
export const toFormResolver = <T extends object>(
  validator: FormValidator<T>,
): FormResolver<T> => {
  return async (values) => {
    const validation = validator(values);
 
    if (validation.isValid) {
      return {
        values,
        errors: {},
      };
    }
 
    return {
      values: {},
      errors: toResolverErrors(validation.fieldErrors),
    };
  };
};
 
export const toRHFResolver = toFormResolver;
export const toHookFormResolver = toFormResolver;