{"version":3,"sources":["../src/types.ts","../src/const.ts","../src/utils/validators.ts","../src/operations/createOne.ts","../src/utils/populate.ts","../src/operations/getOneById.ts","../src/operations/replaceOneById.ts","../src/utils/mergeObjects.ts","../src/operations/patchOneById.ts","../src/operations/deleteOneById.ts","../src/operations/createMany.ts","../src/operations/getMany.ts","../src/operations/deleteMany.ts","../src/operations/patchMany.ts","../src/operations/replaceMany.ts","../src/operations/list.ts","../src/operations/reload.ts","../src/operations/exists.ts","../src/operations/count.ts","../src/operations/clear.ts","../src/operations/save.ts","../src/operations/findOne.ts","../src/index.ts"],"names":["JsonDbModeEnum","uuidv4","resolveEntityId","response","path","fs","Config","JsonDB"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,IAAK,cAAA,qBAAAA,eAAAA,KAAL;AACL,EAAAA,gBAAA,aAAA,CAAA,GAAc,aAAA;AACd,EAAAA,gBAAA,YAAA,CAAA,GAAa,YAAA;AACb,EAAAA,gBAAA,MAAA,CAAA,GAAO,MAAA;AAHG,EAAA,OAAAA,eAAAA;AAAA,CAAA,EAAA,cAAA,IAAA,EAAA;;;ACVL,IAAM,iBAAA,GAA4B,GAAA;AAwBlC,IAAM,cAAA,GAAyB,GAAA;;;ACd/B,IAAM,kBAAA,GAAqB,CAAC,UAAA,KAA6B;AAC9D,EAAA,IAAI,CAAC,UAAA,EAAY;AACf,IAAA,MAAM,IAAI,MAAM,6BAA6B,CAAA;AAAA,EAC/C;AACF,CAAA;AAeO,IAAM,UAAA,GAAa,CAAC,EAAA,KAAqB;AAC9C,EAAA,IAAI,CAAC,EAAA,EAAI;AACP,IAAA,MAAM,IAAI,MAAM,gBAAgB,CAAA;AAAA,EAClC;AACF,CAAA;AAgBO,IAAM,YAAA,GAAe,CAAC,IAAA,KAAoB;AAC/C,EAAA,IAAI,CAAC,IAAA,EAAM;AACT,IAAA,MAAM,IAAI,MAAM,kBAAkB,CAAA;AAAA,EACpC;AACF,CAAA;AAiBO,IAAM,WAAA,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,GAAQ,YAAA,CAAa,QAAA,EAAU,OAAO,CAAA;AAC5C,EAAA,MAAM,IAAA,GAAO,WAAA,CAAY,QAAA,EAAU,OAAO,CAAA;AAC1C,EAAA,MAAM,OAAA,GAAU,cAAA,CAAe,QAAA,EAAU,OAAO,CAAA;AAGhD,EAAA,OAAO;AAAA;AAAA,IAEL,SAAA;AAAA,IACA,UAAA;AAAA,IACA,cAAA;AAAA,IACA,YAAA;AAAA,IACA,aAAA;AAAA;AAAA,IAGA,UAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,SAAA;AAAA,IACA,WAAA;AAAA;AAAA,IAGA,IAAA;AAAA;AAAA,IAGA,MAAA;AAAA,IACA,KAAA;AAAA,IACA,KAAA;AAAA,IACA,IAAA;AAAA,IACA,OAAA;AAAA;AAAA,IAGA,OAAO,MAAM,EAAA;AAAA,IACb,WAAW,MAAM,QAAA;AAAA,IACjB;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["import {Config, JsonDB} from 'node-json-db';\n\n/**\n * Optional Logger interface for adapter operations\n */\nexport interface Logger {\n  debug: (message: string, meta?: any) => void;\n  info: (message: string, meta?: any) => void;\n  warn: (message: string, meta?: any) => void;\n  error: (message: string, meta?: any) => void;\n}\n\n/**\n * Database configuration mode enum\n */\nexport enum JsonDbModeEnum {\n  DEVELOPMENT = 'development',\n  PRODUCTION = 'production',\n  TEST = 'test',\n}\n\n/**\n * Settings for JsonDB adapter initialization\n */\nexport type JsonDbAdapterSettings = {\n  /**\n   * Database filename or path\n   * Supports both simple filenames and paths:\n   * - 'test-db-name' -> creates test-db-name.json in current directory\n   * - 'test-db-name.json' -> creates test-db-name.json in current directory\n   * - 'data/test-db-name' -> creates test-db-name.json in data folder\n   * - 'data/test-db-name.json' -> creates test-db-name.json in data folder\n   * - 'data/nested/test-db' -> creates test-db.json in data/nested folder\n   *\n   * The adapter will automatically create the directory if it doesn't exist\n   */\n  filename: string;\n  saveOnPush: boolean;\n  humanReadable: boolean;\n  separator?: string;\n  mode?: JsonDbModeEnum;\n  logger?: Logger;\n};\n\n/**\n * Base entity interface with id field\n */\nexport interface BaseEntity {\n  id: string;\n  [key: string]: any;\n}\n\n/**\n * Generic entity with timestamp fields\n */\nexport interface TimestampedEntity extends BaseEntity {\n  createdAt: string;\n  updatedAt: string;\n}\n\n/**\n * Request type for creating a single entity\n */\nexport interface CreateOneRequest<T extends BaseEntity> {\n  collection: string;\n  data: Omit<T, 'id'> | T;\n}\n\n/**\n * Response type for creating a single entity\n */\nexport interface CreateOneResponse<T extends BaseEntity> {\n  entity: T;\n  success: boolean;\n}\n\n/**\n * Request type for creating multiple entities\n */\nexport interface CreateManyRequest<T extends BaseEntity> {\n  collection: string;\n  data: Array<Omit<T, 'id'> | T>;\n}\n\n/**\n * Response type for creating multiple entities\n */\nexport interface CreateManyResponse<T extends BaseEntity> {\n  entities: T[];\n  count: number;\n  success: boolean;\n}\n\n/**\n * Configuration for populating a reference field\n *\n * @example\n * ```typescript\n * // Simple - auto-detect collection\n * { field: 'categoryId' }\n *\n * // Advanced - explicit collection\n * { field: 'categoryId', from: 'categories' }\n *\n * // Cross-database\n * {\n *   field: 'categoryId',\n *   from: 'categories',\n *   adapter: categoryDbAdapter\n * }\n *\n * // Field selection\n * {\n *   field: 'categoryId',\n *   from: 'categories',\n *   select: ['id', 'name']\n * }\n * ```\n */\nexport interface PopulateConfig {\n  /**\n   * Field name to populate (e.g., 'categoryId', 'authorIds')\n   */\n  field: string;\n\n  /**\n   * Collection name to fetch from (e.g., 'categories')\n   * If not specified, auto-detected from field name:\n   * - 'categoryId' → 'categories'\n   * - 'authorId' → 'authors'\n   * - 'authorIds' → 'authors' (handles both singular and array refs)\n   */\n  from?: string;\n\n  /**\n   * Adapter instance to use for fetching referenced entities\n   * If not specified, uses the same adapter as the main query\n   *\n   * Use this for cross-database references:\n   * @example\n   * ```typescript\n   * const categoryAdapter = createJsonDbAdapter({ filename: 'categories-db' });\n   *\n   * await adapter.list({\n   *   collection: 'books',\n   *   populate: [{ field: 'categoryId', adapter: categoryAdapter }]\n   * });\n   * ```\n   */\n  adapter?: JsonDbAdapter;\n\n  /**\n   * Fields to select from populated entity\n   * If not specified, returns entire entity\n   *\n   * @example\n   * ```typescript\n   * // Only populate id and name\n   * { field: 'categoryId', select: ['id', 'name'] }\n   * ```\n   */\n  select?: string[];\n\n  /**\n   * Behavior when referenced entity is not found\n   *\n   * - 'null' (default): Set field to null\n   * - 'skip': Keep original ID value\n   * - 'throw': Throw error\n   *\n   * @example\n   * ```typescript\n   * // Book references category 'cat-999' which doesn't exist\n   *\n   * // With 'null' (default):\n   * { id: 'book-1', categoryId: null }\n   *\n   * // With 'skip':\n   * { id: 'book-1', categoryId: 'cat-999' }\n   *\n   * // With 'throw':\n   * // Error: Referenced entity not found: cat-999\n   * ```\n   */\n  onNotFound?: 'null' | 'skip' | 'throw';\n\n  /**\n   * Nested population configuration\n   * Allows populating references within populated entities\n   *\n   * @example\n   * ```typescript\n   * // Book → Author → Country\n   * {\n   *   field: 'authorId',\n   *   populate: [\n   *     { field: 'countryId' }\n   *   ]\n   * }\n   * ```\n   *\n   * Note: Nested population is not implemented in Phase 1-2\n   */\n  populate?: PopulateConfig[];\n}\n\n/**\n * Populate parameter - can be simple string array or advanced config\n *\n * @example\n * ```typescript\n * // Simple string array (auto-detects collections)\n * populate: ['categoryId', 'authorId']\n *\n * // Advanced config array\n * populate: [\n *   { field: 'categoryId', from: 'categories' },\n *   { field: 'authorId', from: 'authors', select: ['id', 'name'] }\n * ]\n * ```\n */\nexport type PopulateParam = string[] | PopulateConfig[];\n\n/**\n * Request type for getting a single entity by ID\n */\nexport interface GetOneByIdRequest {\n  collection: string;\n  id: string;\n  populate?: PopulateParam;\n  /** Reload database from disk before querying (useful for multi-process scenarios) */\n  reload?: boolean;\n}\n\n/**\n * Response type for getting a single entity\n */\nexport interface GetOneByIdResponse<T extends BaseEntity> {\n  entity: T | null;\n  found: boolean;\n}\n\n/**\n * Request type for replacing an entity by ID\n */\nexport interface ReplaceOneByIdRequest<T extends BaseEntity> {\n  collection: string;\n  id: string;\n  data: Omit<T, 'id'>;\n}\n\n/**\n * Response type for replacing an entity\n */\nexport interface ReplaceOneByIdResponse<T extends BaseEntity> {\n  entity: T;\n  success: boolean;\n}\n\n/**\n * Request type for patching an entity by ID\n */\nexport interface PatchOneByIdRequest {\n  collection: string;\n  id: string;\n  data: Partial<BaseEntity>;\n}\n\n/**\n * Response type for patching an entity\n */\nexport interface PatchOneByIdResponse<T extends BaseEntity> {\n  entity: T;\n  success: boolean;\n}\n\n/**\n * Request type for deleting a single entity by ID\n */\nexport interface DeleteOneByIdRequest {\n  collection: string;\n  id: string;\n}\n\n/**\n * Response type for deleting a single entity\n */\nexport interface DeleteOneByIdResponse {\n  success: boolean;\n  deleted: boolean;\n}\n\n/**\n * Request type for getting multiple entities by IDs\n */\nexport interface GetManyRequest {\n  collection: string;\n  ids: string[];\n  populate?: PopulateParam;\n  /** Reload database from disk before querying (useful for multi-process scenarios) */\n  reload?: boolean;\n}\n\n/**\n * Response type for getting multiple entities\n */\nexport interface GetManyResponse<T extends BaseEntity> {\n  entities: T[];\n  count: number;\n  notFound: string[];\n}\n\n/**\n * Request type for deleting multiple entities\n */\nexport interface DeleteManyRequest {\n  collection: string;\n  ids: string[];\n}\n\n/**\n * Response type for deleting multiple entities\n */\nexport interface DeleteManyResponse {\n  count: number;\n  success: boolean;\n}\n\n/**\n * Request type for patching multiple entities\n */\nexport interface PatchManyRequest {\n  collection: string;\n  ids: string[];\n  data: Partial<BaseEntity>;\n}\n\n/**\n * Response type for patching multiple entities\n */\nexport interface PatchManyResponse<T extends BaseEntity> {\n  entities: T[];\n  count: number;\n  notFound: string[];\n  success: boolean;\n}\n\n/**\n * Request type for replacing multiple entities\n */\nexport interface ReplaceManyRequest<T extends BaseEntity> {\n  collection: string;\n  updates: Array<{ id: string; data: Omit<T, 'id'> }>;\n}\n\n/**\n * Response type for replacing multiple entities\n */\nexport interface ReplaceManyResponse<T extends BaseEntity> {\n  entities: T[];\n  count: number;\n  notFound: string[];\n  success: boolean;\n}\n\n/**\n * Request type for listing entities\n */\nexport interface ListRequest<T extends BaseEntity = BaseEntity> {\n  collection: string;\n  filter?: (entity: T) => boolean;\n  populate?: PopulateParam;\n  /** Reload database from disk before querying (useful for multi-process scenarios) */\n  reload?: boolean;\n}\n\n/**\n * Response type for listing entities\n */\nexport interface ListResponse<T extends BaseEntity> {\n  entities: T[];\n  total: number;\n}\n\n/**\n * Response type for reload operation\n */\nexport interface ReloadResponse {\n  success: boolean;\n}\n\n/**\n * Request type for checking entity existence\n */\nexport interface ExistsRequest {\n  collection: string;\n  id: string;\n  /** Reload database from disk before querying (useful for multi-process scenarios) */\n  reload?: boolean;\n}\n\n/**\n * Response type for existence check\n */\nexport interface ExistsResponse {\n  exists: boolean;\n}\n\n/**\n * Request type for counting entities\n */\nexport interface CountRequest<T extends BaseEntity = BaseEntity> {\n  collection: string;\n  filter?: (entity: T) => boolean;\n  /** Reload database from disk before querying (useful for multi-process scenarios) */\n  reload?: boolean;\n}\n\n/**\n * Response type for count operation\n */\nexport interface CountResponse {\n  count: number;\n}\n\n/**\n * Request type for clearing a collection\n */\nexport interface ClearRequest {\n  collection: string;\n}\n\n/**\n * Response type for clear operation\n */\nexport interface ClearResponse {\n  success: boolean;\n  deletedCount: number;\n}\n\n/**\n * Response type for save operation\n */\nexport interface SaveResponse {\n  success: boolean;\n}\n\n/**\n * Request type for finding one entity\n */\nexport interface FindOneRequest<T extends BaseEntity = BaseEntity> {\n  collection: string;\n  filter: (entity: T) => boolean;\n  populate?: PopulateParam;\n  /** Reload database from disk before querying (useful for multi-process scenarios) */\n  reload?: boolean;\n}\n\n/**\n * Response type for findOne operation\n */\nexport interface FindOneResponse<T extends BaseEntity> {\n  entity: T | null;\n  found: boolean;\n}\n\n/**\n * JsonDB Adapter interface with all operations\n */\nexport interface JsonDbAdapter {\n  // Single entity operations\n  createOne: <T extends BaseEntity>(\n    request: CreateOneRequest<T>\n  ) => Promise<CreateOneResponse<T>>;\n\n  getOneById: <T extends BaseEntity>(\n    request: GetOneByIdRequest\n  ) => Promise<GetOneByIdResponse<T>>;\n\n  replaceOneById: <T extends BaseEntity>(\n    request: ReplaceOneByIdRequest<T>\n  ) => Promise<ReplaceOneByIdResponse<T>>;\n\n  patchOneById: <T extends BaseEntity>(\n    request: PatchOneByIdRequest\n  ) => Promise<PatchOneByIdResponse<T>>;\n\n  deleteOneById: (\n    request: DeleteOneByIdRequest\n  ) => Promise<DeleteOneByIdResponse>;\n\n  // Batch operations\n  createMany: <T extends BaseEntity>(\n    request: CreateManyRequest<T>\n  ) => Promise<CreateManyResponse<T>>;\n\n  getMany: <T extends BaseEntity>(\n    request: GetManyRequest\n  ) => Promise<GetManyResponse<T>>;\n\n  deleteMany: (request: DeleteManyRequest) => Promise<DeleteManyResponse>;\n\n  patchMany: <T extends BaseEntity>(\n    request: PatchManyRequest\n  ) => Promise<PatchManyResponse<T>>;\n\n  replaceMany: <T extends BaseEntity>(\n    request: ReplaceManyRequest<T>\n  ) => Promise<ReplaceManyResponse<T>>;\n\n  // List operation\n  list: <T extends BaseEntity>(request: ListRequest<T>) => Promise<ListResponse<T>>;\n\n  // Utility operations\n  exists: (request: ExistsRequest) => Promise<ExistsResponse>;\n\n  count: <T extends BaseEntity>(\n    request: CountRequest<T>\n  ) => Promise<CountResponse>;\n\n  clear: (request: ClearRequest) => Promise<ClearResponse>;\n\n  save: () => Promise<SaveResponse>;\n\n  findOne: <T extends BaseEntity>(\n    request: FindOneRequest<T>\n  ) => Promise<FindOneResponse<T>>;\n\n  // Utility methods\n  getDb: () => JsonDB;\n  getConfig: () => JsonDbAdapterSettings;\n  reload: () => Promise<ReloadResponse>;\n}\n\n/**\n * Internal type for database state management\n */\nexport interface DbState {\n  db: JsonDB;\n  config: Config;\n}\n\n// Re-export populate types for convenience\n","import { JsonDbModeEnum } from './types';\n\n/**\n * Default separator for JsonDB paths\n */\nexport const DEFAULT_SEPARATOR: string = '/';\n\n/**\n * Default save on push setting\n */\nexport const DEFAULT_SAVE_ON_PUSH: boolean = true;\n\n/**\n * Default human readable setting\n */\nexport const DEFAULT_HUMAN_READABLE: boolean = true;\n\n/**\n * Default filename patterns by mode\n */\nexport const DEFAULT_FILENAMES: Record<JsonDbModeEnum, string> = {\n  [JsonDbModeEnum.DEVELOPMENT]: 'db-dev',\n  [JsonDbModeEnum.PRODUCTION]: 'db-prod',\n  [JsonDbModeEnum.TEST]: 'db-test',\n};\n\n/**\n * Maximum batch size for operations\n */\nexport const MAX_BATCH_SIZE: number = 1000;\n","import { MAX_BATCH_SIZE } from '../const';\n\n/**\n * Validates that collection name is provided\n *\n * @param collection - Collection name to validate\n * @throws {Error} If collection name is missing or empty\n *\n * @example\n * ```typescript\n * validateCollection('users'); // OK\n * validateCollection('');      // Error: Collection name is required\n * validateCollection(null);    // Error: Collection name is required\n * ```\n */\nexport const validateCollection = (collection: string): void => {\n  if (!collection) {\n    throw new Error('Collection name is required');\n  }\n};\n\n/**\n * Validates that entity ID is provided\n *\n * @param id - Entity ID to validate\n * @throws {Error} If ID is missing or empty\n *\n * @example\n * ```typescript\n * validateId('user-123'); // OK\n * validateId('');         // Error: ID is required\n * validateId(null);       // Error: ID is required\n * ```\n */\nexport const validateId = (id: string): void => {\n  if (!id) {\n    throw new Error('ID is required');\n  }\n};\n\n/**\n * Validates that data is provided\n *\n * @param data - Data object to validate\n * @throws {Error} If data is missing, null, or undefined\n *\n * @example\n * ```typescript\n * validateData({ name: 'John' }); // OK\n * validateData({});               // OK (empty object is valid)\n * validateData(null);             // Error: Data is required\n * validateData(undefined);        // Error: Data is required\n * ```\n */\nexport const validateData = (data: any): void => {\n  if (!data) {\n    throw new Error('Data is required');\n  }\n};\n\n/**\n * Validates that IDs array is valid and within batch size limit\n *\n * @param ids - Array of entity IDs to validate\n * @throws {Error} If ids is not an array\n * @throws {Error} If batch size exceeds MAX_BATCH_SIZE\n *\n * @example\n * ```typescript\n * validateIds(['id1', 'id2']);     // OK\n * validateIds([]);                 // OK (empty array is valid)\n * validateIds('not-an-array');     // Error: IDs must be an array\n * validateIds(new Array(1001));    // Error: Batch size exceeds maximum of 1000\n * ```\n */\nexport const validateIds = (ids: string[]): void => {\n  if (!ids || !Array.isArray(ids)) {\n    throw new Error('IDs must be an array');\n  }\n\n  if (ids.length > MAX_BATCH_SIZE) {\n    throw new Error(`Batch size exceeds maximum of ${MAX_BATCH_SIZE}`);\n  }\n};\n\n/**\n * Validates that data array is valid and within batch size limit\n *\n * @param data - Array of entities to validate\n * @throws {Error} If data is not an array\n * @throws {Error} If batch size exceeds MAX_BATCH_SIZE\n *\n * @example\n * ```typescript\n * validateDataArray([{ name: 'John' }]); // OK\n * validateDataArray([]);                 // OK (empty array is valid)\n * validateDataArray('not-an-array');     // Error: Data must be an array\n * validateDataArray(new Array(1001));    // Error: Batch size exceeds maximum of 1000\n * ```\n */\nexport const validateDataArray = (data: any[]): void => {\n  if (!data || !Array.isArray(data)) {\n    throw new Error('Data must be an array');\n  }\n\n  if (data.length > MAX_BATCH_SIZE) {\n    throw new Error(`Batch size exceeds maximum of ${MAX_BATCH_SIZE}`);\n  }\n};\n\n/**\n * Validates that filter function is provided\n *\n * @param filter - Filter function to validate\n * @throws {Error} If filter is not a function\n *\n * @example\n * ```typescript\n * validateFilter((x) => x.active);  // OK\n * validateFilter('not-a-function'); // Error: Filter must be a function\n * validateFilter(null);             // Error: Filter must be a function\n * ```\n */\nexport const validateFilter = (filter: any): void => {\n  if (typeof filter !== 'function') {\n    throw new Error('Filter must be a function');\n  }\n};\n\n/**\n * Validates that updates array is valid and within batch size limit\n *\n * @param updates - Array of update objects to validate\n * @throws {Error} If updates is not an array\n * @throws {Error} If batch size exceeds MAX_BATCH_SIZE\n *\n * @example\n * ```typescript\n * validateUpdates([{ id: 'id1', data: { name: 'John' } }]); // OK\n * validateUpdates([]);                                       // OK (empty array is valid)\n * validateUpdates('not-an-array');                           // Error: Updates must be an array\n * validateUpdates(new Array(1001));                          // Error: Batch size exceeds maximum of 1000\n * ```\n */\nexport const validateUpdates = (updates: any[]): void => {\n  if (!updates || !Array.isArray(updates)) {\n    throw new Error('Updates must be an array');\n  }\n\n  if (updates.length > MAX_BATCH_SIZE) {\n    throw new Error(`Batch size exceeds maximum of ${MAX_BATCH_SIZE}`);\n  }\n};\n\n/**\n * Validates that all IDs in the data array are unique\n *\n * @param data - Array of entities with id field\n * @param operation - Operation name for error message context\n * @throws {Error} If duplicate IDs are found\n *\n * @example\n * ```typescript\n * validateUniqueIds([{ id: 'id1' }, { id: 'id2' }], 'createMany'); // OK\n * validateUniqueIds([{ id: 'id1' }, { id: 'id1' }], 'createMany'); // Error: Duplicate IDs found in createMany: id1\n * validateUniqueIds([], 'createMany');                              // OK (empty array is valid)\n * ```\n */\nexport const validateUniqueIds = (\n  data: Array<{ id: string }>,\n  operation: string\n): void => {\n  const ids = new Set<string>();\n  const duplicates = new Set<string>();\n\n  data.forEach((item: { id: string }) => {\n    if (ids.has(item.id)) {\n      duplicates.add(item.id);\n    } else {\n      ids.add(item.id);\n    }\n  });\n\n  if (duplicates.size > 0) {\n    const duplicateList: string = Array.from(duplicates).join(', ');\n    throw new Error(`Duplicate IDs found in ${operation}: ${duplicateList}`);\n  }\n};\n","import { v4 as uuidv4 } from 'uuid';\nimport {\n  JsonDbAdapterSettings,\n  CreateOneRequest,\n  CreateOneResponse,\n  BaseEntity,\n  DbState,\n  Logger,\n} from '../types';\nimport { validateCollection, validateData } from '../utils/validators';\n\n/**\n * Resolves entity ID - uses provided ID if exists, otherwise generates new UUID\n *\n * @param data - Entity data that may contain an ID\n * @param logger - Optional logger\n * @returns Provided ID or generated UUID\n */\nconst resolveEntityId = <T extends BaseEntity>(\n  data: Omit<T, 'id'> | T,\n  logger?: Logger\n): string => {\n  const providedId: string | undefined = (data as Partial<T>).id;\n\n  if (providedId) {\n    logger?.debug('Using predefined ID', { id: providedId });\n    return providedId;\n  }\n\n  // Generate unique ID\n  const id: string = uuidv4();\n  logger?.debug('Generated new ID', { id });\n  return id;\n};\n\nexport const createOneFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async <T extends BaseEntity>(\n    request: CreateOneRequest<T>\n  ): Promise<CreateOneResponse<T>> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting createOne operation', { request });\n\n      const { collection, data } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n      validateData(data);\n\n      // Resolve ID: use provided ID or generate new UUID\n      const id: string = resolveEntityId<T>(data, logger);\n\n      // Create entity with ID\n      const entity: T = {\n        ...data,\n        id,\n      } as T;\n\n      // Use direct UUID path to store entity - O(1) operation\n      // json-db automatically creates the collection hierarchy when pushing to a non-existent path\n      await dbState.db.push(`/${collection}/${id}`, entity);\n\n      const response: CreateOneResponse<T> = {\n        entity,\n        success: true,\n      };\n\n      logger?.debug('createOne completed', response);\n      return response;\n    } catch (error) {\n      logger?.error('createOne failed', error);\n      throw error;\n    }\n  };\n","import {BaseEntity, DbState, JsonDbAdapterSettings, Logger, PopulateConfig, PopulateParam} from '../types';\n\n/**\n * Infer collection name from field name\n *\n * Conventions:\n * - Removes 'Id' or 'Ids' suffix\n * - Handles common irregular plurals\n * - Applies simple pluralization rules\n *\n * @param fieldName - Field name (e.g., 'categoryId', 'authorIds')\n * @returns Collection name (e.g., 'categories', 'authors')\n *\n * @example\n * ```typescript\n * inferCollectionName('categoryId')  // → 'categories'\n * inferCollectionName('authorId')    // → 'authors'\n * inferCollectionName('authorIds')   // → 'authors'\n * inferCollectionName('personId')    // → 'people'\n * ```\n */\nexport const inferCollectionName = (fieldName: string): string => {\n  // Remove 'Id' or 'Ids' suffix\n  const base: string = fieldName.replace(/(Id|Ids)$/, '');\n\n  // Handle common irregular plurals\n  const irregulars: Record<string, string> = {\n    person: 'people',\n    child: 'children',\n    category: 'categories',\n    company: 'companies',\n    city: 'cities',\n  };\n\n  if (irregulars[base]) {\n    return irregulars[base];\n  }\n\n  // Simple pluralization rules\n  if (base.endsWith('y')) {\n    // category → categories\n    return base.slice(0, -1) + 'ies';\n  }\n\n  if (base.endsWith('s') || base.endsWith('x') || base.endsWith('ch') || base.endsWith('sh')) {\n    // class → classes, box → boxes, church → churches, dish → dishes\n    return base + 'es';\n  }\n\n  // Default: just add 's'\n  return base + 's';\n};\n\n/**\n * Normalize populate parameter to PopulateConfig array\n *\n * Converts string array format to PopulateConfig array format\n *\n * @param param - Populate parameter (string[] or PopulateConfig[])\n * @returns Normalized PopulateConfig array\n *\n * @example\n * ```typescript\n * normalizePopulateParam(['categoryId', 'authorId'])\n * // → [{ field: 'categoryId' }, { field: 'authorId' }]\n *\n * normalizePopulateParam([{ field: 'categoryId', from: 'categories' }])\n * // → [{ field: 'categoryId', from: 'categories' }]\n * ```\n */\nexport const normalizePopulateParam = (param: PopulateParam): PopulateConfig[] => {\n  if (Array.isArray(param) && param.length > 0 && typeof param[0] === 'string') {\n    // String array format - convert to PopulateConfig[]\n    return (param as string[]).map((field: string) => ({ field }));\n  }\n\n  return param as PopulateConfig[];\n};\n\n/**\n * Collect unique IDs from entities for a given field\n *\n * Handles both single reference fields (categoryId: string)\n * and array reference fields (authorIds: string[])\n *\n * @param entities - Array of entities\n * @param field - Field name to extract IDs from\n * @returns Array of unique IDs\n *\n * @example\n * ```typescript\n * const books = [\n *   { id: 'b1', categoryId: 'cat-1' },\n *   { id: 'b2', categoryId: 'cat-2' },\n *   { id: 'b3', categoryId: 'cat-1' } // duplicate\n * ];\n *\n * collectUniqueIds(books, 'categoryId');\n * // → ['cat-1', 'cat-2']\n * ```\n */\nexport const collectUniqueIds = <T>(entities: T[], field: string): string[] => {\n  const ids = new Set<string>();\n\n  entities.forEach((entity: T) => {\n    const value = entity[field as keyof T];\n\n    if (Array.isArray(value)) {\n      // Handle array references (e.g., authorIds: string[])\n      value.forEach((id: any) => {\n        if (id && typeof id === 'string') {\n          ids.add(id);\n        }\n      });\n    } else if (value && typeof value === 'string') {\n      // Handle single reference (e.g., categoryId: string)\n      ids.add(value);\n    }\n    // Ignore null/undefined values\n  });\n\n  return Array.from(ids);\n};\n\n/**\n * Select specific fields from an entity\n *\n * @param entity - Entity to select fields from\n * @param fields - Array of field names to include\n * @returns New object with only selected fields\n *\n * @example\n * ```typescript\n * const category = {\n *   id: 'cat-1',\n *   name: 'Programming',\n *   description: 'Tech books',\n *   createdAt: '2024-01-01'\n * };\n *\n * selectFields(category, ['id', 'name']);\n * // → { id: 'cat-1', name: 'Programming' }\n * ```\n */\nexport const selectFields = <T>(entity: T, fields: string[]): Partial<T> => {\n  const result: any = {};\n\n  fields.forEach((field: string) => {\n    if (field in (entity as object)) {\n      result[field] = entity[field as keyof T];\n    }\n  });\n\n  return result;\n};\n\n/**\n * Handle missing reference based on onNotFound behavior\n *\n * @param id - ID that was not found\n * @param behavior - Behavior to apply\n * @returns Value to use for missing reference\n * @throws Error if behavior is 'throw'\n *\n * @example\n * ```typescript\n * handleNotFound('cat-999', 'null')  // → null\n * handleNotFound('cat-999', 'skip')  // → 'cat-999'\n * handleNotFound('cat-999', 'throw') // throws Error\n * ```\n */\nexport const handleNotFound = (id: string, behavior: 'null' | 'skip' | 'throw'): any => {\n  switch (behavior) {\n    case 'null':\n      return null;\n    case 'skip':\n      return id; // Keep original ID\n    case 'throw':\n      throw new Error(`Referenced entity not found: ${id}`);\n    default:\n      return null;\n  }\n};\n\n/**\n * Populate a single field across all entities\n *\n * Uses batch fetching to avoid N+1 query problem\n *\n * @param entities - Entities to populate\n * @param config - Population configuration\n * @param dbState - Database state\n * @param settings - Adapter settings\n * @param logger - Optional logger\n */\nconst populateSingleField = async <T extends BaseEntity>(\n  entities: T[],\n  config: PopulateConfig,\n  dbState: DbState,\n  _settings: JsonDbAdapterSettings,\n  logger?: Logger\n): Promise<void> => {\n  const { field, from, select, onNotFound = 'null' } = config;\n\n  // Determine collection name (auto-detect if not specified)\n  const collection: string = from || inferCollectionName(field);\n\n  // Collect unique IDs to fetch (handles both single and array refs)\n  const ids: string[] = collectUniqueIds(entities, field);\n\n  if (ids.length === 0) {\n    logger?.debug('No IDs to populate for field', { field });\n    return;\n  }\n\n  logger?.debug('Populating field', {\n    field,\n    collection,\n    idsCount: ids.length,\n  });\n\n  // Batch fetch referenced entities\n  // We need to use getMany-like logic directly since we have dbState\n  const referencedEntities: BaseEntity[] = [];\n\n  try {\n    // Load entire collection\n    const collectionMap: Record<string, BaseEntity> = await dbState.db\n      .getData(`/${collection}`)\n      .catch(() => ({}));\n\n    // Extract only the IDs we need\n    ids.forEach((id: string) => {\n      if (collectionMap[id]) {\n        referencedEntities.push(collectionMap[id]);\n      }\n    });\n  } catch (error: unknown) {\n    logger?.debug('Failed to load collection for populate', { collection, error });\n    // Collection doesn't exist or error - all references will be handled by onNotFound\n  }\n\n  // Create lookup map with optional field selection\n  const entityMap = new Map<string, any>(\n    referencedEntities.map((entity: BaseEntity) => [\n      entity.id,\n      select ? selectFields(entity, select) : entity,\n    ])\n  );\n\n  // Populate each entity\n  entities.forEach((entity: T) => {\n    const refValue = entity[field as keyof T];\n\n    if (Array.isArray(refValue)) {\n      // Handle array references (e.g., authorIds: string[])\n      entity[field as keyof T] = refValue.map((id: any) =>\n        entityMap.get(id) || handleNotFound(id, onNotFound)\n      ) as any;\n    } else if (typeof refValue === 'string') {\n      // Handle single reference (e.g., categoryId: string)\n      entity[field as keyof T] = (entityMap.get(refValue) ||\n        handleNotFound(refValue, onNotFound)) as any;\n    }\n    // Ignore null/undefined/other types\n  });\n\n  logger?.debug('Field populated successfully', {\n    field,\n    foundCount: referencedEntities.length,\n    requestedCount: ids.length,\n  });\n};\n\n/**\n * Populate reference fields in entities\n *\n * Main entry point for population functionality.\n * Automatically resolves reference fields by fetching related entities.\n *\n * @param entities - Entities to populate\n * @param populateParam - Population configuration (string[] or PopulateConfig[])\n * @param dbState - Database state\n * @param settings - Adapter settings\n * @param logger - Optional logger\n * @returns Populated entities (mutated in place)\n *\n * @example\n * ```typescript\n * // Simple usage\n * const books = [\n *   { id: 'b1', title: 'TS Guide', categoryId: 'cat-1' }\n * ];\n *\n * await populateEntities(books, ['categoryId'], dbState, settings);\n * // books[0].categoryId is now the full category object\n *\n * // Advanced usage\n * await populateEntities(\n *   books,\n *   [\n *     { field: 'categoryId', select: ['id', 'name'] },\n *     { field: 'authorId', from: 'authors' }\n *   ],\n *   dbState,\n *   settings\n * );\n * ```\n */\nexport const populateEntities = async <T extends BaseEntity>(\n  entities: T[],\n  populateParam: PopulateParam,\n  dbState: DbState,\n  settings: JsonDbAdapterSettings,\n  logger?: Logger\n): Promise<T[]> => {\n  // Early return if no population requested\n  if (!populateParam || populateParam.length === 0) {\n    return entities;\n  }\n\n  // Early return if no entities\n  if (entities.length === 0) {\n    return entities;\n  }\n\n  logger?.debug('Starting populate operation', {\n    entitiesCount: entities.length,\n    populateFields: populateParam,\n  });\n\n  // Normalize to PopulateConfig[]\n  const configs: PopulateConfig[] = normalizePopulateParam(populateParam);\n\n  // Process each populate config sequentially\n  for (const config of configs) {\n    await populateSingleField(entities, config, dbState, settings, logger);\n  }\n\n  logger?.debug('Populate operation completed', {\n    entitiesCount: entities.length,\n    fieldsPopulated: configs.length,\n  });\n\n  return entities;\n};\n","import {\n  JsonDbAdapterSettings,\n  GetOneByIdRequest,\n  GetOneByIdResponse,\n  BaseEntity,\n  DbState,\n} from '../types';\nimport { populateEntities } from '../utils/populate';\nimport { validateCollection, validateId } from '../utils/validators';\n\nexport const getOneByIdFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async <T extends BaseEntity>(\n    request: GetOneByIdRequest\n  ): Promise<GetOneByIdResponse<T>> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting getOneById operation', { request });\n\n      const { collection, id, populate, reload } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n      validateId(id);\n\n      // Reload database if requested\n      if (reload) {\n        await dbState.db.reload();\n        logger?.debug('Database reloaded before query');\n      }\n\n      // Use direct UUID path lookup - O(1) access\n      try {\n        const entity: T = await dbState.db.getData(`/${collection}/${id}`);\n\n        // Apply populate if provided\n        let populatedEntity: T = entity;\n        if (populate) {\n          // Wrap single entity in array for populate function\n          const entities: T[] = [entity];\n\n          // Populate\n          await populateEntities(entities, populate, dbState, settings, logger);\n\n          // Unwrap\n          populatedEntity = entities[0]!;\n        }\n\n        const response: GetOneByIdResponse<T> = {\n          entity: populatedEntity,\n          found: true,\n        };\n\n        logger?.debug('getOneById completed', response);\n        return response;\n      } catch (error: unknown) {\n        // Entity not found (getData throws when path doesn't exist)\n        logger?.debug('Entity not found', { collection, id });\n        return {\n          entity: null,\n          found: false,\n        };\n      }\n    } catch (error) {\n      logger?.error('getOneById failed', error);\n      throw error;\n    }\n  };\n","import {\n  JsonDbAdapterSettings,\n  ReplaceOneByIdRequest,\n  ReplaceOneByIdResponse,\n  BaseEntity,\n  DbState,\n} from '../types';\nimport { validateCollection, validateId, validateData } from '../utils/validators';\n\nexport const replaceOneByIdFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async <T extends BaseEntity>(\n    request: ReplaceOneByIdRequest<T>\n  ): Promise<ReplaceOneByIdResponse<T>> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting replaceOneById operation', { request });\n\n      const { collection, id, data } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n      validateId(id);\n      validateData(data);\n\n      // Check if entity exists using direct UUID path lookup\n      try {\n        await dbState.db.getData(`/${collection}/${id}`);\n      } catch (error: unknown) {\n        throw new Error(`Entity with id ${id} not found in collection ${collection}`);\n      }\n\n      // Replace entity completely (keep only id from original)\n      const replacedEntity: T = {\n        ...data,\n        id,\n      } as T;\n\n      // Use direct UUID path to replace entity - O(1) access\n      await dbState.db.push(`/${collection}/${id}`, replacedEntity);\n\n      const response: ReplaceOneByIdResponse<T> = {\n        entity: replacedEntity,\n        success: true,\n      };\n\n      logger?.debug('replaceOneById completed', response);\n      return response;\n    } catch (error) {\n      logger?.error('replaceOneById failed', error);\n      throw error;\n    }\n  };\n","/**\n * Deep merge utility for patch operations\n *\n * Merges source object into target object recursively:\n * - Primitives: Replace with source value\n * - Arrays: Replace entirely (no item merging)\n * - Objects: Traverse recursively and merge properties\n * - Null/Undefined: Handle edge cases properly\n *\n * @param target - The target object to merge into\n * @param source - The source object with updates\n * @returns Merged object with deep merge applied\n *\n * @example\n * ```typescript\n * const target = {\n *   name: 'John',\n *   settings: { theme: 'dark', lang: 'en' },\n *   tags: ['user']\n * };\n *\n * const source = {\n *   settings: { theme: 'light' },\n *   tags: ['admin']\n * };\n *\n * const result = mergeObjects(target, source);\n * // Result: {\n * //   name: 'John',\n * //   settings: { theme: 'light', lang: 'en' },\n * //   tags: ['admin']\n * // }\n * ```\n */\nexport const mergeObjects = <T extends Record<string, any>>(\n  target: T,\n  source: Partial<T>\n): T => {\n  // Create a shallow copy of target to avoid mutation\n  const result: T = { ...target };\n\n  // Iterate over source properties\n  for (const key in source) {\n    // Skip inherited properties\n    if (!Object.prototype.hasOwnProperty.call(source, key)) {\n      continue;\n    }\n\n    const sourceValue: any = source[key];\n    const targetValue: any = result[key];\n\n    // Skip undefined values (preserve target value)\n    if (sourceValue === undefined) {\n      continue;\n    }\n\n    // Handle null - replace target value with null\n    if (sourceValue === null) {\n      result[key] = null as any;\n      continue;\n    }\n\n    // Handle arrays - replace entirely, don't merge items\n    if (Array.isArray(sourceValue)) {\n      result[key] = sourceValue as any;\n      continue;\n    }\n\n    // Handle objects - deep merge recursively\n    if (\n      typeof sourceValue === 'object' &&\n      targetValue !== null &&\n      targetValue !== undefined &&\n      typeof targetValue === 'object' &&\n      !Array.isArray(targetValue)\n    ) {\n      result[key] = mergeObjects(targetValue, sourceValue) as any;\n      continue;\n    }\n\n    // Handle primitives - replace target value\n    result[key] = sourceValue as any;\n  }\n\n  return result;\n};\n\n/**\n * Type guard to check if value is a plain object\n */\nexport const isPlainObject = (value: any): value is Record<string, any> => {\n  return (\n    value !== null &&\n    typeof value === 'object' &&\n    !Array.isArray(value) &&\n    !(value instanceof Date) &&\n    !(value instanceof RegExp)\n  );\n};\n","import {\n  JsonDbAdapterSettings,\n  PatchOneByIdRequest,\n  PatchOneByIdResponse,\n  BaseEntity,\n  DbState,\n} from '../types';\nimport { mergeObjects } from '../utils';\nimport { validateCollection, validateId, validateData } from '../utils/validators';\n\nexport const patchOneByIdFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async <T extends BaseEntity>(\n    request: PatchOneByIdRequest\n  ): Promise<PatchOneByIdResponse<T>> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting patchOneById operation', { request });\n\n      const { collection, id, data } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n      validateId(id);\n      validateData(data);\n\n      // Load entity using direct UUID path lookup - O(1) access\n      let existingEntity: T;\n      try {\n        existingEntity = await dbState.db.getData(`/${collection}/${id}`);\n      } catch (error: unknown) {\n        throw new Error(`Entity with id ${id} not found in collection ${collection}`);\n      }\n\n      // Apply deep merge using custom mergeObjects utility\n      const patchedEntity: T = mergeObjects(existingEntity, data) as T;\n\n      // Ensure id cannot be changed\n      patchedEntity.id = id;\n\n      // Use direct UUID path to save patched entity - O(1) access\n      await dbState.db.push(`/${collection}/${id}`, patchedEntity);\n\n      const response: PatchOneByIdResponse<T> = {\n        entity: patchedEntity,\n        success: true,\n      };\n\n      logger?.debug('patchOneById completed', response);\n      return response;\n    } catch (error) {\n      logger?.error('patchOneById failed', error);\n      throw error;\n    }\n  };\n","import {\n  JsonDbAdapterSettings,\n  DeleteOneByIdRequest,\n  DeleteOneByIdResponse,\n  DbState,\n} from '../types';\nimport { validateCollection, validateId } from '../utils/validators';\n\nexport const deleteOneByIdFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async (request: DeleteOneByIdRequest): Promise<DeleteOneByIdResponse> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting deleteOneById operation', { request });\n\n      const { collection, id } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n      validateId(id);\n\n      // Use direct UUID path deletion - O(1) access\n      try {\n        await dbState.db.delete(`/${collection}/${id}`);\n\n        const response: DeleteOneByIdResponse = {\n          success: true,\n          deleted: true,\n        };\n\n        logger?.debug('deleteOneById completed', response);\n        return response;\n      } catch (error: unknown) {\n        // Entity not found (delete throws when path doesn't exist)\n        logger?.debug('Entity not found', { collection, id });\n        return {\n          success: true,\n          deleted: false,\n        };\n      }\n    } catch (error) {\n      logger?.error('deleteOneById failed', error);\n      throw error;\n    }\n  };\n","import { v4 as uuidv4 } from 'uuid';\nimport {\n  JsonDbAdapterSettings,\n  CreateManyRequest,\n  CreateManyResponse,\n  BaseEntity,\n  DbState,\n  Logger,\n} from '../types';\nimport {\n  validateCollection,\n  validateDataArray,\n  validateUniqueIds,\n} from '../utils/validators';\n\n/**\n * Resolves entity ID - uses provided ID if exists, otherwise generates new UUID\n *\n * @param data - Entity data that may contain an ID\n * @param logger - Optional logger\n * @returns Provided ID or generated UUID\n */\nconst resolveEntityId = <T extends BaseEntity>(\n  data: Omit<T, 'id'> | T,\n  logger?: Logger\n): string => {\n  const providedId: string | undefined = (data as Partial<T>).id;\n\n  if (providedId) {\n    logger?.debug('Using predefined ID', { id: providedId });\n    return providedId;\n  }\n\n  // Generate unique ID\n  const id: string = uuidv4();\n  logger?.debug('Generated new ID', { id });\n  return id;\n};\n\nexport const createManyFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async <T extends BaseEntity>(\n    request: CreateManyRequest<T>\n  ): Promise<CreateManyResponse<T>> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting createMany operation', { request });\n\n      const { collection, data } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n      validateDataArray(data);\n\n      // Handle empty array early\n      if (data.length === 0) {\n        return {\n          entities: [],\n          count: 0,\n          success: true,\n        };\n      }\n\n      // Resolve IDs for all items: use provided ID or generate new UUID\n      const entities: T[] = data.map((item: Omit<T, 'id'> | T): T => {\n        const id: string = resolveEntityId<T>(item, logger);\n        return {\n          ...item,\n          id,\n        } as T;\n      });\n\n      // Validate that all IDs are unique\n      validateUniqueIds(entities, 'createMany');\n\n      // Batch optimization: load current map, merge all entities in memory, single write\n      // This avoids N disk writes when saveOnPush is enabled\n      // json-db automatically creates the collection hierarchy if it doesn't exist\n      const currentCollection: Record<string, T> = await dbState.db\n        .getData(`/${collection}`)\n        .catch(() => ({}));\n\n      const updatedCollection: Record<string, T> = { ...currentCollection };\n      for (const entity of entities) {\n        updatedCollection[entity.id] = entity;\n      }\n\n      await dbState.db.push(`/${collection}`, updatedCollection);\n\n      const response: CreateManyResponse<T> = {\n        entities,\n        count: entities.length,\n        success: true,\n      };\n\n      logger?.debug('createMany completed', response);\n      return response;\n    } catch (error) {\n      logger?.error('createMany failed', error);\n      throw error;\n    }\n  };\n","import {\n  JsonDbAdapterSettings,\n  GetManyRequest,\n  GetManyResponse,\n  BaseEntity,\n  DbState,\n} from '../types';\nimport { populateEntities } from '../utils/populate';\nimport { validateCollection, validateIds } from '../utils/validators';\n\nexport const getManyFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async <T extends BaseEntity>(\n    request: GetManyRequest\n  ): Promise<GetManyResponse<T>> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting getMany operation', { request });\n\n      const { collection, ids, populate, reload } = request;\n\n      // Validate inputs (includes batch size check)\n      validateCollection(collection);\n      validateIds(ids);\n\n      // Reload database if requested\n      if (reload) {\n        await dbState.db.reload();\n        logger?.debug('Database reloaded before query');\n      }\n\n      // Handle empty array early\n      if (ids.length === 0) {\n        return {\n          entities: [],\n          count: 0,\n          notFound: [],\n        };\n      }\n\n      // Fetch each entity by direct UUID path lookup - O(1) per entity\n      const entities: T[] = [];\n      const notFound: string[] = [];\n\n      for (const id of ids) {\n        try {\n          const entity: T = await dbState.db.getData(`/${collection}/${id}`);\n          entities.push(entity);\n        } catch (error: unknown) {\n          // Entity not found\n          notFound.push(id);\n        }\n      }\n\n      // Apply to populate if provided\n      if (populate) {\n        await populateEntities(entities, populate, dbState, settings, logger);\n      }\n\n      const response: GetManyResponse<T> = {\n        entities,\n        count: entities.length,\n        notFound,\n      };\n\n      logger?.debug('getMany completed', response);\n      return response;\n    } catch (error) {\n      logger?.error('getMany failed', error);\n      throw error;\n    }\n  };\n","import {\n  JsonDbAdapterSettings,\n  DeleteManyRequest,\n  DeleteManyResponse,\n  DbState,\n} from '../types';\nimport { validateCollection, validateIds } from '../utils/validators';\n\nexport const deleteManyFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async (request: DeleteManyRequest): Promise<DeleteManyResponse> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting deleteMany operation', { request });\n\n      const { collection, ids } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n      validateIds(ids);\n\n      // Handle empty array early\n      if (ids.length === 0) {\n        return {\n          count: 0,\n          success: true,\n        };\n      }\n\n      // Batch optimization: load collection once, delete in memory, single write\n      // This avoids N disk writes when saveOnPush is enabled\n      const currentCollection: Record<string, any> = await dbState.db\n        .getData(`/${collection}`)\n        .catch(() => ({}));\n\n      let deletedCount: number = 0;\n\n      // Perform deletions in memory\n      for (const id of ids) {\n        if (currentCollection[id]) {\n          delete currentCollection[id];\n          deletedCount++;\n        } else {\n          // Entity not found - skip\n          logger?.debug('Entity not found for deletion', { id });\n        }\n      }\n\n      // Single disk write\n      await dbState.db.push(`/${collection}`, currentCollection);\n\n      const response: DeleteManyResponse = {\n        count: deletedCount,\n        success: true,\n      };\n\n      logger?.debug('deleteMany completed', response);\n      return response;\n    } catch (error) {\n      logger?.error('deleteMany failed', error);\n      throw error;\n    }\n  };\n","import {\n  JsonDbAdapterSettings,\n  PatchManyRequest,\n  PatchManyResponse,\n  BaseEntity,\n  DbState,\n} from '../types';\nimport { mergeObjects } from '../utils';\nimport { validateCollection, validateIds, validateData } from '../utils/validators';\n\nexport const patchManyFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async <T extends BaseEntity>(\n    request: PatchManyRequest\n  ): Promise<PatchManyResponse<T>> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting patchMany operation', { request });\n\n      const { collection, ids, data } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n      validateIds(ids);\n      validateData(data);\n\n      // Handle empty array early\n      if (ids.length === 0) {\n        return {\n          entities: [],\n          count: 0,\n          notFound: [],\n          success: true,\n        };\n      }\n\n      // Batch optimization: load collection once, patch in memory, single write\n      // This avoids N disk reads + N disk writes when saveOnPush is enabled\n      const currentCollection: Record<string, T> = await dbState.db\n        .getData(`/${collection}`)\n        .catch(() => ({}));\n\n      // Clone collection for atomic update\n      const updatedCollection: Record<string, T> = { ...currentCollection };\n      const patchedEntities: T[] = [];\n      const notFound: string[] = [];\n\n      // Patch entities in memory\n      for (const id of ids) {\n        if (currentCollection[id]) {\n          // Apply deep merge using custom mergeObjects utility\n          const patchedEntity: T = mergeObjects(currentCollection[id], data) as T;\n\n          // Ensure id cannot be changed\n          patchedEntity.id = id;\n\n          updatedCollection[id] = patchedEntity;\n          patchedEntities.push(patchedEntity);\n        } else {\n          // Entity not found - track it\n          notFound.push(id);\n          logger?.debug('Entity not found for patching', { id });\n        }\n      }\n\n      if (patchedEntities.length === 0) {\n        throw new Error('No entities found with provided IDs');\n      }\n\n      // Single disk write\n      await dbState.db.push(`/${collection}`, updatedCollection);\n\n      const response: PatchManyResponse<T> = {\n        entities: patchedEntities,\n        count: patchedEntities.length,\n        notFound,\n        success: true,\n      };\n\n      logger?.debug('patchMany completed', response);\n      return response;\n    } catch (error) {\n      logger?.error('patchMany failed', error);\n      throw error;\n    }\n  };\n","import {\n  JsonDbAdapterSettings,\n  ReplaceManyRequest,\n  ReplaceManyResponse,\n  BaseEntity,\n  DbState,\n} from '../types';\nimport { validateCollection, validateUpdates } from '../utils/validators';\n\nexport const replaceManyFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async <T extends BaseEntity>(\n    request: ReplaceManyRequest<T>\n  ): Promise<ReplaceManyResponse<T>> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting replaceMany operation', { request });\n\n      const { collection, updates } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n      validateUpdates(updates);\n\n      // Handle empty array early\n      if (updates.length === 0) {\n        return {\n          entities: [],\n          count: 0,\n          notFound: [],\n          success: true,\n        };\n      }\n\n      // Batch optimization: load collection once, replace in memory, single write\n      // This avoids N disk reads + N disk writes when saveOnPush is enabled\n      const currentCollection: Record<string, T> = await dbState.db\n        .getData(`/${collection}`)\n        .catch(() => ({}));\n\n      // Clone collection for atomic update\n      const updatedCollection: Record<string, T> = { ...currentCollection };\n      const replacedEntities: T[] = [];\n      const notFound: string[] = [];\n\n      // Replace entities in memory\n      for (const update of updates) {\n        const { id, data } = update;\n\n        if (currentCollection[id]) {\n          // Replace entity completely (keep only id from original)\n          const replacedEntity: T = {\n            ...data,\n            id,\n          } as T;\n\n          updatedCollection[id] = replacedEntity;\n          replacedEntities.push(replacedEntity);\n        } else {\n          // Entity not found - track it\n          notFound.push(id);\n          logger?.debug('Entity not found for replacement', { id });\n        }\n      }\n\n      if (replacedEntities.length === 0) {\n        throw new Error('No entities found with provided IDs');\n      }\n\n      // Single disk write\n      await dbState.db.push(`/${collection}`, updatedCollection);\n\n      const response: ReplaceManyResponse<T> = {\n        entities: replacedEntities,\n        count: replacedEntities.length,\n        notFound,\n        success: true,\n      };\n\n      logger?.debug('replaceMany completed', response);\n      return response;\n    } catch (error) {\n      logger?.error('replaceMany failed', error);\n      throw error;\n    }\n  };\n","import {\n  JsonDbAdapterSettings,\n  ListRequest,\n  ListResponse,\n  BaseEntity,\n  DbState,\n} from '../types';\nimport { populateEntities } from '../utils/populate';\nimport { validateCollection } from '../utils/validators';\n\nexport const listFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async <T extends BaseEntity>(\n    request: ListRequest<T>\n  ): Promise<ListResponse<T>> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting list operation', { request });\n\n      const { collection, filter, populate, reload } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n\n      // Reload database if requested\n      if (reload) {\n        await dbState.db.reload();\n        logger?.debug('Database reloaded before query');\n      }\n\n      // Load entire collection (now stored as map/object)\n      let collectionData: T[] = [];\n      try {\n        const collectionMap: Record<string, T> | T[] =\n          await dbState.db.getData(`/${collection}`);\n\n        // Convert map to array using Object.values()\n        if (Array.isArray(collectionMap)) {\n          // Legacy array format - convert to empty for now\n          collectionData = [];\n        } else if (\n          typeof collectionMap === 'object' &&\n          collectionMap !== null\n        ) {\n          // Map/object format - convert to array\n          collectionData = Object.values(collectionMap);\n        } else {\n          collectionData = [];\n        }\n      } catch (error: unknown) {\n        // Collection doesn't exist\n        logger?.debug('Collection not found', { collection });\n        return {\n          entities: [],\n          total: 0,\n        };\n      }\n\n      // Apply filter if provided\n      let entities: T[] = filter\n        ? collectionData.filter((entity: T) => filter(entity))\n        : collectionData;\n\n      // Apply populate if provided\n      if (populate) {\n        entities = await populateEntities(\n          entities,\n          populate,\n          dbState,\n          settings,\n          logger\n        );\n      }\n\n      const total: number = entities.length;\n\n      const response: ListResponse<T> = {\n        entities,\n        total,\n      };\n\n      logger?.debug('list completed', response);\n      return response;\n    } catch (error) {\n      logger?.error('list failed', error);\n      throw error;\n    }\n  };\n","import { JsonDbAdapterSettings, ReloadResponse, DbState } from '../types';\n\n/**\n * Factory for reload operation\n *\n * Reloads the database from disk. Useful when the database file is modified\n * by external processes or other Node.js instances.\n *\n * @param settings - Adapter settings\n * @param dbState - Database state\n * @returns Reload operation function\n */\nexport const reloadFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async (): Promise<ReloadResponse> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting reload operation');\n\n      // Reload the database from disk\n      await dbState.db.reload();\n\n      const response: ReloadResponse = {\n        success: true,\n      };\n\n      logger?.debug('Reload completed successfully');\n      return response;\n    } catch (error) {\n      logger?.error('Reload failed', error);\n      throw error;\n    }\n  };\n","import { JsonDbAdapterSettings, DbState } from '../types';\nimport { validateCollection, validateId } from '../utils/validators';\n\n/**\n * Request type for checking entity existence\n */\nexport interface ExistsRequest {\n  collection: string;\n  id: string;\n  /** Reload database from disk before querying (useful for multi-process scenarios) */\n  reload?: boolean;\n}\n\n/**\n * Response type for existence check\n */\nexport interface ExistsResponse {\n  exists: boolean;\n}\n\n/**\n * Factory function to create exists operation\n *\n * Checks if an entity exists in a collection without fetching the full data.\n * More efficient than getOneById when only existence check is needed.\n *\n * @param settings - Adapter settings\n * @param dbState - Database state\n * @returns Exists operation function\n */\nexport const existsFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async (request: ExistsRequest): Promise<ExistsResponse> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting exists operation', { request });\n\n      const { collection, id, reload } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n      validateId(id);\n\n      // Reload database if requested\n      if (reload) {\n        await dbState.db.reload();\n        logger?.debug('Database reloaded before query');\n      }\n\n      // Try to get entity - if it exists, getData succeeds\n      try {\n        await dbState.db.getData(`/${collection}/${id}`);\n\n        const response: ExistsResponse = { exists: true };\n        logger?.debug('exists completed', response);\n        return response;\n      } catch (error: unknown) {\n        // Entity doesn't exist (getData throws when path doesn't exist)\n        const response: ExistsResponse = { exists: false };\n        logger?.debug('exists completed', response);\n        return response;\n      }\n    } catch (error) {\n      logger?.error('exists failed', error);\n      throw error;\n    }\n  };\n","import { JsonDbAdapterSettings, BaseEntity, DbState } from '../types';\nimport { validateCollection } from '../utils/validators';\n\n/**\n * Request type for counting entities\n */\nexport interface CountRequest<T extends BaseEntity = BaseEntity> {\n  collection: string;\n  filter?: (entity: T) => boolean;\n  /** Reload database from disk before querying (useful for multi-process scenarios) */\n  reload?: boolean;\n}\n\n/**\n * Response type for count operation\n */\nexport interface CountResponse {\n  count: number;\n}\n\n/**\n * Factory function to create count operation\n *\n * Gets the total number of entities in a collection.\n * Optionally supports filtering to count only entities matching a condition.\n * More efficient than list() when only count is needed.\n *\n * @param settings - Adapter settings\n * @param dbState - Database state\n * @returns Count operation function\n */\nexport const countFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async <T extends BaseEntity>(\n    request: CountRequest<T>\n  ): Promise<CountResponse> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting count operation', { request });\n\n      const { collection, filter, reload } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n\n      // Reload database if requested\n      if (reload) {\n        await dbState.db.reload();\n        logger?.debug('Database reloaded before query');\n      }\n\n      try {\n        // Load collection as object map\n        const collectionMap: Record<string, T> = await dbState.db.getData(\n          `/${collection}`\n        );\n\n        // Convert to array\n        const entities: T[] = Object.values(collectionMap);\n\n        // Apply filter if provided\n        const count: number = filter\n          ? entities.filter(filter).length\n          : entities.length;\n\n        const response: CountResponse = { count };\n        logger?.debug('count completed', response);\n        return response;\n      } catch (error: unknown) {\n        // Collection doesn't exist or is empty\n        const response: CountResponse = { count: 0 };\n        logger?.debug('count completed (empty collection)', response);\n        return response;\n      }\n    } catch (error) {\n      logger?.error('count failed', error);\n      throw error;\n    }\n  };\n","import { JsonDbAdapterSettings, DbState } from '../types';\nimport { validateCollection } from '../utils/validators';\n\n/**\n * Request type for clearing a collection\n */\nexport interface ClearRequest {\n  collection: string;\n}\n\n/**\n * Response type for clear operation\n */\nexport interface ClearResponse {\n  success: boolean;\n  deletedCount: number;\n}\n\n/**\n * Factory function to create clear operation\n *\n * Removes all entities from a collection.\n * More efficient than deleteMany with all IDs as it's a single atomic operation.\n * Useful for testing/cleanup scenarios.\n *\n * @param settings - Adapter settings\n * @param dbState - Database state\n * @returns Clear operation function\n */\nexport const clearFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async (request: ClearRequest): Promise<ClearResponse> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting clear operation', { request });\n\n      const { collection } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n\n      try {\n        // Get current collection to count entities before deletion\n        const collectionMap: Record<string, any> = await dbState.db.getData(\n          `/${collection}`\n        );\n\n        const deletedCount: number = Object.keys(collectionMap).length;\n\n        // Delete entire collection\n        await dbState.db.delete(`/${collection}`);\n\n        const response: ClearResponse = { success: true, deletedCount };\n        logger?.debug('clear completed', response);\n        return response;\n      } catch (error: unknown) {\n        // Collection doesn't exist - treat as success with 0 deletions\n        const response: ClearResponse = { success: true, deletedCount: 0 };\n        logger?.debug('clear completed (collection did not exist)', response);\n        return response;\n      }\n    } catch (error) {\n      logger?.error('clear failed', error);\n      throw error;\n    }\n  };\n","import { JsonDbAdapterSettings, DbState } from '../types';\n\n/**\n * Response type for save operation\n */\nexport interface SaveResponse {\n  success: boolean;\n}\n\n/**\n * Factory function to create save operation\n *\n * Manually saves the database to disk. Useful when saveOnPush is set to false\n * to control when I/O operations occur. Allows batching multiple operations\n * before writing to disk.\n *\n * @param settings - Adapter settings\n * @param dbState - Database state\n * @returns Save operation function\n *\n * @example\n * ```typescript\n * const adapter = createJsonDbAdapter({\n *   filename: 'db',\n *   saveOnPush: false, // Manual save mode\n *   humanReadable: true,\n * });\n *\n * await adapter.createOne({ collection: 'users', data: { name: 'John' }});\n * await adapter.createOne({ collection: 'users', data: { name: 'Jane' }});\n *\n * // Nothing saved to disk yet...\n *\n * await adapter.save(); // Now save to disk\n * ```\n */\nexport const saveFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async (): Promise<SaveResponse> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting save operation');\n\n      // Save database to disk\n      await dbState.db.save();\n\n      const response: SaveResponse = { success: true };\n      logger?.debug('save completed', response);\n      return response;\n    } catch (error) {\n      logger?.error('save failed', error);\n      throw error;\n    }\n  };\n","import { JsonDbAdapterSettings, BaseEntity, DbState, PopulateParam } from '../types';\nimport { populateEntities } from '../utils/populate';\nimport { validateCollection, validateFilter } from '../utils/validators';\n\n/**\n * Request type for finding one entity\n */\nexport interface FindOneRequest<T extends BaseEntity = BaseEntity> {\n  collection: string;\n  filter: (entity: T) => boolean;\n  populate?: PopulateParam;\n  /** Reload database from disk before querying (useful for multi-process scenarios) */\n  reload?: boolean;\n}\n\n/**\n * Response type for findOne operation\n */\nexport interface FindOneResponse<T extends BaseEntity> {\n  entity: T | null;\n  found: boolean;\n}\n\n/**\n * Factory function to create findOne operation\n *\n * Finds the first entity matching a filter condition. More efficient than list()\n * when only one result is needed as it stops searching after the first match.\n * Supports populate to resolve reference fields.\n *\n * @param settings - Adapter settings\n * @param dbState - Database state\n * @returns FindOne operation function\n *\n * @example\n * ```typescript\n * const result = await adapter.findOne({\n *   collection: 'users',\n *   filter: (user) => user.email === 'john@example.com'\n * });\n *\n * if (result.found) {\n *   console.log(result.entity);\n * }\n *\n * // With populate\n * const result = await adapter.findOne({\n *   collection: 'books',\n *   filter: (book) => book.title.includes('TypeScript'),\n *   populate: ['authorId', 'categoryId']\n * });\n * ```\n */\nexport const findOneFactory =\n  (settings: JsonDbAdapterSettings, dbState: DbState) =>\n  async <T extends BaseEntity>(\n    request: FindOneRequest<T>\n  ): Promise<FindOneResponse<T>> => {\n    const logger = settings.logger;\n\n    try {\n      logger?.debug('Starting findOne operation', { request });\n\n      const { collection, filter, populate, reload } = request;\n\n      // Validate inputs\n      validateCollection(collection);\n      validateFilter(filter);\n\n      // Reload database if requested\n      if (reload) {\n        await dbState.db.reload();\n        logger?.debug('Database reloaded before query');\n      }\n\n      try {\n        // Load collection as object map\n        const collectionMap: Record<string, T> = await dbState.db.getData(\n          `/${collection}`\n        );\n\n        // Convert to array\n        const entities: T[] = Object.values(collectionMap);\n\n        // Find first matching entity\n        const entity: T | undefined = entities.find(filter);\n\n        if (!entity) {\n          const response: FindOneResponse<T> = { entity: null, found: false };\n          logger?.debug('findOne completed (not found)', response);\n          return response;\n        }\n\n        // Apply populate if provided\n        let populatedEntity: T = entity;\n        if (populate) {\n          const entityArray: T[] = [entity];\n          await populateEntities(entityArray, populate, dbState, settings, logger);\n          populatedEntity = entityArray[0]!;\n        }\n\n        const response: FindOneResponse<T> = {\n          entity: populatedEntity,\n          found: true,\n        };\n\n        logger?.debug('findOne completed', response);\n        return response;\n      } catch (error: unknown) {\n        // Collection doesn't exist or is empty\n        const response: FindOneResponse<T> = { entity: null, found: false };\n        logger?.debug('findOne completed (collection not found)', response);\n        return response;\n      }\n    } catch (error) {\n      logger?.error('findOne failed', error);\n      throw error;\n    }\n  };\n","import { JsonDB } from 'node-json-db';\nimport { Config } from 'node-json-db/dist/lib/JsonDBConfig';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { JsonDbAdapterSettings, JsonDbAdapter, DbState, Logger } from './types';\nimport { DEFAULT_SEPARATOR } from './const';\nimport {\n  createOneFactory,\n  getOneByIdFactory,\n  replaceOneByIdFactory,\n  patchOneByIdFactory,\n  deleteOneByIdFactory,\n  createManyFactory,\n  getManyFactory,\n  deleteManyFactory,\n  patchManyFactory,\n  replaceManyFactory,\n  listFactory,\n  reloadFactory,\n  existsFactory,\n  countFactory,\n  clearFactory,\n  saveFactory,\n  findOneFactory,\n} from './operations';\n\n/**\n * Ensures the directory for the database file exists\n * Creates the directory recursively if it doesn't exist\n *\n * @param filename - Database filename or path\n * @param logger - Optional logger instance\n */\nconst ensureDirectoryExists = (filename: string, logger?: Logger): void => {\n  // Add .json extension if not present\n  const fullPath: string = filename.endsWith('.json') ? filename : `${filename}.json`;\n\n  // Extract directory path\n  const dirPath: string = path.dirname(fullPath);\n\n  // Check if directory path is meaningful (not just current directory)\n  if (dirPath && dirPath !== '.' && dirPath !== '') {\n    // Check if directory exists\n    if (!fs.existsSync(dirPath)) {\n      logger?.debug('Creating database directory', { dirPath });\n\n      // Create directory recursively\n      fs.mkdirSync(dirPath, { recursive: true });\n\n      logger?.info('Database directory created', { dirPath });\n    } else {\n      logger?.debug('Database directory already exists', { dirPath });\n    }\n  }\n};\n\n/**\n * Creates a functional JsonDB adapter with all CRUD operations\n *\n * @param settings - Configuration settings for the adapter\n * @returns JsonDbAdapter instance with all operations\n *\n * @example\n * ```typescript\n * // Simple filename (creates in current directory)\n * const adapter1 = createAdapter({\n *   filename: 'mydb',\n *   saveOnPush: true,\n *   humanReadable: true,\n *   separator: '/',\n *   logger: console,\n * });\n *\n * // Path with directory (creates data folder if needed)\n * const adapter2 = createAdapter({\n *   filename: 'data/mydb',\n *   saveOnPush: true,\n *   humanReadable: true,\n *   separator: '/',\n *   logger: console,\n * });\n *\n * // Nested path (creates data/nested folders if needed)\n * const adapter3 = createAdapter({\n *   filename: 'data/nested/mydb.json',\n *   saveOnPush: true,\n *   humanReadable: true,\n *   separator: '/',\n *   logger: console,\n * });\n *\n * // Create a single entity\n * const result = await adapter1.createOne({\n *   collection: 'users',\n *   data: { name: 'John', email: 'john@example.com' },\n * });\n *\n * // List entities\n * const list = await adapter1.list({\n *   collection: 'users',\n * });\n * ```\n */\nexport const createJsonDbAdapter = (settings: JsonDbAdapterSettings): JsonDbAdapter => {\n  const logger: Logger | undefined = settings.logger;\n\n  logger?.debug('Creating JsonDB adapter', { settings });\n\n  // Ensure the directory for the database file exists\n  ensureDirectoryExists(settings.filename, logger);\n\n  // Create JsonDB configuration\n  const config: Config = new Config(\n    settings.filename,\n    settings.saveOnPush,\n    settings.humanReadable,\n    settings.separator || DEFAULT_SEPARATOR\n  );\n\n  // Initialize JsonDB instance\n  const db: JsonDB = new JsonDB(config);\n\n  // Create shared database state\n  const dbState: DbState = {\n    db,\n    config,\n  };\n\n  logger?.info('JsonDB adapter created successfully', {\n    filename: settings.filename,\n    mode: settings.mode,\n  });\n\n  // Create all operation factories\n  const createOne = createOneFactory(settings, dbState);\n  const getOneById = getOneByIdFactory(settings, dbState);\n  const replaceOneById = replaceOneByIdFactory(settings, dbState);\n  const patchOneById = patchOneByIdFactory(settings, dbState);\n  const deleteOneById = deleteOneByIdFactory(settings, dbState);\n  const createMany = createManyFactory(settings, dbState);\n  const getMany = getManyFactory(settings, dbState);\n  const deleteMany = deleteManyFactory(settings, dbState);\n  const patchMany = patchManyFactory(settings, dbState);\n  const replaceMany = replaceManyFactory(settings, dbState);\n  const list = listFactory(settings, dbState);\n  const reload = reloadFactory(settings, dbState);\n  const exists = existsFactory(settings, dbState);\n  const count = countFactory(settings, dbState);\n  const clear = clearFactory(settings, dbState);\n  const save = saveFactory(settings, dbState);\n  const findOne = findOneFactory(settings, dbState);\n\n  // Return adapter interface\n  return {\n    // Single entity operations\n    createOne,\n    getOneById,\n    replaceOneById,\n    patchOneById,\n    deleteOneById,\n\n    // Batch operations\n    createMany,\n    getMany,\n    deleteMany,\n    patchMany,\n    replaceMany,\n\n    // List operation\n    list,\n\n    // Utility operations\n    exists,\n    count,\n    clear,\n    save,\n    findOne,\n\n    // Utility methods\n    getDb: () => db,\n    getConfig: () => settings,\n    reload,\n  };\n};\n\n// Re-export types and enums\nexport { JsonDbModeEnum } from './types';\nexport type {\n  JsonDbAdapterSettings,\n  JsonDbAdapter,\n  Logger,\n  BaseEntity,\n  TimestampedEntity,\n  CreateOneRequest,\n  CreateOneResponse,\n  GetOneByIdRequest,\n  GetOneByIdResponse,\n  ReplaceOneByIdRequest,\n  ReplaceOneByIdResponse,\n  PatchOneByIdRequest,\n  PatchOneByIdResponse,\n  DeleteOneByIdRequest,\n  DeleteOneByIdResponse,\n  CreateManyRequest,\n  CreateManyResponse,\n  GetManyRequest,\n  GetManyResponse,\n  DeleteManyRequest,\n  DeleteManyResponse,\n  PatchManyRequest,\n  PatchManyResponse,\n  ReplaceManyRequest,\n  ReplaceManyResponse,\n  ListRequest,\n  ListResponse,\n  ReloadResponse,\n  ExistsRequest,\n  ExistsResponse,\n  CountRequest,\n  CountResponse,\n  ClearRequest,\n  ClearResponse,\n  SaveResponse,\n  FindOneRequest,\n  FindOneResponse,\n  PopulateConfig,\n  PopulateParam,\n} from './types';\n"]}