{"version":3,"file":"normalizer.mjs","sources":["../../../../src/lib/data/normalization/normalizer.ts"],"sourcesContent":["/**\n * @file Entity Normalizer\n * @description Production-grade entity normalization for transforming nested\n * API responses into flat, normalized state structures.\n *\n * Features:\n * - Automatic entity extraction from nested data\n * - Relationship handling (hasMany, belongsTo)\n * - Circular reference detection\n * - Schema-based normalization\n * - TypeScript type inference\n *\n * @example\n * ```typescript\n * import { normalize, schema } from '@/lib/data/normalization';\n *\n * const userSchema = schema.entity('users');\n * const postSchema = schema.entity('posts', {\n *   author: userSchema,\n * });\n *\n * const { entities, result } = normalize(apiResponse, postSchema);\n * // entities.users = { '1': {...}, '2': {...} }\n * // entities.posts = { '101': {...author: '1'} }\n * ```\n */\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\n/**\n * Entity with required ID field\n */\nexport interface Entity {\n  id: string | number;\n  [key: string]: unknown;\n}\n\n/**\n * Normalized entity map\n */\nexport type EntityMap<T extends Entity = Entity> = Record<string, T>;\n\n/**\n * Normalized entities by type\n */\nexport type NormalizedEntities = Record<string, EntityMap>;\n\n/**\n * Normalization result\n */\nexport interface NormalizationResult<TResult = string | string[]> {\n  /** Normalized entities by type */\n  entities: NormalizedEntities;\n  /** Result reference(s) - ID or array of IDs */\n  result: TResult;\n}\n\n/**\n * Entity schema definition\n */\nexport interface EntitySchemaDefinition {\n  /** Entity type name */\n  name: string;\n  /** ID attribute name */\n  idAttribute?: string | ((entity: Entity) => string);\n  /** Relationship definitions */\n  relations?: Record<string, EntitySchema | ArraySchema | UnionSchema>;\n  /** Process entity after extraction */\n  processStrategy?: (entity: Entity) => Entity;\n  /** Merge strategy for duplicate entities */\n  mergeStrategy?: (existingEntity: Entity, newEntity: Entity) => Entity;\n  /** Fields to exclude from normalization */\n  excludeFields?: string[];\n}\n\n/**\n * Schema types\n */\nexport type Schema = EntitySchema | ArraySchema | ObjectSchema | UnionSchema | ValueSchema;\n\n// =============================================================================\n// SCHEMA CLASSES\n// =============================================================================\n\n/**\n * Entity Schema\n */\nexport class EntitySchema {\n  readonly _type = 'entity' as const;\n  readonly name: string;\n  readonly idAttribute: string | ((entity: Entity) => string);\n  readonly relations: Record<string, Schema>;\n  readonly processStrategy?: (entity: Entity) => Entity;\n  readonly mergeStrategy: (existingEntity: Entity, newEntity: Entity) => Entity;\n  readonly excludeFields: string[];\n\n  constructor(name: string, definition?: Omit<EntitySchemaDefinition, 'name'>) {\n    this.name = name;\n    this.idAttribute = definition?.idAttribute ?? 'id';\n    this.relations =\n      definition?.relations != null ? (definition.relations as Record<string, Schema>) : {};\n    this.processStrategy = definition?.processStrategy;\n    this.mergeStrategy = definition?.mergeStrategy ?? ((_, newEntity) => newEntity);\n    this.excludeFields = definition?.excludeFields ?? [];\n  }\n\n  /**\n   * Get entity ID\n   */\n  getId(entity: Entity): string {\n    if (typeof this.idAttribute === 'function') {\n      return this.idAttribute(entity);\n    }\n    return String(entity[this.idAttribute]);\n  }\n\n  /**\n   * Define a relationship\n   */\n  define(relations: Record<string, Schema>): EntitySchema {\n    return new EntitySchema(this.name, {\n      idAttribute: this.idAttribute,\n      relations: { ...this.relations, ...relations } as Record<\n        string,\n        EntitySchema | ArraySchema | UnionSchema\n      >,\n      processStrategy: this.processStrategy,\n      mergeStrategy: this.mergeStrategy,\n      excludeFields: this.excludeFields,\n    });\n  }\n}\n\n/**\n * Array Schema\n */\nexport class ArraySchema {\n  readonly _type = 'array' as const;\n  readonly schema: Schema;\n\n  constructor(schema: Schema) {\n    this.schema = schema;\n  }\n}\n\n/**\n * Object Schema\n */\nexport class ObjectSchema {\n  readonly _type = 'object' as const;\n  readonly schema: Record<string, Schema>;\n\n  constructor(schema: Record<string, Schema>) {\n    this.schema = schema;\n  }\n}\n\n/**\n * Union Schema (for polymorphic relationships)\n */\nexport class UnionSchema {\n  readonly _type = 'union' as const;\n  readonly schemas: Record<string, EntitySchema>;\n  readonly schemaAttribute: string | ((entity: Entity) => string);\n\n  constructor(\n    schemas: Record<string, EntitySchema>,\n    schemaAttribute: string | ((entity: Entity) => string) = '__typename'\n  ) {\n    this.schemas = schemas;\n    this.schemaAttribute = schemaAttribute;\n  }\n\n  /**\n   * Get schema for entity\n   */\n  getSchema(entity: Entity): EntitySchema | undefined {\n    const type =\n      typeof this.schemaAttribute === 'function'\n        ? this.schemaAttribute(entity)\n        : String(entity[this.schemaAttribute]);\n    return this.schemas[type];\n  }\n}\n\n/**\n * Value Schema (pass-through)\n */\nexport class ValueSchema {\n  readonly _type = 'value' as const;\n}\n\n// =============================================================================\n// SCHEMA FACTORY\n// =============================================================================\n\n/**\n * Schema factory functions\n */\nexport const schema = {\n  /**\n   * Create entity schema\n   */\n  entity: (\n    name: string,\n    relations?: Record<string, Schema>,\n    options?: Omit<EntitySchemaDefinition, 'name' | 'relations'>\n  ): EntitySchema =>\n    new EntitySchema(name, {\n      ...options,\n      relations: relations as Record<string, EntitySchema | ArraySchema | UnionSchema> | undefined,\n    }),\n\n  /**\n   * Create array schema\n   */\n  array: (itemSchema: Schema): ArraySchema => new ArraySchema(itemSchema),\n\n  /**\n   * Create object schema\n   */\n  object: (shape: Record<string, Schema>): ObjectSchema => new ObjectSchema(shape),\n\n  /**\n   * Create union schema\n   */\n  union: (\n    schemas: Record<string, EntitySchema>,\n    schemaAttribute?: string | ((entity: Entity) => string)\n  ): UnionSchema => new UnionSchema(schemas, schemaAttribute),\n\n  /**\n   * Create value schema (pass-through)\n   */\n  value: (): ValueSchema => new ValueSchema(),\n};\n\n// =============================================================================\n// NORMALIZER\n// =============================================================================\n\n/**\n * Normalization context\n */\ninterface NormalizationContext {\n  entities: NormalizedEntities;\n  visitedEntities: Set<string>;\n}\n\n/**\n * Create initial context\n */\nfunction createContext(): NormalizationContext {\n  return {\n    entities: {},\n    visitedEntities: new Set(),\n  };\n}\n\n/**\n * Add entity to context\n */\nfunction addEntity(\n  context: NormalizationContext,\n  entitySchema: EntitySchema,\n  entity: Entity\n): string {\n  const entityType = entitySchema.name;\n  const entityId = entitySchema.getId(entity);\n  const visitKey = `${entityType}:${entityId}`;\n\n  // Ensure entity type exists\n  context.entities[entityType] ??= {};\n\n  // Apply process strategy\n  const processedEntity = entitySchema.processStrategy\n    ? entitySchema.processStrategy(entity)\n    : entity;\n\n  // Check for existing entity\n  const existing = context.entities[entityType][entityId];\n  if (existing) {\n    // Merge with existing\n    context.entities[entityType][entityId] = entitySchema.mergeStrategy(existing, processedEntity);\n  } else {\n    context.entities[entityType][entityId] = processedEntity;\n  }\n\n  // Mark as visited\n  context.visitedEntities.add(visitKey);\n\n  return entityId;\n}\n\n/**\n * Normalize a value with a schema\n */\nfunction normalizeValue(value: unknown, schema: Schema, context: NormalizationContext): unknown {\n  if (value === null || value === undefined) {\n    return value;\n  }\n\n  switch (schema._type) {\n    case 'entity':\n      return normalizeEntity(value as Entity, schema, context);\n\n    case 'array':\n      return normalizeArray(value as unknown[], schema, context);\n\n    case 'object':\n      return normalizeObject(value as Record<string, unknown>, schema, context);\n\n    case 'union':\n      return normalizeUnion(value as Entity, schema, context);\n\n    case 'value':\n      return value;\n\n    default:\n      return value;\n  }\n}\n\n/**\n * Normalize an entity\n */\nfunction normalizeEntity(\n  entity: Entity,\n  entitySchema: EntitySchema,\n  context: NormalizationContext\n): string {\n  const entityId = entitySchema.getId(entity);\n  const visitKey = `${entitySchema.name}:${entityId}`;\n\n  // Check for circular reference\n  if (context.visitedEntities.has(visitKey)) {\n    return entityId;\n  }\n\n  // Create normalized entity\n  const normalizedEntity: Entity = { id: entityId };\n\n  // Copy fields\n  for (const [key, value] of Object.entries(entity)) {\n    if (entitySchema.excludeFields.includes(key)) {\n      continue;\n    }\n\n    if (key in entitySchema.relations) {\n      // Normalize relationship\n      const relationSchema = entitySchema.relations[key];\n      if (relationSchema) {\n        normalizedEntity[key] = normalizeValue(value, relationSchema, context);\n      }\n    } else {\n      // Copy value\n      normalizedEntity[key] = value;\n    }\n  }\n\n  // Add to entities\n  return addEntity(context, entitySchema, normalizedEntity);\n}\n\n/**\n * Normalize an array\n */\nfunction normalizeArray(\n  items: unknown[],\n  arraySchema: ArraySchema,\n  context: NormalizationContext\n): unknown[] {\n  return items.map((item) => normalizeValue(item, arraySchema.schema, context));\n}\n\n/**\n * Normalize an object\n */\nfunction normalizeObject(\n  obj: Record<string, unknown>,\n  objectSchema: ObjectSchema,\n  context: NormalizationContext\n): Record<string, unknown> {\n  const result: Record<string, unknown> = {};\n\n  for (const [key, value] of Object.entries(obj)) {\n    if (key in objectSchema.schema) {\n      const fieldSchema = objectSchema.schema[key];\n      if (fieldSchema) {\n        result[key] = normalizeValue(value, fieldSchema, context);\n      }\n    } else {\n      result[key] = value;\n    }\n  }\n\n  return result;\n}\n\n/**\n * Normalize a union type\n */\nfunction normalizeUnion(\n  entity: Entity,\n  unionSchema: UnionSchema,\n  context: NormalizationContext\n): string | null {\n  const entitySchema = unionSchema.getSchema(entity);\n  if (!entitySchema) {\n    console.warn('[Normalizer] Unknown union type for entity:', entity);\n    return null;\n  }\n\n  return normalizeEntity(entity, entitySchema, context);\n}\n\n// =============================================================================\n// PUBLIC API\n// =============================================================================\n\n/**\n * Normalize data with a schema\n *\n * @param data - Data to normalize\n * @param inputSchema\n * @returns Normalized result with entities and result reference\n *\n * @example\n * ```typescript\n * // Single entity\n * const { entities, result } = normalize(user, userSchema);\n * // result = \"1\"\n * // entities.users = { \"1\": {...} }\n *\n * // Array of entities\n * const { entities, result } = normalize(users, schema.array(userSchema));\n * // result = [\"1\", \"2\", \"3\"]\n * // entities.users = { \"1\": {...}, \"2\": {...}, \"3\": {...} }\n * ```\n */\nexport function normalize<TResult = string | string[]>(\n  data: unknown,\n  inputSchema: Schema\n): NormalizationResult<TResult> {\n  const context = createContext();\n  const result = normalizeValue(data, inputSchema, context);\n\n  return {\n    entities: context.entities,\n    result: result as TResult,\n  };\n}\n\n/**\n * Normalize and merge with existing entities\n *\n * @param data - New data to normalize\n * @param inputSchema\n * @param existingEntities - Existing normalized entities\n * @returns Merged normalization result\n */\nexport function normalizeAndMerge<TResult = string | string[]>(\n  data: unknown,\n  inputSchema: Schema,\n  existingEntities: NormalizedEntities\n): NormalizationResult<TResult> {\n  const context: NormalizationContext = {\n    entities: { ...existingEntities },\n    visitedEntities: new Set(),\n  };\n\n  // Deep clone existing entities\n  for (const [type, entities] of Object.entries(existingEntities)) {\n    context.entities[type] = { ...entities };\n  }\n\n  const result = normalizeValue(data, inputSchema, context);\n\n  return {\n    entities: context.entities,\n    result: result as TResult,\n  };\n}\n\n/**\n * Normalize batch of data\n *\n * @param items - Array of items to normalize\n * @param entitySchema\n * @returns Combined normalization result\n */\nexport function normalizeBatch<T extends Entity>(\n  items: T[],\n  entitySchema: EntitySchema\n): NormalizationResult<string[]> {\n  return normalize(items, new ArraySchema(entitySchema));\n}\n\n/**\n * Get entity from normalized state\n */\nexport function getEntity<T extends Entity>(\n  entities: NormalizedEntities,\n  entityType: string,\n  id: string\n): T | undefined {\n  return entities[entityType]?.[id] as T | undefined;\n}\n\n/**\n * Get multiple entities from normalized state\n */\nexport function getEntities<T extends Entity>(\n  entities: NormalizedEntities,\n  entityType: string,\n  ids: string[]\n): T[] {\n  const entityMap = entities[entityType];\n  if (!entityMap) return [];\n\n  return ids.map((id) => entityMap[id] as T).filter(Boolean);\n}\n\n/**\n * Get all entities of a type\n */\nexport function getAllEntities<T extends Entity>(\n  entities: NormalizedEntities,\n  entityType: string\n): T[] {\n  const entityMap = entities[entityType];\n  if (!entityMap) return [];\n\n  return Object.values(entityMap) as T[];\n}\n\n/**\n * Update entity in normalized state\n */\nexport function updateEntity<T extends Entity>(\n  entities: NormalizedEntities,\n  entityType: string,\n  id: string,\n  updates: Partial<T>\n): NormalizedEntities {\n  const entityMap = entities[entityType];\n  if (!entityMap?.[id]) {\n    return entities;\n  }\n\n  return {\n    ...entities,\n    [entityType]: {\n      ...entityMap,\n      [id]: { ...entityMap[id], ...updates },\n    },\n  };\n}\n\n/**\n * Remove entity from normalized state\n */\nexport function removeEntity(\n  entities: NormalizedEntities,\n  entityType: string,\n  id: string\n): NormalizedEntities {\n  const entityMap = entities[entityType];\n  if (!entityMap?.[id]) {\n    return entities;\n  }\n\n  const { [id]: _removed, ...rest } = entityMap;\n  return {\n    ...entities,\n    [entityType]: rest,\n  };\n}\n\n/**\n * Merge two normalized states\n */\nexport function mergeEntities(\n  target: NormalizedEntities,\n  source: NormalizedEntities,\n  mergeStrategy: 'overwrite' | 'keep' | 'merge' = 'merge'\n): NormalizedEntities {\n  const result: NormalizedEntities = { ...target };\n\n  for (const [entityType, entityMap] of Object.entries(source)) {\n    if (!result[entityType]) {\n      result[entityType] = { ...entityMap };\n      continue;\n    }\n\n    result[entityType] = { ...result[entityType] };\n\n    for (const [id, entity] of Object.entries(entityMap)) {\n      const existing = result[entityType][id];\n\n      switch (mergeStrategy) {\n        case 'overwrite':\n          result[entityType][id] = entity;\n          break;\n        case 'keep':\n          if (!existing) {\n            result[entityType][id] = entity;\n          }\n          break;\n        case 'merge':\n          result[entityType][id] = existing ? { ...existing, ...entity } : entity;\n          break;\n      }\n    }\n  }\n\n  return result;\n}\n"],"names":["EntitySchema","name","definition","_","newEntity","entity","relations","ArraySchema","schema","ObjectSchema","UnionSchema","schemas","schemaAttribute","type","ValueSchema","options","itemSchema","shape","createContext","addEntity","context","entitySchema","entityType","entityId","visitKey","processedEntity","existing","normalizeValue","value","normalizeEntity","normalizeArray","normalizeObject","normalizeUnion","normalizedEntity","key","relationSchema","items","arraySchema","item","obj","objectSchema","result","fieldSchema","unionSchema","normalize","data","inputSchema","normalizeAndMerge","existingEntities","entities","normalizeBatch","getEntity","id","getEntities","ids","entityMap","getAllEntities","updateEntity","updates","removeEntity","_removed","rest","mergeEntities","target","source","mergeStrategy"],"mappings":"AAyFO,MAAMA,EAAa;AAAA,EACf,QAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAYC,GAAcC,GAAmD;AAC3E,SAAK,OAAOD,GACZ,KAAK,cAAcC,GAAY,eAAe,M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