All files / state/src state-validation.js

90.55% Statements 259/286
84% Branches 252/300
97.61% Functions 41/42
91.48% Lines 247/270

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 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879                                  4x           4x                 6x                                                                                     124x   4x       57x   4x   27x   32x           6x 5x 5x 1x                     18x   4x 3x   1x       7x 6x 1x     1x   6x 7x     6x 4x 4x 3x 1x   2x     1x                 38x 38x                             122x 122x       122x 122x 122x 13x   109x       109x 2x 2x 1x         109x 22x 22x 4x         109x 22x 22x 3x         109x 4x 4x 2x   4x       109x 54x 54x 28x   54x       109x 2x 2x 1x                 109x               122x 122x 122x     122x   124x   122x 25x   18x 18x 18x 12x   6x                 7x                   122x               2x 2x 1x               2x       22x   22x 1x               22x                 22x 2x 2x 1x                 22x 6x 6x 2x       22x       6x 6x               6x 2x                 6x       22x   22x 1x               22x 1x               22x                 22x                 22x 1x               22x       4x 4x   4x 1x               4x                 4x 2x 2x 2x 6x 6x 1x   6x   2x 1x                   4x 4x 8x 8x 8x     8x           4x               54x 54x     54x 2x 2x 1x                     54x 54x 83x 60x 60x 60x 24x   60x 18x                 54x 3x 3x 6x 3x                     54x 54x                 54x                 54x                             44x                         44x         44x 44x 44x                 61x 61x     61x 54x       54x 54x 28x   54x       61x                     61x   59x 2x 2x 2x 1x                       61x 1x 2x 1x                   61x                         39x   39x                   39x                 57x   57x         57x     57x 57x   57x 28x   28x 11x     28x 1x 1x 1x       27x       29x 9x 9x 9x 12x 12x     9x       29x     29x     29x 2x 2x                         2x 2x                 17x               2x 2x 1x   2x                   2x     44x                           4x             7x 6x 1x                 2x 2x 2x 2x   1x                   1x 3x 2x 1x                 1x 2x 2x 1x   1x               1x 2x 2x 2x 1x                 4x 3x   1x                  
/**
 * @fileoverview State Validation for Coherent.js
 * Provides JSON Schema validation and custom validators for state management
 * @module @coherent.js/core/state/state-validation
 */
 
/**
 * Email shape check: a local part, then a dotted domain.
 *
 * Domain labels use `[^\s@.]` rather than `[^\s@]` so that the literal dot
 * separators are the only thing that can match a dot. Allowing `[^\s@]+` on
 * both sides of `\.` makes the split ambiguous, and a non-matching subject
 * with many dots ("a@" + "a." * n + " ") then costs O(n²) backtracking —
 * CodeQL js/polynomial-redos.
 *
 * @private
 */
const EMAIL_PATTERN = /^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/;
 
/**
 * Longest address RFC 5321 permits, used to bound work before matching.
 * @private
 */
const EMAIL_MAX_LENGTH = 254;
 
/**
 * Test whether a value has the shape of an email address.
 * @private
 * @param {unknown} value - Value to check
 * @returns {boolean} True if the value looks like an email address
 */
function isEmailShaped(value) {
  return (
    typeof value === 'string' &&
    value.length <= EMAIL_MAX_LENGTH &&
    EMAIL_PATTERN.test(value)
  );
}
 
 
/**
 * @typedef {Object} ValidationOptions
 * @property {Object} [schema] - JSON Schema for validation
 * @property {Object<string, Function>} [validators] - Custom validator functions
 * @property {boolean} [strict=false] - Strict mode (throw on validation errors)
 * @property {boolean} [coerce=false] - Coerce types to match schema
 * @property {Function} [onError] - Validation error callback
 * @property {boolean} [validateOnSet=true] - Validate on state updates
 * @property {boolean} [validateOnGet=false] - Validate on state reads
 * @property {Array<string>} [required] - Required fields
 * @property {boolean} [allowUnknown=true] - Allow unknown properties
 */
 
/**
 * @typedef {Object} ValidationResult
 * @property {boolean} valid - Whether validation passed
 * @property {Array<ValidationError>} errors - Array of validation errors
 * @property {*} value - Validated/coerced value
 */
 
/**
 * @typedef {Object} ValidationError
 * @property {string} path - Property path that failed validation
 * @property {string} message - Error message
 * @property {string} type - Error type
 * @property {*} value - The invalid value
 * @property {*} expected - Expected value/type
 */
 
/**
 * Whether a value has a JSON Schema type. `object` excludes null and arrays;
 * `number` excludes NaN, which JSON cannot represent.
 * @private
 */
function matchesType(value, type) {
  switch (type) {
    case 'array':
      return Array.isArray(value);
    case 'null':
      return value === null;
    case 'object':
      return value !== null && typeof value === 'object' && !Array.isArray(value);
    case 'integer':
      return typeof value === 'number' && Number.isInteger(value);
    case 'number':
      return typeof value === 'number' && !Number.isNaN(value);
    default:
      return typeof value === type;
  }
}
 
/** @private */
function describeValue(value) {
  if (value === null) return 'null';
  Iif (Array.isArray(value)) return 'array';
  if (typeof value === 'string') return JSON.stringify(value);
  return typeof value === 'object' ? 'object' : String(value);
}
 
/**
 * Coerce a value to a JSON Schema type, refusing conversions that would
 * invent data: `Boolean('false')` is true, `Number('')` is 0 and
 * `String({})` is "[object Object]", so none of those are accepted.
 * @private
 * @returns {{ ok: boolean, value?: * }}
 */
function coerceTo(value, type) {
  switch (type) {
    case 'string':
      if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
        return { ok: !Number.isNaN(value), value: String(value) };
      }
      return { ok: false };
    case 'number':
    case 'integer': {
      let number;
      if (typeof value === 'string' && value.trim() !== '') {
        number = Number(value);
      } else Iif (typeof value === 'boolean') {
        number = value ? 1 : 0;
      } else {
        return { ok: false };
      }
      const valid = type === 'integer' ? Number.isInteger(number) : !Number.isNaN(number);
      return valid ? { ok: true, value: number } : { ok: false };
    }
    case 'boolean':
      if (typeof value === 'string') {
        const normalized = value.trim().toLowerCase();
        if (normalized === 'true' || normalized === '1') return { ok: true, value: true };
        if (normalized === 'false' || normalized === '0' || normalized === '') return { ok: true, value: false };
        return { ok: false };
      }
      Eif (value === 1 || value === 0) return { ok: true, value: value === 1 };
      return { ok: false };
    default:
      return { ok: false };
  }
}
 
/**
 * Simple JSON Schema validator
 */
class SchemaValidator {
  constructor(schema, options = {}) {
    this.schema = schema;
    this.options = {
      coerce: false,
      allowUnknown: true,
      ...options
    };
  }
 
  /**
   * Validate value against schema
   * @param {*} value - Value to validate
   * @param {Object} schema - Schema to validate against
   * @param {string} path - Current path in object
   * @returns {ValidationResult} Validation result
   */
  validate(value, schema = this.schema, path = '') {
    const errors = [];
    let coercedValue = value;
 
    // Type validation. A value of the wrong type that could not be coerced
    // gets no further checks: they assume the declared type.
    Eif (schema.type) {
      const typeResult = this.validateType(value, schema.type, path);
      if (!typeResult.valid) {
        return { valid: false, errors: typeResult.errors, value };
      }
      coercedValue = typeResult.value;
    }
 
    // Enum validation
    if (schema.enum) {
      const enumResult = this.validateEnum(coercedValue, schema.enum, path);
      if (!enumResult.valid) {
        errors.push(...enumResult.errors);
      }
    }
 
    // String validations
    if (schema.type === 'string') {
      const stringResult = this.validateString(coercedValue, schema, path);
      if (!stringResult.valid) {
        errors.push(...stringResult.errors);
      }
    }
 
    // Number validations
    if (schema.type === 'number' || schema.type === 'integer') {
      const numberResult = this.validateNumber(coercedValue, schema, path);
      if (!numberResult.valid) {
        errors.push(...numberResult.errors);
      }
    }
 
    // Array validations
    if (schema.type === 'array') {
      const arrayResult = this.validateArray(coercedValue, schema, path);
      if (!arrayResult.valid) {
        errors.push(...arrayResult.errors);
      }
      coercedValue = arrayResult.value;
    }
 
    // Object validations
    if (schema.type === 'object') {
      const objectResult = this.validateObject(coercedValue, schema, path);
      if (!objectResult.valid) {
        errors.push(...objectResult.errors);
      }
      coercedValue = objectResult.value;
    }
 
    // Custom validation function
    if (schema.validate && typeof schema.validate === 'function') {
      const customResult = schema.validate(coercedValue);
      if (customResult !== true) {
        errors.push({
          path,
          message: typeof customResult === 'string' ? customResult : 'Custom validation failed',
          type: 'custom',
          value: coercedValue
        });
      }
    }
 
    return {
      valid: errors.length === 0,
      errors,
      value: coercedValue
    };
  }
 
  validateType(value, type, path) {
    const actualType = Array.isArray(value) ? 'array' : typeof value;
    const errors = [];
    let coercedValue = value;
 
    // Support array of types
    const types = Array.isArray(type) ? type : [type];
 
    const isValid = types.some(t => matchesType(value, t));
 
    if (!isValid) {
      if (this.options.coerce) {
        // Try to coerce to the first declared type
        const primaryType = types[0];
        const coerced = coerceTo(value, primaryType);
        if (coerced.ok) {
          coercedValue = coerced.value;
        } else {
          errors.push({
            path,
            message: `Cannot coerce ${describeValue(value)} to ${primaryType}`,
            type: 'type',
            value,
            expected: primaryType
          });
        }
      } else {
        errors.push({
          path,
          message: `Expected type ${types.join(' or ')}, got ${actualType}`,
          type: 'type',
          value,
          expected: type
        });
      }
    }
 
    return {
      valid: errors.length === 0,
      errors,
      value: coercedValue
    };
  }
 
  validateEnum(value, enumValues, path) {
    const errors = [];
    if (!enumValues.includes(value)) {
      errors.push({
        path,
        message: `Value must be one of: ${enumValues.join(', ')}`,
        type: 'enum',
        value,
        expected: enumValues
      });
    }
    return { valid: errors.length === 0, errors };
  }
 
  validateString(value, schema, path) {
    const errors = [];
 
    if (schema.minLength !== undefined && value.length < schema.minLength) {
      errors.push({
        path,
        message: `String length must be >= ${schema.minLength}`,
        type: 'minLength',
        value
      });
    }
 
    Iif (schema.maxLength !== undefined && value.length > schema.maxLength) {
      errors.push({
        path,
        message: `String length must be <= ${schema.maxLength}`,
        type: 'maxLength',
        value
      });
    }
 
    if (schema.pattern) {
      const regex = new RegExp(schema.pattern);
      if (!regex.test(value)) {
        errors.push({
          path,
          message: `String does not match pattern: ${schema.pattern}`,
          type: 'pattern',
          value
        });
      }
    }
 
    if (schema.format) {
      const formatResult = this.validateFormat(value, schema.format, path);
      if (!formatResult.valid) {
        errors.push(...formatResult.errors);
      }
    }
 
    return { valid: errors.length === 0, errors };
  }
 
  validateFormat(value, format, path) {
    const errors = [];
    const formats = {
      email: EMAIL_PATTERN,
      url: /^https?:\/\/.+/,
      uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
      date: /^\d{4}-\d{2}-\d{2}$/,
      'date-time': /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/
    };
 
    if (formats[format] && !formats[format].test(value)) {
      errors.push({
        path,
        message: `String does not match format: ${format}`,
        type: 'format',
        value,
        expected: format
      });
    }
 
    return { valid: errors.length === 0, errors };
  }
 
  validateNumber(value, schema, path) {
    const errors = [];
 
    if (schema.minimum !== undefined && value < schema.minimum) {
      errors.push({
        path,
        message: `Number must be >= ${schema.minimum}`,
        type: 'minimum',
        value
      });
    }
 
    if (schema.maximum !== undefined && value > schema.maximum) {
      errors.push({
        path,
        message: `Number must be <= ${schema.maximum}`,
        type: 'maximum',
        value
      });
    }
 
    Iif (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) {
      errors.push({
        path,
        message: `Number must be > ${schema.exclusiveMinimum}`,
        type: 'exclusiveMinimum',
        value
      });
    }
 
    Iif (schema.exclusiveMaximum !== undefined && value >= schema.exclusiveMaximum) {
      errors.push({
        path,
        message: `Number must be < ${schema.exclusiveMaximum}`,
        type: 'exclusiveMaximum',
        value
      });
    }
 
    if (schema.multipleOf !== undefined && value % schema.multipleOf !== 0) {
      errors.push({
        path,
        message: `Number must be multiple of ${schema.multipleOf}`,
        type: 'multipleOf',
        value
      });
    }
 
    return { valid: errors.length === 0, errors };
  }
 
  validateArray(value, schema, path) {
    const errors = [];
    const coercedValue = [...value];
 
    if (schema.minItems !== undefined && value.length < schema.minItems) {
      errors.push({
        path,
        message: `Array must have at least ${schema.minItems} items`,
        type: 'minItems',
        value
      });
    }
 
    Iif (schema.maxItems !== undefined && value.length > schema.maxItems) {
      errors.push({
        path,
        message: `Array must have at most ${schema.maxItems} items`,
        type: 'maxItems',
        value
      });
    }
 
    if (schema.uniqueItems) {
      const seen = new Set();
      const duplicates = [];
      value.forEach((item, index) => {
        const key = JSON.stringify(item);
        if (seen.has(key)) {
          duplicates.push(index);
        }
        seen.add(key);
      });
      if (duplicates.length > 0) {
        errors.push({
          path,
          message: 'Array items must be unique',
          type: 'uniqueItems',
          value
        });
      }
    }
 
    // Validate items
    Eif (schema.items) {
      value.forEach((item, index) => {
        const itemPath = `${path}[${index}]`;
        const itemResult = this.validate(item, schema.items, itemPath);
        Iif (!itemResult.valid) {
          errors.push(...itemResult.errors);
        }
        Iif (this.options.coerce) {
          coercedValue[index] = itemResult.value;
        }
      });
    }
 
    return {
      valid: errors.length === 0,
      errors,
      value: coercedValue
    };
  }
 
  validateObject(value, schema, path) {
    const errors = [];
    const coercedValue = { ...value };
 
    // Required properties
    if (schema.required) {
      schema.required.forEach(prop => {
        if (!(prop in value)) {
          errors.push({
            path: path ? `${path}.${prop}` : prop,
            message: `Required property "${prop}" is missing`,
            type: 'required',
            value: undefined
          });
        }
      });
    }
 
    // Validate properties
    Eif (schema.properties) {
      Object.entries(schema.properties).forEach(([prop, propSchema]) => {
        if (prop in value) {
          const propPath = path ? `${path}.${prop}` : prop;
          const propResult = this.validate(value[prop], propSchema, propPath);
          if (!propResult.valid) {
            errors.push(...propResult.errors);
          }
          if (this.options.coerce) {
            coercedValue[prop] = propResult.value;
          }
        }
      });
    }
 
    // Additional properties: rejected by the schema's own
    // `additionalProperties: false`, or for any object schema that lists its
    // properties when the validator runs with `allowUnknown: false`
    if (schema.additionalProperties === false || (!this.options.allowUnknown && schema.properties)) {
      const allowedProps = new Set(Object.keys(schema.properties || {}));
      Object.keys(value).forEach(prop => {
        if (!allowedProps.has(prop)) {
          errors.push({
            path: path ? `${path}.${prop}` : prop,
            message: `Unknown property "${prop}"`,
            type: 'additionalProperties',
            value: value[prop]
          });
        }
      });
    }
 
    // Min/max properties
    const propCount = Object.keys(value).length;
    Iif (schema.minProperties !== undefined && propCount < schema.minProperties) {
      errors.push({
        path,
        message: `Object must have at least ${schema.minProperties} properties`,
        type: 'minProperties',
        value
      });
    }
 
    Iif (schema.maxProperties !== undefined && propCount > schema.maxProperties) {
      errors.push({
        path,
        message: `Object must have at most ${schema.maxProperties} properties`,
        type: 'maxProperties',
        value
      });
    }
 
    return {
      valid: errors.length === 0,
      errors,
      value: coercedValue
    };
  }
}
 
/**
 * Create validated state manager
 * @param {Object} initialState - Initial state
 * @param {ValidationOptions} options - Validation options
 * @returns {Object} Validated state manager
 */
export function createValidatedState(initialState = {}, options = {}) {
  const opts = {
    schema: null,
    validators: {},
    strict: false,
    coerce: false,
    onError: null,
    validateOnSet: true,
    validateOnGet: false,
    required: [],
    allowUnknown: true,
    ...options
  };
 
  const schemaValidator = opts.schema ? new SchemaValidator(opts.schema, {
    coerce: opts.coerce,
    allowUnknown: opts.allowUnknown
  }) : null;
 
  let state = { ...initialState };
  const listeners = new Set();
  const validationErrors = new Map();
 
  /**
   * Validate state
   * @param {Object} value - State to validate
   * @param {string} key - State key (for partial validation)
   * @returns {ValidationResult} Validation result
   */
  function validateState(value, key = null) {
    const errors = [];
    let validatedValue = value;
 
    // JSON Schema validation
    if (schemaValidator) {
      const schema = key && opts.schema.properties
        ? opts.schema.properties[key]
        : opts.schema;
 
      const result = schemaValidator.validate(value, schema, key || '');
      if (!result.valid) {
        errors.push(...result.errors);
      }
      validatedValue = result.value;
    }
 
    // Custom validators
    Iif (key && opts.validators[key]) {
      const validator = opts.validators[key];
      const result = validator(value);
      if (result !== true) {
        errors.push({
          path: key,
          message: typeof result === 'string' ? result : 'Validation failed',
          type: 'custom',
          value
        });
      }
    } else if (!key) {
      // Run custom validators for all fields when validating full state
      Object.entries(opts.validators).forEach(([fieldKey, validator]) => {
        Eif (fieldKey in value) {
          const result = validator(value[fieldKey]);
          if (result !== true) {
            errors.push({
              path: fieldKey,
              message: typeof result === 'string' ? result : 'Validation failed',
              type: 'custom',
              value: value[fieldKey]
            });
          }
        }
      });
    }
 
    // Required fields
    if (opts.required.length > 0 && !key) {
      opts.required.forEach(field => {
        if (!(field in value)) {
          errors.push({
            path: field,
            message: `Required field "${field}" is missing`,
            type: 'required',
            value: undefined
          });
        }
      });
    }
 
    return {
      valid: errors.length === 0,
      errors,
      value: validatedValue
    };
  }
 
  /**
   * Get state
   * @param {string} key - State key
   * @returns {*} State value
   */
  function getState(key) {
    const value = key ? state[key] : { ...state };
 
    Iif (opts.validateOnGet) {
      const result = validateState(value, key);
      if (!result.valid) {
        validationErrors.set(key || '__root__', result.errors);
        if (opts.onError) {
          opts.onError(result.errors);
        }
      }
    }
 
    return value;
  }
 
  /**
   * Set state
   * @param {Object|Function} updates - State updates
   * @throws {Error} If validation fails in strict mode
   */
  function setState(updates) {
    const oldState = { ...state };
 
    Iif (typeof updates === 'function') {
      updates = updates(oldState);
    }
 
    // Create the new full state for validation
    const newState = { ...state, ...updates };
 
    // Validate before setting
    Eif (opts.validateOnSet) {
      const result = validateState(newState);
 
      if (!result.valid) {
        validationErrors.set('__root__', result.errors);
 
        if (opts.onError) {
          opts.onError(result.errors);
        }
 
        if (opts.strict) {
          const error = new Error('Validation failed');
          error.validationErrors = result.errors;
          throw error;
        }
 
        // Don't update state if validation fails in non-strict mode
        return;
      }
 
      // Use coerced value if coercion is enabled
      if (opts.coerce) {
        const updatedKeys = Object.keys(updates);
        const newUpdates = {};
        updatedKeys.forEach(key => {
          Eif (result.value[key] !== state[key]) {
            newUpdates[key] = result.value[key];
          }
        });
        updates = newUpdates;
      }
 
      // Clear errors on successful validation
      validationErrors.clear();
    }
 
    state = { ...state, ...updates };
 
    // Notify listeners
    listeners.forEach(listener => {
      try {
        listener(state, oldState);
      } catch (error) {
        console.error('Listener error:', error);
      }
    });
  }
 
  /**
   * Subscribe to state changes
   * @param {Function} listener - Change listener
   * @returns {Function} Unsubscribe function
   */
  function subscribe(listener) {
    listeners.add(listener);
    return () => listeners.delete(listener);
  }
 
  /**
   * Get validation errors
   * @param {string} key - State key
   * @returns {Array<ValidationError>} Validation errors
   */
  function getErrors(key = '__root__') {
    return validationErrors.get(key) || [];
  }
 
  /**
   * Check if state is valid
   * @returns {boolean} Whether state is valid
   */
  function isValid() {
    const result = validateState(state);
    if (!result.valid) {
      validationErrors.set('__root__', result.errors);
    }
    return result.valid;
  }
 
  /**
   * Validate specific field
   * @param {string} key - Field key
   * @param {*} value - Field value
   * @returns {ValidationResult} Validation result
   */
  function validateField(key, value) {
    return validateState(value, key);
  }
 
  return {
    getState,
    setState,
    subscribe,
    getErrors,
    isValid,
    validateField,
    validate: () => validateState(state)
  };
}
 
/**
 * Common validators
 */
export const validators = {
  /**
   * Email validator
   * @param {string} value - Email to validate
   * @returns {boolean|string} True if valid, error message otherwise
   */
  email: (value) => {
    if (typeof value !== 'string') return 'Email must be a string';
    if (!isEmailShaped(value)) return 'Invalid email format';
    return true;
  },
 
  /**
   * URL validator
   * @param {string} value - URL to validate
   * @returns {boolean|string} True if valid, error message otherwise
   */
  url: (value) => {
    Iif (typeof value !== 'string') return 'URL must be a string';
    try {
      new URL(value);
      return true;
    } catch {
      return 'Invalid URL format';
    }
  },
 
  /**
   * Range validator
   * @param {number} min - Minimum value
   * @param {number} max - Maximum value
   * @returns {Function} Validator function
   */
  range: (min, max) => (value) => {
    if (typeof value !== 'number') return 'Value must be a number';
    if (value < min || value > max) return `Value must be between ${min} and ${max}`;
    return true;
  },
 
  /**
   * Length validator
   * @param {number} min - Minimum length
   * @param {number} max - Maximum length
   * @returns {Function} Validator function
   */
  length: (min, max) => (value) => {
    Iif (typeof value !== 'string') return 'Value must be a string';
    if (value.length < min || value.length > max) {
      return `Length must be between ${min} and ${max}`;
    }
    return true;
  },
 
  /**
   * Pattern validator
   * @param {RegExp|string} pattern - Pattern to match
   * @returns {Function} Validator function
   */
  pattern: (pattern) => (value) => {
    Iif (typeof value !== 'string') return 'Value must be a string';
    const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern;
    if (!regex.test(value)) return `Value does not match pattern: ${pattern}`;
    return true;
  },
 
  /**
   * Required validator
   * @param {*} value - Value to validate
   * @returns {boolean|string} True if valid, error message otherwise
   */
  required: (value) => {
    if (value === undefined || value === null || value === '') {
      return 'Value is required';
    }
    return true;
  }
};
 
export default {
  createValidatedState,
  validators,
  SchemaValidator
};