All files / packages/fds-uif/core/src validate-resolved.ts

89.65% Statements 26/29
93.1% Branches 27/29
100% Functions 1/1
89.28% Lines 25/28

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                                                                                          58x 58x 58x       2x           56x       4x                   1x           18x                         2x           3x           53x       1x                   1x               1x               1x               1x                                         56x                                     4x     4x 2x       1x     1x                 3x   3x 3x      
/**
 * @fds-uif/core - Resolved UIF Validation
 *
 * Validation utilities for resolved/merged UIFs.
 * Resolved UIFs are the output of extends resolution and contain
 * properties from both foundations and systems.
 */
 
import type { ResolvedUIF } from '@fds-uif/schema';
import { validateUif as validateSourceUif } from '@fds-uif/schema';
 
/**
 * Validation result for resolved UIFs
 */
export interface ResolvedValidationResult {
  valid: boolean;
  errors?: ResolvedValidationError[];
  warnings?: string[];
}
 
/**
 * Validation error with context
 */
export interface ResolvedValidationError {
  /** JSON pointer to the error location */
  path: string;
 
  /** Error message */
  message: string;
 
  /** Error code for programmatic handling */
  code: 'MISSING_FIELD' | 'INVALID_TYPE' | 'INVALID_STRUCTURE' | 'SCHEMA_ERROR';
}
 
/**
 * Validate a resolved UIF for consumption
 *
 * Performs structural validation to ensure the UIF has the required
 * fields and correct types. In strict mode, also runs schema validation.
 *
 * @param uif - The resolved UIF to validate
 * @param options - Validation options
 * @returns Validation result
 */
export function validateResolved(uif: unknown, options: { strict?: boolean } = {}): ResolvedValidationResult {
  const { strict = false } = options;
  const errors: ResolvedValidationError[] = [];
  const warnings: string[] = [];
 
  // Check it's an object
  if (typeof uif !== 'object' || uif === null) {
    return {
      valid: false,
      errors: [{ path: '/', message: 'UIF must be an object', code: 'INVALID_TYPE' }],
    };
  }
 
  const obj = uif as Record<string, unknown>;
 
  // Required: name
  if (typeof obj.name !== 'string' || !obj.name) {
    errors.push({
      path: '/name',
      message: 'name is required and must be a non-empty string',
      code: 'MISSING_FIELD',
    });
  }
 
  // Required in strict, warning otherwise: description
  if (typeof obj.description !== 'string') {
    if (strict) {
      errors.push({
        path: '/description',
        message: 'description is required',
        code: 'MISSING_FIELD',
      });
    } else {
      warnings.push('UIF is missing description');
    }
  }
 
  // Required in strict, warning otherwise: apiVersion
  if (typeof obj.apiVersion !== 'string') {
    if (strict) {
      errors.push({
        path: '/apiVersion',
        message: 'apiVersion is required',
        code: 'MISSING_FIELD',
      });
    } else {
      warnings.push('UIF is missing apiVersion');
    }
  }
 
  // Required: structure
  if (typeof obj.structure !== 'object' || obj.structure === null) {
    errors.push({
      path: '/structure',
      message: 'structure is required and must be an object',
      code: 'MISSING_FIELD',
    });
  } else {
    const structure = obj.structure as Record<string, unknown>;
 
    // If restrict exists, it must be an array
    if (structure.restrict !== undefined && !Array.isArray(structure.restrict)) {
      errors.push({
        path: '/structure/restrict',
        message: 'structure.restrict must be an array',
        code: 'INVALID_STRUCTURE',
      });
    }
  }
 
  // Type checks for arrays
  if (obj.states !== undefined && !Array.isArray(obj.states)) {
    errors.push({
      path: '/states',
      message: 'states must be an array',
      code: 'INVALID_TYPE',
    });
  }
 
  if (obj.modifiers !== undefined && !Array.isArray(obj.modifiers)) {
    errors.push({
      path: '/modifiers',
      message: 'modifiers must be an array',
      code: 'INVALID_TYPE',
    });
  }
 
  if (obj.variants !== undefined && !Array.isArray(obj.variants)) {
    errors.push({
      path: '/variants',
      message: 'variants must be an array',
      code: 'INVALID_TYPE',
    });
  }
 
  if (obj.stateClasses !== undefined && !Array.isArray(obj.stateClasses)) {
    errors.push({
      path: '/stateClasses',
      message: 'stateClasses must be an array',
      code: 'INVALID_TYPE',
    });
  }
 
  // In strict mode, also run source schema validation
  if (strict && errors.length === 0) {
    const schemaResult = validateSourceUif(uif);
    if (!schemaResult.valid && schemaResult.errors) {
      for (const err of schemaResult.errors) {
        errors.push({
          path: err.path,
          message: err.message,
          code: 'SCHEMA_ERROR',
        });
      }
    }
  }
 
  return {
    valid: errors.length === 0,
    errors: errors.length > 0 ? errors : undefined,
    warnings: warnings.length > 0 ? warnings : undefined,
  };
}
 
/**
 * Validate and cast to ResolvedUIF type
 *
 * @param uif - The data to validate
 * @param options - Validation options
 * @returns The typed UIF
 * @throws UifResolvedValidationError if validation fails
 */
export function validateResolvedOrThrow(
  uif: unknown,
  options: { strict?: boolean; throwOnWarning?: boolean } = {},
): ResolvedUIF {
  const result = validateResolved(uif, options);
 
  if (!result.valid) {
    const messages = result.errors?.map((e) => `${e.path}: ${e.message}`).join('; ');
    throw new UifResolvedValidationError(`UIF validation failed: ${messages}`, result.errors);
  }
 
  if (options.throwOnWarning && result.warnings?.length) {
    throw new UifResolvedValidationError(`UIF has warnings: ${result.warnings.join('; ')}`);
  }
 
  return uif as ResolvedUIF;
}
 
/**
 * Error thrown during resolved UIF validation
 */
export class UifResolvedValidationError extends Error {
  constructor(
    message: string,
    public readonly errors?: ResolvedValidationError[],
  ) {
    super(message);
    this.name = 'UifResolvedValidationError';
  }
}