{"version":3,"file":"useNormalizedData.mjs","sources":["../../../../src/lib/data/hooks/useNormalizedData.ts"],"sourcesContent":["/**\n * @file useNormalizedData Hook\n * @description React hook for working with normalized data including\n * entity selection, denormalization, and CRUD operations.\n *\n * Features:\n * - Entity selection and memoization\n * - Automatic denormalization\n * - CRUD operations with normalization\n * - Selector composition\n * - Optimized re-renders\n *\n * @example\n * ```typescript\n * import { useNormalizedData, useEntity, useEntities } from '@/lib/data';\n *\n * function PostList() {\n *   const { entities, getEntity, updateEntity } = useNormalizedData(store);\n *   const posts = useEntities(entities, 'posts', postIds, postSchema);\n *\n *   return posts.map(post => (\n *     <PostCard key={post.id} post={post} />\n *   ));\n * }\n *\n * function PostCard({ postId }) {\n *   const post = useEntity(entities, 'posts', postId, postSchema);\n *   return <div>{post?.title}</div>;\n * }\n * ```\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type {\n  Entity,\n  EntitySchema,\n  NormalizationResult,\n  NormalizedEntities,\n  Schema,\n} from '../normalization/normalizer';\nimport {\n  ArraySchema,\n  getAllEntities,\n  getEntities as getEntitiesFromState,\n  getEntity as getEntityFromState,\n  mergeEntities,\n  normalizeAndMerge,\n  removeEntity as removeEntityFromState,\n  updateEntity as updateEntityInState,\n} from '../normalization/normalizer';\nimport {\n  denormalize,\n  denormalizeMany,\n  type DenormalizeOptions,\n} from '../normalization/denormalizer';\nimport type { SchemaRegistry } from '../normalization/schema-registry';\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\n/**\n * Normalized data store\n */\nexport interface NormalizedStore {\n  /** Get current entities */\n  getEntities: () => NormalizedEntities;\n  /** Set entities */\n  setEntities: (entities: NormalizedEntities) => void;\n  /** Subscribe to changes */\n  subscribe: (listener: () => void) => () => void;\n}\n\n/**\n * Normalized data state\n */\nexport interface NormalizedDataState {\n  /** Current entities */\n  entities: NormalizedEntities;\n  /** Entity counts by type */\n  entityCounts: Record<string, number>;\n  /** Last update timestamp */\n  lastUpdatedAt: number | null;\n  /** Is loading */\n  isLoading: boolean;\n}\n\n/**\n * Validation function type\n */\nexport type ValidationFunction<T = unknown> = (\n  data: T\n) => boolean | { valid: boolean; errors?: string[] };\n\n/**\n * Validation error thrown when data fails validation\n */\nexport class ValidationError extends Error {\n  constructor(\n    message: string,\n    public readonly errors: string[] = []\n  ) {\n    super(message);\n    this.name = 'ValidationError';\n  }\n}\n\n/**\n * Hook options\n */\nexport interface UseNormalizedDataOptions {\n  /** Schema registry for denormalization */\n  registry?: SchemaRegistry;\n  /** Default denormalization options */\n  denormalizeOptions?: DenormalizeOptions;\n  /** Enable change tracking */\n  trackChanges?: boolean;\n  /** Callback on entity change */\n  onEntityChange?: (entityType: string, entityId: string, entity: Entity | null) => void;\n  /** Optional validation function to run before writes */\n  validate?: ValidationFunction;\n  /** Whether to throw on validation failure (default: true) */\n  throwOnValidationError?: boolean;\n}\n\n/**\n * Hook return type\n */\nexport interface UseNormalizedDataReturn {\n  /** Current state */\n  state: NormalizedDataState;\n  /** Current entities */\n  entities: NormalizedEntities;\n  /** Get entity by type and ID */\n  getEntity: <T extends Entity>(entityType: string, entityId: string) => T | undefined;\n  /** Get multiple entities */\n  getEntities: <T extends Entity>(entityType: string, ids: string[]) => T[];\n  /** Get all entities of type */\n  getAllOfType: <T extends Entity>(entityType: string) => T[];\n  /** Get denormalized entity */\n  getDenormalized: <T>(entityType: string, entityId: string, schema: EntitySchema) => T | null;\n  /** Get multiple denormalized entities */\n  getDenormalizedMany: <T extends Entity>(\n    entityType: string,\n    ids: string[],\n    schema: EntitySchema\n  ) => T[];\n  /** Normalize and add data */\n  addData: <T>(data: unknown, schema: Schema) => NormalizationResult<T>;\n  /** Update entity */\n  updateEntity: <T extends Entity>(\n    entityType: string,\n    entityId: string,\n    updates: Partial<T>\n  ) => void;\n  /** Remove entity */\n  removeEntity: (entityType: string, entityId: string) => void;\n  /** Merge entities */\n  mergeData: (source: NormalizedEntities, strategy?: 'overwrite' | 'keep' | 'merge') => void;\n  /** Clear all entities */\n  clearAll: () => void;\n  /** Clear entities of type */\n  clearType: (entityType: string) => void;\n  /** Get entity count */\n  getCount: (entityType: string) => number;\n  /** Check if entity exists */\n  hasEntity: (entityType: string, entityId: string) => boolean;\n}\n\n// =============================================================================\n// HOOK IMPLEMENTATION\n// =============================================================================\n\n/**\n * Hook for working with normalized data\n *\n * @param store - Normalized data store\n * @param options - Hook options\n * @returns Normalized data state and methods\n */\nexport function useNormalizedData(\n  store: NormalizedStore,\n  options: UseNormalizedDataOptions = {}\n): UseNormalizedDataReturn {\n  const {\n    registry: _registry,\n    denormalizeOptions = {},\n    trackChanges = false,\n    onEntityChange,\n    validate,\n    throwOnValidationError = true,\n  } = options;\n\n  // Helper function to validate data before writes\n  const validateData = useCallback(\n    <T>(data: T): boolean => {\n      if (!validate) return true;\n\n      const result = validate(data);\n      const isValid = typeof result === 'boolean' ? result : result.valid;\n      const errors = typeof result === 'object' && result.errors ? result.errors : [];\n\n      if (!isValid && throwOnValidationError) {\n        throw new ValidationError('Data validation failed', errors);\n      }\n\n      return isValid;\n    },\n    [validate, throwOnValidationError]\n  );\n\n  // State\n  const [state, setState] = useState<NormalizedDataState>(() => {\n    const entities = store.getEntities();\n    return {\n      entities,\n      entityCounts: Object.fromEntries(\n        Object.entries(entities).map(([type, map]) => [type, Object.keys(map).length])\n      ),\n      lastUpdatedAt: null,\n      isLoading: false,\n    };\n  });\n\n  // Refs\n  const storeRef = useRef(store);\n  storeRef.current = store;\n\n  // Subscribe to store changes\n  useEffect(() => {\n    return store.subscribe(() => {\n      const entities = storeRef.current.getEntities();\n      setState({\n        entities,\n        entityCounts: Object.fromEntries(\n          Object.entries(entities).map(([type, map]) => [type, Object.keys(map).length])\n        ),\n        lastUpdatedAt: Date.now(),\n        isLoading: false,\n      });\n    });\n  }, [store]);\n\n  // Get entity\n  const getEntity = useCallback(\n    <T extends Entity>(entityType: string, entityId: string): T | undefined => {\n      return getEntityFromState<T>(state.entities, entityType, entityId);\n    },\n    [state.entities]\n  );\n\n  // Get multiple entities\n  const getEntitiesFn = useCallback(\n    <T extends Entity>(entityType: string, ids: string[]): T[] => {\n      return getEntitiesFromState<T>(state.entities, entityType, ids);\n    },\n    [state.entities]\n  );\n\n  // Get all entities of type\n  const getAllOfType = useCallback(\n    <T extends Entity>(entityType: string): T[] => {\n      return getAllEntities<T>(state.entities, entityType);\n    },\n    [state.entities]\n  );\n\n  // Get denormalized entity\n  const getDenormalized = useCallback(\n    <T>(_entityType: string, entityId: string, schema: EntitySchema): T | null => {\n      return denormalize<T>(entityId, schema, state.entities, denormalizeOptions);\n    },\n    [state.entities, denormalizeOptions]\n  );\n\n  // Get multiple denormalized entities\n  const getDenormalizedMany = useCallback(\n    <T extends Entity>(_entityType: string, ids: string[], schema: EntitySchema): T[] => {\n      return denormalizeMany<T>(ids, schema, state.entities, denormalizeOptions);\n    },\n    [state.entities, denormalizeOptions]\n  );\n\n  // Normalize and add data with optional validation\n  const addData = useCallback(\n    <T>(data: unknown, schema: Schema): NormalizationResult<T> => {\n      // Validate data before normalizing if validation is configured\n      validateData(data);\n      const result = normalizeAndMerge<T>(data, schema, state.entities);\n      storeRef.current.setEntities(result.entities);\n      return result;\n    },\n    [state.entities, validateData]\n  );\n\n  // Update entity with optional validation\n  const updateEntityFn = useCallback(\n    <T extends Entity>(entityType: string, entityId: string, updates: Partial<T>): void => {\n      // Validate updates before applying if validation is configured\n      validateData(updates);\n      const updated = updateEntityInState<T>(state.entities, entityType, entityId, updates);\n      storeRef.current.setEntities(updated);\n\n      if (trackChanges && onEntityChange) {\n        const entity = getEntityFromState<T>(updated, entityType, entityId);\n        onEntityChange(entityType, entityId, entity ?? null);\n      }\n    },\n    [state.entities, trackChanges, onEntityChange, validateData]\n  );\n\n  // Remove entity\n  const removeEntityFn = useCallback(\n    (entityType: string, entityId: string): void => {\n      const updated = removeEntityFromState(state.entities, entityType, entityId);\n      storeRef.current.setEntities(updated);\n\n      if (trackChanges && onEntityChange) {\n        onEntityChange(entityType, entityId, null);\n      }\n    },\n    [state.entities, trackChanges, onEntityChange]\n  );\n\n  // Merge entities\n  const mergeData = useCallback(\n    (source: NormalizedEntities, strategy: 'overwrite' | 'keep' | 'merge' = 'merge'): void => {\n      const merged = mergeEntities(state.entities, source, strategy);\n      storeRef.current.setEntities(merged);\n    },\n    [state.entities]\n  );\n\n  // Clear all entities\n  const clearAll = useCallback((): void => {\n    storeRef.current.setEntities({});\n  }, []);\n\n  // Clear entities of type\n  const clearType = useCallback(\n    (entityType: string): void => {\n      const { [entityType]: _removed, ...rest } = state.entities;\n      storeRef.current.setEntities(rest);\n    },\n    [state.entities]\n  );\n\n  // Get entity count\n  const getCount = useCallback(\n    (entityType: string): number => {\n      return state.entityCounts[entityType] ?? 0;\n    },\n    [state.entityCounts]\n  );\n\n  // Check if entity exists\n  const hasEntity = useCallback(\n    (entityType: string, entityId: string): boolean => {\n      return !!state.entities[entityType]?.[entityId];\n    },\n    [state.entities]\n  );\n\n  return {\n    state,\n    entities: state.entities,\n    getEntity,\n    getEntities: getEntitiesFn,\n    getAllOfType,\n    getDenormalized,\n    getDenormalizedMany,\n    addData,\n    updateEntity: updateEntityFn,\n    removeEntity: removeEntityFn,\n    mergeData,\n    clearAll,\n    clearType,\n    getCount,\n    hasEntity,\n  };\n}\n\n// =============================================================================\n// SPECIALIZED HOOKS\n// =============================================================================\n\n/**\n * Hook for selecting a single entity\n *\n * @param entities - Normalized entities\n * @param entityType - Entity type\n * @param entityId - Entity ID\n * @param schema - Optional schema for denormalization\n * @param options - Denormalization options\n * @returns Entity or null\n */\nexport function useEntity<T extends Entity>(\n  entities: NormalizedEntities,\n  entityType: string,\n  entityId: string | null | undefined,\n  schema?: EntitySchema,\n  options?: DenormalizeOptions\n): T | null {\n  return useMemo(() => {\n    if (entityId == null || entityId === '') return null;\n\n    if (schema !== undefined) {\n      return denormalize<T>(entityId, schema, entities, options);\n    }\n\n    return getEntityFromState<T>(entities, entityType, entityId) ?? null;\n  }, [entities, entityType, entityId, schema, options]);\n}\n\n/**\n * Hook for selecting multiple entities\n *\n * @param entities - Normalized entities\n * @param entityType - Entity type\n * @param ids - Entity IDs\n * @param schema - Optional schema for denormalization\n * @param options - Denormalization options\n * @returns Array of entities\n */\nexport function useEntities<T extends Entity>(\n  entities: NormalizedEntities,\n  entityType: string,\n  ids: string[],\n  schema?: EntitySchema,\n  options?: DenormalizeOptions\n): T[] {\n  return useMemo(() => {\n    if (ids.length === 0) return [];\n\n    if (schema) {\n      return denormalizeMany<T>(ids, schema, entities, options);\n    }\n\n    return getEntitiesFromState<T>(entities, entityType, ids);\n  }, [entities, entityType, ids, schema, options]);\n}\n\n/**\n * Hook for selecting all entities of a type\n *\n * @param entities - Normalized entities\n * @param entityType - Entity type\n * @param filter - Optional filter function\n * @param sort - Optional sort function\n * @returns Array of entities\n */\nexport function useAllEntities<T extends Entity>(\n  entities: NormalizedEntities,\n  entityType: string,\n  filter?: (entity: T) => boolean,\n  sort?: (a: T, b: T) => number\n): T[] {\n  return useMemo(() => {\n    let result = getAllEntities<T>(entities, entityType);\n\n    if (filter) {\n      result = result.filter(filter);\n    }\n\n    if (sort) {\n      result = [...result].sort(sort);\n    }\n\n    return result;\n  }, [entities, entityType, filter, sort]);\n}\n\n/**\n * Hook for entity selector with memoization\n *\n * @param entities - Normalized entities\n * @param selector - Selector function\n * @param _deps\n * @returns Selected value\n */\nexport function useEntitySelector<T>(\n  entities: NormalizedEntities,\n  selector: (entities: NormalizedEntities) => T,\n  _deps: unknown[] = []\n): T {\n  // Note: deps parameter is kept for API compatibility but not used\n  // Users should memoize their selector function instead\n  return useMemo(() => selector(entities), [entities, selector]);\n}\n\n/**\n * Hook for normalized CRUD operations\n *\n * @param store - Normalized store\n * @param entityType - Entity type\n * @param schema - Entity schema\n * @returns CRUD operations\n */\nexport function useNormalizedCrud<T extends Entity>(\n  store: NormalizedStore,\n  entityType: string,\n  schema: EntitySchema\n): {\n  items: T[];\n  getById: (id: string) => T | null;\n  create: (data: Omit<T, 'id'> & { id?: string }) => T;\n  update: (id: string, data: Partial<T>) => T | null;\n  remove: (id: string) => void;\n  upsert: (data: T) => T;\n  upsertMany: (items: T[]) => T[];\n} {\n  const [entities, setEntities] = useState<NormalizedEntities>(store.getEntities());\n\n  useEffect(() => {\n    return store.subscribe(() => {\n      setEntities(store.getEntities());\n    });\n  }, [store]);\n\n  const items = useMemo(() => {\n    return getAllEntities<T>(entities, entityType);\n  }, [entities, entityType]);\n\n  const getById = useCallback(\n    (id: string): T | null => {\n      return denormalize<T>(id, schema, entities) ?? null;\n    },\n    [entities, schema]\n  );\n\n  const create = useCallback(\n    (data: Omit<T, 'id'> & { id?: string }): T => {\n      const id =\n        data.id != null && data.id !== ''\n          ? data.id\n          : `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n      const entity = { ...data, id } as T;\n      const result = normalizeAndMerge(entity, schema, entities);\n      store.setEntities(result.entities);\n      return entity;\n    },\n    [entities, schema, store]\n  );\n\n  const update = useCallback(\n    (id: string, data: Partial<T>): T | null => {\n      const existing = getEntityFromState<T>(entities, entityType, id);\n      if (!existing) return null;\n\n      const updated = updateEntityInState<T>(entities, entityType, id, data);\n      store.setEntities(updated);\n      return { ...existing, ...data } as T;\n    },\n    [entities, entityType, store]\n  );\n\n  const remove = useCallback(\n    (id: string): void => {\n      const updated = removeEntityFromState(entities, entityType, id);\n      store.setEntities(updated);\n    },\n    [entities, entityType, store]\n  );\n\n  const upsert = useCallback(\n    (data: T): T => {\n      const result = normalizeAndMerge(data, schema, entities);\n      store.setEntities(result.entities);\n      return data;\n    },\n    [entities, schema, store]\n  );\n\n  const upsertMany = useCallback(\n    (newItems: T[]): T[] => {\n      const arraySchema = new ArraySchema(schema);\n      const result = normalizeAndMerge(newItems, arraySchema, entities);\n      store.setEntities(result.entities);\n      return newItems;\n    },\n    [entities, schema, store]\n  );\n\n  return {\n    items,\n    getById,\n    create,\n    update,\n    remove,\n    upsert,\n    upsertMany,\n  };\n}\n\n/**\n * Create a simple normalized store\n */\nexport function createNormalizedStore(initialEntities: NormalizedEntities = {}): NormalizedStore {\n  let entities = initialEntities;\n  const listeners = new Set<() => void>();\n\n  return {\n    getEntities: () => entities,\n    setEntities: (newEntities) => {\n      entities = newEntities;\n      listeners.forEach((listener) => listener());\n    },\n    subscribe: (listener) => {\n      listeners.add(listener);\n      return () => {\n        listeners.delete(listener);\n      };\n    },\n  };\n}\n"],"names":["ValidationError","message","errors","useNormalizedData","store","options","_registry","denormalizeOptions","trackChanges","onEntityChange","validate","throwOnValidationError","validateData","useCallback","data","result","isValid","state","setState","useState","entities","type","map","storeRef","useRef","useEffect","getEntity","entityType","entityId","getEntityFromState","getEntitiesFn","ids","getEntitiesFromState","getAllOfType","getAllEntities","getDenormalized","_entityType","schema","denormalize","getDenormalizedMany","denormalizeMany","addData","normalizeAndMerge","updateEntityFn","updates","updated","updateEntityInState","entity","removeEntityFn","removeEntityFromState","mergeData","source","strategy","merged","mergeEntities","clearAll","clearType","_removed","rest","getCount","hasEntity","useEntity","useMemo","useEntities","useAllEntities","filter","sort","useEntitySelector","selector","_deps","useNormalizedCrud","setEntities","items","getById","id","create","update","existing","remove","upsert","upsertMany","newItems","arraySchema","ArraySchema","createNormalizedStore","initialEntities","listeners","newEntities","listener"],"mappings":";;;AAiGO,MAAMA,UAAwB,MAAM;AAAA,EACzC,YACEC,GACgBC,IAAmB,IACnC;AACA,UAAMD,CAAO,GAFG,KAAA,SAAAC,GAGhB,KAAK,OAAO;AAAA,EACd;AACF;AA2EO,SAASC,EACdC,GACAC,IAAoC,IACX;AACzB,QAAM;AAAA,IACJ,UAAUC;AAAA,IACV,oBAAAC,IAAqB,CAAA;AAAA,IACrB,cAAAC,IAAe;AAAA,IACf,gBAAAC;AAAA,IACA,UAAAC;AAAA,IACA,wBAAAC,IAAyB;AAAA,EAAA,IACvBN,GAGEO,IAAeC;AAAA,IACnB,CAAIC,MAAqB;AACvB,UAAI,CAACJ,EAAU,QAAO;AAEtB,YAAMK,IAASL,EAASI,CAAI,G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