@fjell/lib-sequelize 4.4.79 → 4.4.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/Options.ts", "../src/logger.ts", "../src/Coordinate.ts", "../src/Definition.ts", "../src/SequelizeLibrary.ts", "../src/Operations.ts", "../src/ops/all.ts", "../src/QueryBuilder.ts", "../src/util/general.ts", "../src/util/relationshipUtils.ts", "../src/KeyMaster.ts", "../src/RowProcessor.ts", "../src/EventCoordinator.ts", "../src/processing/ReferenceBuilder.ts", "../src/processing/RefsAdapter.ts", "../src/processing/AggsAdapter.ts", "../src/errors/sequelizeErrorHandler.ts", "../src/metrics/QueryMetrics.ts", "../src/ops/create.ts", "../src/ops/find.ts", "../src/ops/get.ts", "../src/ops/one.ts", "../src/ops/remove.ts", "../src/ops/update.ts", "../src/ops/upsert.ts", "../src/SequelizeLibraryFactory.ts", "../src/contained/index.ts", "../src/contained/SequelizeLibrary.ts", "../src/primary/index.ts", "../src/primary/SequelizeLibrary.ts"],
4
- "sourcesContent": ["import * as Library from '@fjell/lib';\nimport { ComKey, Item, LocKeyArray, PriKey } from '@fjell/core';\nimport { SequelizeReferenceDefinition } from './processing/ReferenceBuilder';\n\n// Re-export AggregationDefinition from @fjell/lib for backwards compatibility\nexport type { AggregationDefinition } from '@fjell/lib';\n\n// Export Sequelize-specific reference definition\nexport type { SequelizeReferenceDefinition } from './processing/ReferenceBuilder';\n\n/**\n * Sequelize-specific Options that uses SequelizeReferenceDefinition\n * instead of the generic ReferenceDefinition\n */\nexport interface Options<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> {\n hooks?: {\n preCreate?: (\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?:\n {\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n locations?: never;\n } | {\n key?: never;\n locations: LocKeyArray<L1, L2, L3, L4, L5>,\n }\n ) => Promise<Partial<Item<S, L1, L2, L3, L4, L5>>>;\n postCreate?: (\n item: V,\n ) => Promise<V>;\n preUpdate?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n ) => Promise<Partial<Item<S, L1, L2, L3, L4, L5>>>;\n postUpdate?: (\n item: V,\n ) => Promise<V>;\n preRemove?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n ) => Promise<Partial<Item<S, L1, L2, L3, L4, L5>>>;\n postRemove?: (\n item: V,\n ) => Promise<V>;\n },\n validators?: {\n onCreate?: (\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?:\n {\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n locations?: never;\n } | {\n key?: never;\n locations: LocKeyArray<L1, L2, L3, L4, L5>,\n }\n ) => Promise<boolean>;\n onUpdate?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n ) => Promise<boolean>;\n onRemove?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n ) => Promise<boolean>;\n },\n finders?: Record<string, Library.FinderMethod<V, S, L1, L2, L3, L4, L5>>,\n actions?: Record<string, Library.ActionMethod<V, S, L1, L2, L3, L4, L5>>,\n facets?: Record<string, Library.FacetMethod<V, S, L1, L2, L3, L4, L5>>,\n allActions?: Record<string, Library.AllActionMethod<V, S, L1, L2, L3, L4, L5>>,\n allFacets?: Record<string, Library.AllFacetMethod<L1, L2, L3, L4, L5>>,\n references?: SequelizeReferenceDefinition[], // Sequelize-specific!\n aggregations?: Library.AggregationDefinition[],\n deleteOnRemove?: boolean; // Sequelize-specific option\n}\n\nexport const createOptions = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(sequelizeOptions?: Options<V, S, L1, L2, L3, L4, L5>): Options<V, S, L1, L2, L3, L4, L5> => {\n // Convert Sequelize options to Library options (excluding references which have different types)\n const { references, deleteOnRemove, ...libCompatibleOptions } = sequelizeOptions || {};\n \n // Create base options from Library\n const baseOptions = Library.createOptions(libCompatibleOptions as Library.Options<V, S, L1, L2, L3, L4, L5>);\n\n // Return Sequelize options with Sequelize-specific references, aggregations, and deleteOnRemove\n return {\n ...baseOptions,\n references: references ?? [], // Keep Sequelize-specific references\n aggregations: baseOptions.aggregations ?? [], // Ensure aggregations is always present\n deleteOnRemove: deleteOnRemove ?? false, // Sequelize-specific option\n } as Options<V, S, L1, L2, L3, L4, L5>;\n}\n", "import Logging from '@fjell/logging';\n\nconst LibLogger = Logging.getLogger('@fjell/lib-sequelize');\n\nexport default LibLogger;\n", "import { Coordinate, createCoordinate as createBaseCoordinate, ItemTypeArray } from '@fjell/core';\nimport LibLogger from './logger';\n\nconst logger = LibLogger.get('Coordinate');\n\nexport const SCOPE_SEQUELIZE = 'sequelize';\n\nexport const createCoordinate = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(kta: ItemTypeArray<S, L1, L2, L3, L4, L5>, scopes?: string[]): Coordinate<S, L1, L2, L3, L4, L5> => {\n logger.debug('createCoordinate', { kta, scopes });\n const coordinate = createBaseCoordinate(kta, [SCOPE_SEQUELIZE, ...(scopes || [])]);\n return coordinate;\n};\n\n// Re-export the Coordinate type\nexport type { Coordinate } from '@fjell/core';\n", "import { Item, ItemTypeArray } from '@fjell/core';\nimport { createOptions, Options } from './Options';\nimport LibLogger from './logger';\nimport { createCoordinate } from './Coordinate';\n\nconst logger = LibLogger.get('lib-sequelize', 'Definition');\n\nexport interface Definition<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> {\n coordinate: import('@fjell/core').Coordinate<S, L1, L2, L3, L4, L5>;\n options: Options<V, S, L1, L2, L3, L4, L5>;\n}\n\nexport const createDefinition = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n kta: ItemTypeArray<S, L1, L2, L3, L4, L5>,\n scopes: string[],\n libOptions?: Partial<Options<V, S, L1, L2, L3, L4, L5>>,\n ): Definition<V, S, L1, L2, L3, L4, L5> => {\n logger.debug('createDefinition', { kta, scopes, libOptions });\n const coordinate = createCoordinate(kta, scopes);\n const options = createOptions<V, S, L1, L2, L3, L4, L5>(libOptions);\n\n return {\n coordinate,\n options,\n }\n}\n", "\nimport * as Library from '@fjell/lib';\nimport { Coordinate, Item } from '@fjell/core';\nimport { Registry } from './Registry';\nimport { createOperations } from './Operations';\nimport { ModelStatic } from 'sequelize';\nimport { Options } from './Options';\nimport SequelizeLogger from './logger';\n\nconst logger = SequelizeLogger.get(\"SequelizeLibrary\");\n\n/**\n * The SequelizeLibrary interface extends the fjell-lib Library\n * and adds Sequelize-specific functionality:\n * - models: Array of Sequelize model classes for this library\n *\n * @template V - The type of the data model item, extending Item\n * @template S - The string literal type representing the model's key type\n * @template L1-L5 - Optional string literal types for location hierarchy levels\n */\nexport interface SequelizeLibrary<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> extends Library.Library<V, S, L1, L2, L3, L4, L5> {\n /** Array of Sequelize model classes associated with this library */\n models: ModelStatic<any>[];\n}\n\n/**\n * Creates a new SequelizeLibrary that extends the fjell-lib Library\n * with Sequelize-specific functionality\n */\nexport const createSequelizeLibrary = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n registry: Registry,\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>,\n models: ModelStatic<any>[],\n options: Options<V, S, L1, L2, L3, L4, L5>\n ): SequelizeLibrary<V, S, L1, L2, L3, L4, L5> => {\n logger.debug(\"createSequelizeLibrary\", { coordinate, models, registry, options });\n\n // Create Sequelize-specific operations\n const operations = createOperations<V, S, L1, L2, L3, L4, L5>(models, coordinate, registry, options);\n\n // Wrap operations with validation and hooks from base library\n const wrappedOperations = Library.wrapOperations(operations, options, coordinate, registry);\n\n // Create the base fjell-lib library\n const libLibrary = Library.createLibrary(registry, coordinate, wrappedOperations, options);\n\n return {\n ...libLibrary,\n models,\n };\n}\n\n/**\n * Type guard to check if an object is a SequelizeLibrary\n */\nexport const isSequelizeLibrary = (library: any): library is SequelizeLibrary<any, any, any, any, any, any, any> => {\n return library != null &&\n library.coordinate != null &&\n library.operations != null &&\n library.options != null &&\n library.registry != null &&\n library.models != null &&\n Array.isArray(library.models);\n}\n", "/* eslint-disable indent */\nimport { Coordinate, Item } from \"@fjell/core\";\n\nimport * as Library from \"@fjell/lib\";\nimport { Registry } from \"./Registry\";\nimport { getAllOperation } from \"./ops/all\";\nimport { getCreateOperation } from \"./ops/create\";\nimport { getFindOperation } from \"./ops/find\";\nimport { getGetOperation } from \"./ops/get\";\nimport { getOneOperation } from \"./ops/one\";\nimport { getRemoveOperation } from \"./ops/remove\";\nimport { getUpdateOperation } from \"./ops/update\";\nimport { getUpsertOperation } from \"./ops/upsert\";\nimport { ModelStatic } from \"sequelize\";\n\nexport const createOperations = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never,\n>(\n models: Array<ModelStatic<any>>,\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>,\n registry: Registry,\n options: import('./Options').Options<V, S, L1, L2, L3, L4, L5>\n): Library.Operations<V, S, L1, L2, L3, L4, L5> => {\n\n // Create a definition-like object for backward compatibility with existing operation functions\n const definition = { coordinate, options };\n\n // Create implementation operations (core CRUD and query operations only)\n // These are the operations that lib-sequelize actually implements\n const implOps: Library.ImplementationOperations<V, S, L1, L2, L3, L4, L5> = {\n all: getAllOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n one: getOneOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n create: getCreateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n update: getUpdateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n get: getGetOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n remove: getRemoveOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n find: getFindOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n // findOne depends on find, so set it after\n findOne: null as any,\n upsert: getUpsertOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n };\n\n // Set findOne operation that depends on find\n implOps.findOne = async (finder: string, params?: Library.OperationParams, locations?: any): Promise<V | null> => {\n const results = await implOps.find(finder, params || {}, locations);\n return results.items.length > 0 ? results.items[0] : null;\n };\n\n // Wrap with default stub implementations for extended operations (facets, actions)\n // and add metadata dictionaries (finders, actions, facets, allActions, allFacets)\n return Library.wrapImplementationOperations(implOps, options);\n}\n", "/* eslint-disable no-undefined */\n/* eslint-disable indent */\n/* eslint-disable max-depth */\nimport { AllMethod, AllOperationResult, AllOptions, createAllWrapper } from \"@fjell/core\";\nimport { validateKeys } from \"@fjell/core/validation\";\n\nimport { addAggregationIncludes, addReferenceIncludes, buildQuery } from \"../QueryBuilder\";\n\nimport { Definition } from \"../Definition\";\nimport LibLogger from '../logger';\nimport * as Library from \"@fjell/lib\";\nimport { processRow } from \"../RowProcessor\";\nimport { Item, ItemQuery, LocKeyArray } from \"@fjell/core\";\nimport { ModelStatic, Op } from \"sequelize\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { contextManager } from \"../RowProcessor\";\nimport { transformSequelizeError } from \"../errors/sequelizeErrorHandler\";\n\nimport { stringifyJSON } from \"../util/general\";\nimport { queryMetrics } from \"../metrics/QueryMetrics\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'all');\n\n// Helper function to merge includes avoiding duplicates\nconst mergeIncludes = (existingIncludes: any[], newIncludes: any[]): any[] => {\n const mergedIncludes = [...existingIncludes];\n\n for (const newInclude of newIncludes) {\n const existingIndex = mergedIncludes.findIndex(\n (existing: any) => existing.as === newInclude.as && existing.model === newInclude.model\n );\n if (existingIndex === -1) {\n mergedIncludes.push(newInclude);\n } else if (newInclude.include && mergedIncludes[existingIndex].include) {\n mergedIncludes[existingIndex].include = [\n ...mergedIncludes[existingIndex].include,\n ...newInclude.include\n ];\n } else if (newInclude.include) {\n mergedIncludes[existingIndex].include = newInclude.include;\n }\n }\n\n return mergedIncludes;\n};\n\nexport const getAllOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: Array<ModelStatic<any>>,\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n): AllMethod<V, S, L1, L2, L3, L4, L5> => {\n\n const { coordinate, options: { references, aggregations } } = definition;\n\n return createAllWrapper(\n coordinate,\n async (\n itemQuery?: ItemQuery,\n locations?: LocKeyArray<L1, L2, L3, L4, L5> | [],\n allOptions?: AllOptions\n ): Promise<AllOperationResult<V>> => {\n try {\n const locs = locations ?? [];\n logger.debug(`ALL operation called on ${models[0].name} with ${locs.length} location filters: ${locs.map(loc => `${loc.kt}=${loc.lk}`).join(', ') || 'none'}`);\n\n const loc: LocKeyArray<L1, L2, L3, L4, L5> | [] = locs;\n\n // @ts-ignore\n const model = models[0];\n\n // Build base query from itemQuery (includes limit/offset from query)\n let options = buildQuery(itemQuery ?? {}, model, references, registry);\n\n // Auto-detect and add reference INCLUDES to prevent N+1 queries\n const { options: optionsWithRefs, includedReferences } = addReferenceIncludes(\n options,\n model,\n references || []\n );\n options = optionsWithRefs;\n\n // Auto-detect and add aggregation INCLUDES to prevent N+1 queries\n const { options: optionsWithAggs, includedAggregations } = addAggregationIncludes(\n options,\n model,\n aggregations || []\n );\n options = optionsWithAggs;\n\n // Handle location keys if present\n if (loc.length > 0) {\n const { kta } = coordinate;\n const directLocations: Array<{ kt: string; lk: any }> = [];\n const hierarchicalLocations: Array<{ kt: string; lk: any }> = [];\n const additionalIncludes: any[] = [];\n\n // Categorize location keys as direct or hierarchical\n for (const locKey of loc) {\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Location key '${locKey.kt}' cannot be resolved on model '${model.name}' or through its relationships.`;\n logger.error(errorMessage, { locations: loc, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n directLocations.push(locKey);\n } else {\n hierarchicalLocations.push(locKey);\n }\n }\n\n // Handle direct location keys (simple foreign key constraints)\n for (const locKey of directLocations) {\n if (locKey.lk === undefined || locKey.lk == null || locKey.lk === '' || (typeof locKey.lk === 'object' && Object.keys(locKey.lk).length === 0)) {\n logger.error(`Location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`, { locKey, locations: loc });\n throw new Error(`Location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`);\n }\n const foreignKeyField = locKey.kt + 'Id';\n\n // Check if this field already has a condition from the itemQuery\n if (options.where[foreignKeyField]) {\n logger.debug(`[ALL] Field ${foreignKeyField} already constrained by itemQuery, skipping location constraint to avoid conflicts`);\n continue; // Skip this location constraint to avoid conflicts\n }\n\n logger.trace(`[ALL] Setting direct location where clause: ${foreignKeyField} = ${stringifyJSON(locKey.lk)} (type: ${typeof locKey.lk})`);\n options.where[foreignKeyField] = {\n [Op.eq]: locKey.lk\n };\n }\n\n // Handle hierarchical location keys (requires relationship traversal)\n for (const locKey of hierarchicalLocations) {\n if (locKey.lk === undefined || locKey.lk == null || locKey.lk === '' || (typeof locKey.lk === 'object' && Object.keys(locKey.lk).length === 0)) {\n logger.error(`Hierarchical location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`, { locKey, locations: loc });\n throw new Error(`Hierarchical location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`);\n }\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta);\n\n if (relationshipInfo.found && relationshipInfo.path) {\n // Check if this field already has a condition from the itemQuery\n if (options.where[relationshipInfo.path]) {\n logger.debug(`[ALL] Field ${relationshipInfo.path} already constrained by itemQuery, skipping hierarchical location constraint to avoid conflicts`);\n continue; // Skip this location constraint to avoid conflicts\n }\n\n // Add the relationship constraint using the path\n logger.trace(`[ALL] Setting hierarchical location where clause: ${relationshipInfo.path} = ${stringifyJSON(locKey.lk)} (type: ${typeof locKey.lk})`);\n options.where[relationshipInfo.path] = {\n [Op.eq]: locKey.lk\n };\n\n // Add necessary includes for the relationship traversal\n if (relationshipInfo.includes) {\n additionalIncludes.push(...relationshipInfo.includes);\n }\n }\n }\n\n // Merge additional includes with existing includes\n if (additionalIncludes.length > 0) {\n const existingIncludes = options.include || [];\n options.include = mergeIncludes(existingIncludes, additionalIncludes);\n }\n }\n\n // Determine effective limit/offset (options takes precedence over query)\n const effectiveLimit = allOptions?.limit ?? itemQuery?.limit;\n const effectiveOffset = allOptions?.offset ?? itemQuery?.offset ?? 0;\n\n const whereFields = options.where ? Object.keys(options.where).join(', ') : 'none';\n const includeCount = options.include?.length || 0;\n logger.default(\n `All query configured for ${model.name} with where fields: ${whereFields}, ` +\n `includes: ${includeCount}, limit: ${effectiveLimit}, offset: ${effectiveOffset}`\n );\n\n // Execute COUNT query to get total matching records (before pagination)\n // Use only where and include from options, not limit/offset\n const countOptions: any = {\n where: options.where,\n distinct: true\n };\n if (options.include) {\n countOptions.include = options.include;\n }\n\n queryMetrics.recordQuery(model.name);\n const countResult = await model.count(countOptions);\n // Sequelize count() with distinct:true and include can return GroupedCountResultItem[]\n // Extract the count value properly\n const total = Array.isArray(countResult) ? countResult.length : (countResult as number);\n logger.debug(`[ALL] Total count for ${model.name}: ${total}`);\n\n // Apply effective limit/offset for the data query\n // Remove any limit/offset that came from buildQuery (via itemQuery)\n delete options.limit;\n delete options.offset;\n\n if (effectiveLimit !== undefined) {\n options.limit = effectiveLimit;\n }\n if (effectiveOffset > 0) {\n options.offset = effectiveOffset;\n }\n\n try {\n logger.trace(`[ALL] Executing ${model.name}.findAll() with options: ${JSON.stringify(options, null, 2)}`);\n } catch {\n // Fallback for cases where JSON.stringify fails on Sequelize operators\n logger.trace(`[ALL] Executing ${model.name}.findAll() with options containing non-serializable operators (${Object.keys(options.where || {}).length} where conditions)`);\n }\n queryMetrics.recordQuery(model.name);\n const matchingItems = await model.findAll(options);\n\n // this.logger.default('Matching Items', { matchingItems });\n\n // Pass null as context to let processRow create a new context for each top-level operation\n // This prevents circular dependency false positives between concurrent operations\n // while still detecting legitimate circular references within the same operation\n\n // TODO: Move this Up!\n const currentContext = contextManager.getCurrentContext();\n const items = (await Promise.all(matchingItems.map(async (row: any) => {\n // Each row in an all() operation should get its own context to prevent interference\n const processedRow = await processRow(\n row,\n coordinate.kta,\n references || [],\n aggregations || [],\n registry,\n currentContext,\n includedAggregations,\n includedReferences\n );\n return validateKeys(processedRow, coordinate.kta);\n }))) as V[];\n\n logger.debug(`[ALL] Returning ${items.length} of ${total} ${model.name} records`);\n\n // Build and return AllOperationResult\n return {\n items,\n metadata: {\n total,\n returned: items.length,\n limit: effectiveLimit,\n offset: effectiveOffset,\n hasMore: effectiveOffset + items.length < total\n }\n };\n } catch (error: any) {\n // Transform database errors\n throw transformSequelizeError(error, coordinate.kta[0]);\n }\n }\n );\n\n}\n", "/* eslint-disable max-len */\nimport {\n CompoundCondition,\n Condition,\n EventQuery,\n isComKey,\n isCondition,\n isPriKey,\n ItemQuery,\n OrderBy,\n PriKey,\n References\n} from '@fjell/core';\n\nimport { Association, ModelStatic, Op } from 'sequelize';\nimport LibLogger from './logger';\nimport { stringifyJSON } from './util/general';\nimport { SequelizeReferenceDefinition } from './processing/ReferenceBuilder';\nimport type { Registry } from '@fjell/lib';\n\nconst logger = LibLogger.get('sequelize', 'QueryBuilder');\n\nexport type QueryOptions = {\n where: Record<string, any>;\n limit?: number;\n offset?: number;\n order?: Array<[string, string]>;\n include?: Array<any>;\n}\n\nconst addDeleteQuery = (options: QueryOptions, model: ModelStatic<any>): QueryOptions => {\n logger.default(`QueryBuilder adding delete query with options: ${stringifyJSON(options)}`);\n if (model.getAttributes().deletedAt) {\n options.where['deletedAt'] = {\n [Op.eq]: null\n }\n } else if (model.getAttributes().isDeleted) {\n options.where['isDeleted'] = {\n [Op.eq]: false\n }\n }\n\n return options;\n}\n\nconst addEventQueries = (\n options: QueryOptions, events: Record<string, EventQuery>, model: ModelStatic<any>): QueryOptions => {\n logger.default(`QueryBuilder adding event queries with options: ${stringifyJSON(options)}, events: ${stringifyJSON(events)}`);\n Object.keys(events).forEach((key: string) => {\n\n if (!model.getAttributes()[`${key}At`]) {\n throw new Error(`Event ${key} is not supported on model '${model.name}', column '${key}At' not found. Available columns: [${Object.keys(model.getAttributes()).join(', ')}]. Event query: ${stringifyJSON(events[key])}`);\n }\n\n let whereClauses = {};\n\n const event = events[key];\n if (event.start) {\n whereClauses = { ...whereClauses, [Op.gte]: new Date(event.start) };\n }\n if (event.end) {\n whereClauses = { ...whereClauses, [Op.lt]: new Date(event.end) };\n }\n\n if (event.by) {\n if (!model.getAttributes()[`${key}By`]) {\n throw new Error(`Event ${key} is not supported on model '${model.name}', column '${key}By' not found. Available columns: [${Object.keys(model.getAttributes()).join(', ')}]. Event query: ${stringifyJSON(events[key])}`);\n }\n whereClauses = { ...whereClauses, [Op.eq]: event.by };\n }\n\n options.where[`${key}At`] = whereClauses;\n\n });\n return options;\n}\n\n// Add the references to the query\nconst addReferenceQueries = (options: any, references: References, model: ModelStatic<any>): any => {\n logger.default(`QueryBuilder adding reference queries with options: ${stringifyJSON(options)}, references: ${stringifyJSON(references)}`);\n\n Object.keys(references).forEach((key: string) => {\n logger.default(`QueryBuilder adding reference query for key: ${key}, references: ${stringifyJSON(references)}`);\n\n if (!model.getAttributes()[`${key}Id`]) {\n throw new Error(`Reference ${key} is not supported on model '${model.name}', column '${key}Id' not found. Available columns: [${Object.keys(model.getAttributes()).join(', ')}]. Reference query: ${stringifyJSON(references[key])}`);\n }\n\n const refValue = references[key];\n const keyValue = (refValue as any).key || refValue;\n\n if (isPriKey(keyValue)) {\n const priKey: PriKey<string> = keyValue as PriKey<string>;\n\n if (priKey.pk == null || priKey.pk === '' || (typeof priKey.pk === 'object' && Object.keys(priKey.pk).length === 0)) {\n logger.error(`Reference key '${key}' has invalid pk value: ${stringifyJSON(priKey.pk)}`, { priKey, references });\n throw new Error(`Reference key '${key}' has invalid pk value: ${stringifyJSON(priKey.pk)}. Model: '${model.name}', Key type: '${priKey.kt}', Full reference: ${stringifyJSON(references[key])}`);\n }\n\n logger.trace(`[QueryBuilder] Setting reference where clause: ${key}Id = ${stringifyJSON(priKey.pk)} (type: ${typeof priKey.pk})`);\n options.where[`${key}Id`] = {\n [Op.eq]: priKey.pk\n }\n } else if (isComKey(references[key])) {\n throw new Error(`ComKeys are not supported in Sequelize. Reference key: '${key}', Model: '${model.name}', ComKey: ${stringifyJSON(references[key])}`);\n }\n });\n return options;\n}\n\nexport const addCompoundCondition = (\n options: any,\n compoundCondition: CompoundCondition,\n model: ModelStatic<any>,\n references?: SequelizeReferenceDefinition[],\n allReferences?: Map<string, SequelizeReferenceDefinition[]>,\n registry?: Registry\n) => {\n // Ensure options.where exists\n options.where = options.where || {};\n\n let compoundOp: symbol;\n const compoundType = compoundCondition.compoundType;\n if (compoundType === \"AND\") {\n compoundOp = Op.and;\n } else {\n compoundOp = Op.or;\n };\n\n let conditions: Record<string, any> = {};\n compoundCondition.conditions.forEach((condition: Condition | CompoundCondition) => {\n if (isCondition(condition)) {\n conditions = addCondition(conditions, condition, model, options, references, allReferences, registry);\n } else {\n throw new Error(`Nested Compound conditions not supported. Model: '${model.name}', Compound condition: ${stringifyJSON(compoundCondition)}, Nested condition: ${stringifyJSON(condition)}`);\n }\n });\n\n // Merge with existing where conditions instead of replacing\n if (Object.keys(options.where).length > 0) {\n // If there are existing conditions, wrap everything in an AND\n options.where = {\n [Op.and]: [\n options.where,\n { [compoundOp]: conditions }\n ]\n };\n } else {\n // If no existing conditions, just set the compound condition\n options.where[compoundOp] = conditions;\n }\n\n return options;\n}\n\nconst getSequelizeOperator = (operator: string): symbol => {\n if (operator === '==') {\n return Op.eq;\n } else if (operator === '<') {\n return Op.lt;\n } else if (operator === '>') {\n return Op.gt;\n } else if (operator === '<=') {\n return Op.lte;\n } else if (operator === '>=') {\n return Op.gte;\n } else if (operator === 'in') {\n return Op.in;\n } else if (operator === '!=') {\n return Op.ne;\n } else {\n throw new Error(`Operator ${operator} not supported`);\n }\n};\n\n/**\n * Finds a reference definition that matches the given property name.\n * @param propertyName - The property name to match (e.g., \"phase\")\n * @param references - Array of reference definitions\n * @returns The matching reference definition or null\n */\nconst findReferenceByProperty = (\n propertyName: string,\n references?: SequelizeReferenceDefinition[]\n): SequelizeReferenceDefinition | null => {\n if (!references || references.length === 0) {\n return null;\n }\n return references.find(ref => ref.property === propertyName) || null;\n};\n\n/**\n * Gets reference definitions for a model from the registry by looking up the library\n * associated with the model's primary key type.\n * @param model - The Sequelize model\n * @param registry - The registry to look up libraries\n * @returns Array of reference definitions or undefined if not found\n */\nconst getReferencesFromRegistry = (\n model: ModelStatic<any>,\n registry?: Registry\n): SequelizeReferenceDefinition[] | void => {\n if (!registry) {\n return;\n }\n\n // Try to get the library for this model by its name (which often matches the key type)\n // We'll try the model name first, then try common variations\n const modelName = model.name.toLowerCase();\n try {\n const library = registry.get([modelName] as any);\n if (library && (library as any).options && (library as any).options.references) {\n return (library as any).options.references;\n }\n } catch {\n // Model name might not match key type, that's okay\n }\n\n return;\n};\n\n/**\n * Builds nested include structure for a reference path (e.g., \"step.phase.code\").\n * For the first segment, requires a reference definition match.\n * For subsequent segments, looks up reference definitions from registry if available.\n * @param pathSegments - Array of path segments (e.g., [\"step\", \"phase\"])\n * @param currentModel - The current Sequelize model\n * @param references - Array of reference definitions for the current model (only used for first segment)\n * @param allReferences - Map of all reference definitions by model name (for nested references)\n * @param registry - Registry to look up reference definitions for nested models\n * @param isFirstSegment - Whether this is the first segment (requires reference definition match)\n * @returns Include configuration object or null if path cannot be resolved\n */\nconst buildNestedInclude = (\n pathSegments: string[],\n currentModel: ModelStatic<any>,\n references?: SequelizeReferenceDefinition[],\n allReferences?: Map<string, SequelizeReferenceDefinition[]>,\n registry?: Registry,\n isFirstSegment: boolean = true\n): { include: any; associationName: string } | null => {\n if (pathSegments.length === 0) {\n return null;\n }\n\n const [firstSegment, ...remainingSegments] = pathSegments;\n\n // For the first segment, check if it matches a reference definition\n if (isFirstSegment) {\n const refDef = findReferenceByProperty(firstSegment, references);\n if (!refDef) {\n logger.debug(`[buildNestedInclude] No reference definition found for property '${firstSegment}'`, {\n model: currentModel.name,\n property: firstSegment,\n availableReferences: references?.map(r => r.property) || [],\n referencesCount: references?.length || 0\n });\n return null;\n }\n logger.debug(`[buildNestedInclude] Found reference definition for property '${firstSegment}'`, {\n model: currentModel.name,\n property: firstSegment,\n refDef: { property: refDef.property, column: refDef.column, kta: refDef.kta }\n });\n }\n\n // Check if Sequelize association exists\n const association = currentModel.associations?.[firstSegment];\n if (!association) {\n if (isFirstSegment) {\n logger.debug(`[buildNestedInclude] Reference property '${firstSegment}' found but no Sequelize association exists`, {\n model: currentModel.name,\n property: firstSegment,\n availableAssociations: Object.keys(currentModel.associations || {}),\n associationsObject: currentModel.associations ? Object.keys(currentModel.associations) : 'undefined'\n });\n }\n return null;\n }\n logger.debug(`[buildNestedInclude] Found Sequelize association for '${firstSegment}'`, {\n model: currentModel.name,\n property: firstSegment,\n associationType: association.associationType,\n targetModel: association.target?.name\n });\n\n const targetModel = association.target;\n const includeConfig: any = {\n model: targetModel,\n as: firstSegment,\n required: true // Use INNER JOIN for filtering conditions\n };\n\n // If there are remaining segments, recursively build nested includes\n // For nested segments, we use Sequelize associations directly (no reference definition required)\n if (remainingSegments.length === 0) {\n return { include: includeConfig, associationName: firstSegment };\n }\n\n // Try to get nested references from registry first, then fall back to allReferences map\n let nestedReferences: SequelizeReferenceDefinition[] | undefined = getReferencesFromRegistry(targetModel, registry);\n if (!nestedReferences) {\n nestedReferences = allReferences?.get(targetModel.name);\n }\n const nestedInclude = buildNestedInclude(\n remainingSegments,\n targetModel,\n nestedReferences,\n allReferences,\n registry,\n false // Subsequent segments don't require reference definition match\n );\n\n if (nestedInclude) {\n includeConfig.include = [nestedInclude.include];\n return { include: includeConfig, associationName: firstSegment };\n }\n\n // Fallback: try direct Sequelize association lookup for nested paths\n // This allows \"step.phase.code\" to work even if Step model doesn't have \"phase\" in its references\n const [nextSegment, ...restSegments] = remainingSegments;\n const nextAssociation = targetModel.associations?.[nextSegment];\n\n if (!nextAssociation) {\n return null;\n }\n\n if (restSegments.length === 0) {\n // Final segment - just add the include\n includeConfig.include = [{\n model: nextAssociation.target,\n as: nextSegment,\n required: true\n }];\n return { include: includeConfig, associationName: firstSegment };\n }\n\n // Continue building deeper nested includes\n const deeperInclude = buildNestedInclude(\n remainingSegments,\n targetModel,\n nestedReferences,\n allReferences,\n registry,\n false\n );\n if (!deeperInclude) {\n return null;\n }\n includeConfig.include = [deeperInclude.include];\n\n return { include: includeConfig, associationName: firstSegment };\n};\n\n/**\n * Detects if a condition field path matches a reference property and returns include configuration.\n * @param fieldPath - The condition field path (e.g., \"phase.code\" or \"step.phase.code\")\n * @param model - The Sequelize model\n * @param references - Array of reference definitions\n * @param allReferences - Optional map of all reference definitions by model name\n * @returns Object with include config and remaining attribute path, or null if no match\n */\nconst detectReferenceJoin = (\n fieldPath: string,\n model: ModelStatic<any>,\n references?: SequelizeReferenceDefinition[],\n allReferences?: Map<string, SequelizeReferenceDefinition[]>,\n registry?: Registry\n): { include: any; attributePath: string; associationName: string } | null => {\n const pathSegments = fieldPath.split('.');\n\n if (pathSegments.length < 2) {\n // Need at least \"property.attribute\" format\n return null;\n }\n\n // Try to match progressively longer paths (e.g., \"phase\", \"step.phase\")\n // Start from the longest possible path and work backwards to find the best match\n for (let i = pathSegments.length - 1; i >= 1; i--) {\n const referencePath = pathSegments.slice(0, i);\n const attributePath = pathSegments.slice(i).join('.');\n\n const includeResult = buildNestedInclude(referencePath, model, references, allReferences, registry);\n\n if (!includeResult) {\n continue;\n }\n\n // Verify that the attribute path resolves to a single attribute on the final model\n // Traverse the include structure to get the final model\n let finalModel = model;\n for (const segment of referencePath) {\n const assoc = finalModel.associations?.[segment];\n if (!assoc) {\n break;\n }\n finalModel = assoc.target;\n }\n\n // Check if attributePath is a single attribute (not nested)\n const attributeSegments = attributePath.split('.');\n if (attributeSegments.length !== 1 || !finalModel.getAttributes()[attributePath]) {\n continue;\n }\n\n logger.debug(`Auto-detected reference join for condition '${fieldPath}'`, {\n model: model.name,\n referencePath: referencePath.join('.'),\n attributePath,\n associationName: includeResult.associationName\n });\n\n return {\n include: includeResult.include,\n attributePath,\n associationName: includeResult.associationName\n };\n }\n\n return null;\n};\n\n/**\n * Adds an include to options if it doesn't already exist.\n * Handles nested includes by merging them properly.\n */\nconst addIncludeIfNotExists = (options: any, newInclude: any): void => {\n options.include = options.include || [];\n\n // Check if this include already exists (by model and alias)\n const exists = options.include.some((inc: any) => {\n if (typeof inc === 'string') {\n return inc === newInclude.as;\n }\n if (inc.model === newInclude.model && inc.as === newInclude.as) {\n // If it exists and has nested includes, merge them\n if (newInclude.include && inc.include) {\n newInclude.include.forEach((nested: any) => {\n const nestedExists = inc.include.some((existingNested: any) =>\n existingNested.model === nested.model && existingNested.as === nested.as\n );\n if (!nestedExists) {\n inc.include.push(nested);\n }\n });\n } else if (newInclude.include) {\n inc.include = newInclude.include;\n }\n return true;\n }\n return false;\n });\n\n if (!exists) {\n options.include.push(newInclude);\n }\n};\n\nconst addAssociationCondition = (\n conditions: Record<string, any>,\n condition: Condition,\n model: ModelStatic<any>,\n options?: any,\n references?: SequelizeReferenceDefinition[],\n allReferences?: Map<string, SequelizeReferenceDefinition[]>,\n registry?: Registry\n): Record<string, any> => {\n const fieldPath = condition.column;\n const pathSegments = fieldPath.split('.');\n\n // First, try to detect if this matches a reference property\n logger.debug(`[addAssociationCondition] Processing condition '${fieldPath}'`, {\n model: model.name,\n hasReferences: !!references,\n referencesCount: references?.length || 0,\n pathSegmentsLength: pathSegments.length,\n pathSegments,\n willAttemptDetection: !!(references && pathSegments.length >= 2)\n });\n\n if (references && pathSegments.length >= 2) {\n logger.debug(`[addAssociationCondition] Attempting reference join detection for '${fieldPath}'`, {\n model: model.name,\n referencesCount: references.length,\n references: references.map(r => ({ property: r.property, column: r.column })),\n pathSegments,\n hasOptions: !!options\n });\n const referenceJoin = detectReferenceJoin(fieldPath, model, references, allReferences, registry);\n\n if (!referenceJoin) {\n logger.debug(`[addAssociationCondition] Reference join detection returned null for '${fieldPath}'`, {\n model: model.name,\n fieldPath\n });\n }\n\n if (referenceJoin && options) {\n logger.debug(`[addAssociationCondition] Reference join detected successfully for '${fieldPath}'`, {\n model: model.name,\n associationName: referenceJoin.associationName,\n attributePath: referenceJoin.attributePath\n });\n // Add the include to options\n addIncludeIfNotExists(options, referenceJoin.include);\n\n // Build the Sequelize association column syntax\n // For nested paths like \"step.phase.code\", we need \"$step.phase.code$\"\n // The referenceJoin.attributePath already contains just the final attribute name (e.g., \"code\")\n const attributeName = referenceJoin.attributePath;\n // Build the full association path (everything except the final attribute)\n const associationPath = fieldPath.substring(0, fieldPath.length - attributeName.length - 1);\n const sequelizeAssociationColumn = `$${associationPath}.${attributeName}$`;\n\n // Verify the attribute exists on the target model\n // Traverse the association path to get to the final model\n const finalPathSegments = associationPath.split('.');\n let currentModel = model;\n let targetModel = model;\n\n for (const segment of finalPathSegments) {\n const assoc = currentModel.associations?.[segment];\n if (!assoc) {\n throw new Error(`Association ${segment} not found on model ${currentModel.name}`);\n }\n targetModel = assoc.target;\n currentModel = targetModel;\n }\n\n if (!targetModel.getAttributes()[attributeName]) {\n throw new Error(`Attribute ${attributeName} not found on associated model ${targetModel.name} for path ${associationPath}`);\n }\n\n // Handle null values with proper SQL IS NULL / IS NOT NULL syntax\n if (condition.value === null) {\n if (condition.operator === '==' || !condition.operator) {\n logger.trace(`[QueryBuilder] Setting reference condition: ${sequelizeAssociationColumn} IS NULL`);\n conditions[sequelizeAssociationColumn] = {\n [Op.is]: null\n };\n } else if (condition.operator === '!=') {\n logger.trace(`[QueryBuilder] Setting reference condition: ${sequelizeAssociationColumn} IS NOT NULL`);\n conditions[sequelizeAssociationColumn] = {\n [Op.not]: null\n };\n } else {\n logger.error(`Operator ${condition.operator} cannot be used with null value on reference`, { condition });\n throw new Error(`Operator ${condition.operator} cannot be used with null value. Use '==' for IS NULL or '!=' for IS NOT NULL.`);\n }\n return conditions;\n }\n\n const conditionOp = getSequelizeOperator(condition.operator);\n logger.trace(`[QueryBuilder] Setting reference condition: ${sequelizeAssociationColumn} = ${stringifyJSON(condition.value)} (type: ${typeof condition.value})`);\n conditions[sequelizeAssociationColumn] = {\n [conditionOp]: condition.value\n };\n\n return conditions;\n }\n }\n\n // Fall back to original behavior: check for direct Sequelize association\n const [associationName, attributeName] = fieldPath.split('.', 2);\n\n // Check if the association exists on the model\n if (!model.associations || !model.associations[associationName]) {\n throw new Error(`Association ${associationName} not found on model ${model.name}`);\n }\n\n const association: Association<any, any> = model.associations[associationName];\n const associatedModel = association.target;\n\n // Check if the attribute exists on the associated model\n if (!associatedModel.getAttributes()[attributeName]) {\n throw new Error(`Attribute ${attributeName} not found on associated model ${associatedModel.name} for association ${associationName}`);\n }\n\n // Use Sequelize's $association.attribute$ syntax for querying associated models\n const sequelizeAssociationColumn = `$${associationName}.${attributeName}$`;\n\n // Handle null values with proper SQL IS NULL / IS NOT NULL syntax\n if (condition.value === null) {\n if (condition.operator === '==' || !condition.operator) {\n // Use Op.is for IS NULL\n logger.trace(`[QueryBuilder] Setting association condition: ${sequelizeAssociationColumn} IS NULL`);\n conditions[sequelizeAssociationColumn] = {\n [Op.is]: null\n };\n } else if (condition.operator === '!=') {\n // Use Op.not for IS NOT NULL\n logger.trace(`[QueryBuilder] Setting association condition: ${sequelizeAssociationColumn} IS NOT NULL`);\n conditions[sequelizeAssociationColumn] = {\n [Op.not]: null\n };\n } else {\n logger.error(`Operator ${condition.operator} cannot be used with null value on association`, { condition });\n throw new Error(`Operator ${condition.operator} cannot be used with null value. Use '==' for IS NULL or '!=' for IS NOT NULL.`);\n }\n return conditions;\n }\n\n const conditionOp = getSequelizeOperator(condition.operator);\n\n logger.trace(`[QueryBuilder] Setting association condition: ${sequelizeAssociationColumn} = ${stringifyJSON(condition.value)} (type: ${typeof condition.value})`);\n conditions[sequelizeAssociationColumn] = {\n [conditionOp]: condition.value\n };\n\n return conditions;\n};\n\nconst addAttributeCondition = (\n conditions: Record<string, any>,\n condition: Condition,\n model: ModelStatic<any>\n): Record<string, any> => {\n const conditionColumn = condition.column;\n\n if (!model.getAttributes()[conditionColumn]) {\n throw new Error(`Condition column ${conditionColumn} not found on model ${model.name}`);\n }\n\n // Handle null values with proper SQL IS NULL / IS NOT NULL syntax\n if (condition.value === null) {\n if (condition.operator === '==' || !condition.operator) {\n // Use Op.is for IS NULL\n logger.trace(`[QueryBuilder] Setting attribute condition: ${conditionColumn} IS NULL`);\n conditions[conditionColumn] = {\n [Op.is]: null\n };\n } else if (condition.operator === '!=') {\n // Use Op.not for IS NOT NULL\n logger.trace(`[QueryBuilder] Setting attribute condition: ${conditionColumn} IS NOT NULL`);\n conditions[conditionColumn] = {\n [Op.not]: null\n };\n } else {\n logger.error(`Operator ${condition.operator} cannot be used with null value`, { condition });\n throw new Error(`Operator ${condition.operator} cannot be used with null value. Use '==' for IS NULL or '!=' for IS NOT NULL.`);\n }\n return conditions;\n }\n\n const conditionOp = getSequelizeOperator(condition.operator);\n\n logger.trace(`[QueryBuilder] Setting attribute condition: ${conditionColumn} = ${stringifyJSON(condition.value)} (type: ${typeof condition.value})`);\n conditions[conditionColumn] = {\n [conditionOp]: condition.value\n };\n\n return conditions;\n};\n\nexport const addCondition = (\n conditions: Record<string, any>,\n condition: Condition,\n model: ModelStatic<any>,\n options?: any,\n references?: SequelizeReferenceDefinition[],\n allReferences?: Map<string, SequelizeReferenceDefinition[]>,\n registry?: Registry\n) => {\n const conditionColumn: string = condition.column;\n\n // Check if this is an association query (contains a dot)\n if (conditionColumn.includes('.')) {\n return addAssociationCondition(conditions, condition, model, options, references, allReferences, registry);\n }\n\n // Handle regular column queries\n return addAttributeCondition(conditions, condition, model);\n}\n\nconst collectAssociationsFromConditions = (conditions: any): Set<string> => {\n const associations = new Set<string>();\n\n const processObject = (obj: any) => {\n if (typeof obj === 'object' && obj !== null) {\n // Check string keys\n Object.keys(obj).forEach(key => {\n // Check if this is an association reference ($association.attribute$)\n if (typeof key === 'string' && key.startsWith('$') && key.endsWith('$') && key.includes('.')) {\n const associationName = key.substring(1, key.indexOf('.'));\n associations.add(associationName);\n }\n\n // Recursively process nested objects\n if (typeof obj[key] === 'object') {\n processObject(obj[key]);\n }\n });\n\n // Also check Symbol keys (for compound conditions like Op.and, Op.or)\n Object.getOwnPropertySymbols(obj).forEach(symbol => {\n if (typeof obj[symbol] === 'object') {\n processObject(obj[symbol]);\n }\n });\n }\n\n // Handle arrays (for compound conditions that might be arrays)\n if (Array.isArray(obj)) {\n obj.forEach(item => {\n if (typeof item === 'object') {\n processObject(item);\n }\n });\n }\n };\n\n processObject(conditions);\n return associations;\n};\n\nconst addAssociationIncludes = (options: any, model: ModelStatic<any>): any => {\n // Collect all association names used in conditions\n const referencedAssociations = collectAssociationsFromConditions(options.where);\n\n if (referencedAssociations.size > 0) {\n options.include = options.include || [];\n\n // Add each referenced association to the include array\n referencedAssociations.forEach(associationName => {\n // Check if this association is already included\n const alreadyIncluded = options.include.some((inc: any) =>\n (typeof inc === 'string' && inc === associationName) ||\n (typeof inc === 'object' && inc.association === associationName)\n );\n\n if (!alreadyIncluded && model.associations && model.associations[associationName]) {\n options.include.push({\n model: model.associations[associationName].target,\n as: associationName,\n required: false // Use LEFT JOIN so records without associations are still returned\n });\n }\n });\n }\n\n return options;\n};\n\n/**\n * Detects references that can be loaded via Sequelize INCLUDE and adds them to options.\n * This prevents N+1 queries by using JOIN instead of separate queries per item.\n *\n * @param options - Query options to modify\n * @param model - Sequelize model to check for associations\n * @param referenceDefinitions - Reference definitions from library config\n * @returns Modified options with includes added, plus array of property names that were included\n */\nexport const addReferenceIncludes = (\n options: any,\n model: ModelStatic<any>,\n referenceDefinitions: SequelizeReferenceDefinition[]\n): { options: any; includedReferences: string[] } => {\n if (!referenceDefinitions || referenceDefinitions.length === 0) {\n return { options, includedReferences: [] };\n }\n\n const includedReferences: string[] = [];\n options.include = options.include || [];\n\n for (const refDef of referenceDefinitions) {\n // Check if the model has an association matching the reference property\n const association = model.associations && model.associations[refDef.property];\n\n if (association) {\n // Check if this association is already included\n const alreadyIncluded = options.include.some((inc: any) =>\n (typeof inc === 'string' && inc === refDef.property) ||\n (typeof inc === 'object' && inc.as === refDef.property)\n );\n\n if (!alreadyIncluded) {\n logger.default(`Auto-detected association for reference '${refDef.property}' - using INCLUDE to prevent N+1`, {\n property: refDef.property,\n associationType: association.associationType,\n targetModel: association.target.name\n });\n\n // Add the association to includes\n options.include.push({\n model: association.target,\n as: refDef.property,\n required: false // Use LEFT JOIN to preserve items without references\n });\n\n includedReferences.push(refDef.property);\n } else {\n logger.debug(`Association '${refDef.property}' already included in query`, {\n property: refDef.property\n });\n includedReferences.push(refDef.property);\n }\n } else {\n logger.debug(`No association found for reference '${refDef.property}' - will use separate query`, {\n property: refDef.property,\n availableAssociations: Object.keys(model.associations || {})\n });\n }\n }\n\n return { options, includedReferences };\n};\n\n/**\n * Detects aggregations that can be loaded via Sequelize INCLUDE and adds them to options.\n * This prevents N+1 queries by using JOIN instead of separate queries per item.\n *\n * @param options - Query options to modify\n * @param model - Sequelize model to check for associations\n * @param aggregationDefinitions - Aggregation definitions from library config\n * @returns Modified options with includes added, plus array of property names that were included\n */\nexport const addAggregationIncludes = (\n options: any,\n model: ModelStatic<any>,\n aggregationDefinitions: any[]\n): { options: any; includedAggregations: string[] } => {\n if (!aggregationDefinitions || aggregationDefinitions.length === 0) {\n return { options, includedAggregations: [] };\n }\n\n const includedAggregations: string[] = [];\n options.include = options.include || [];\n\n for (const aggDef of aggregationDefinitions) {\n // Check if the model has an association matching the aggregation property\n const association = model.associations && model.associations[aggDef.property];\n\n if (association) {\n // Check if this association is already included\n const alreadyIncluded = options.include.some((inc: any) =>\n (typeof inc === 'string' && inc === aggDef.property) ||\n (typeof inc === 'object' && inc.as === aggDef.property)\n );\n\n if (!alreadyIncluded) {\n logger.default(`Auto-detected association for aggregation '${aggDef.property}' - using INCLUDE to prevent N+1`, {\n property: aggDef.property,\n associationType: association.associationType,\n targetModel: association.target.name\n });\n\n // Add the association to includes\n options.include.push({\n model: association.target,\n as: aggDef.property,\n required: false // Use LEFT JOIN to preserve items without aggregations\n });\n\n includedAggregations.push(aggDef.property);\n } else {\n logger.debug(`Association '${aggDef.property}' already included in query`, {\n property: aggDef.property\n });\n includedAggregations.push(aggDef.property);\n }\n } else {\n logger.debug(`No association found for aggregation '${aggDef.property}' - will use separate query`, {\n property: aggDef.property,\n availableAssociations: Object.keys(model.associations || {})\n });\n }\n }\n\n return { options, includedAggregations };\n};\n\nexport const buildQuery = (\n itemQuery: ItemQuery,\n model: ModelStatic<any>,\n references?: SequelizeReferenceDefinition[],\n registry?: Registry\n): any => {\n logger.default(`QueryBuilder build called with itemQuery: ${stringifyJSON(itemQuery)}`);\n logger.debug(`[buildQuery] Parameters:`, {\n modelName: model.name,\n referencesCount: references?.length || 0,\n references: references?.map(r => ({ property: r.property, column: r.column })) || [],\n hasRegistry: !!registry,\n hasCompoundCondition: !!itemQuery.compoundCondition\n });\n\n let options: any = {\n where: {},\n };\n\n // Build a map of references by model name for nested reference lookups\n // This is a simplified approach - in a real scenario, we'd need to resolve\n // model names from the registry, but for now we'll use the references array\n const allReferences = new Map<string, SequelizeReferenceDefinition[]>();\n if (references) {\n // For now, we'll store references under the current model name\n // In a full implementation, we'd need to resolve model names from the registry\n allReferences.set(model.name, references);\n }\n\n if (itemQuery.compoundCondition) {\n logger.default(`QueryBuilder adding conditions: ${stringifyJSON(itemQuery.compoundCondition)}`);\n options = addCompoundCondition(options, itemQuery.compoundCondition, model, references, allReferences, registry);\n }\n\n // If the model has a deletedAt column, we need to add a delete query\n if (model.getAttributes().deletedAt || model.getAttributes().isDeleted) {\n options = addDeleteQuery(options, model);\n }\n\n if (itemQuery.refs) {\n options = addReferenceQueries(options, itemQuery.refs, model);\n }\n if (itemQuery.events) {\n options = addEventQueries(options, itemQuery.events, model);\n }\n\n // TODO: Once we start to support Aggs on the server-side, we'll need to parse agg queries\n\n // Apply a limit to the result set\n if (itemQuery.limit) {\n logger.default(`QueryBuilder applying limit: ${itemQuery.limit}`);\n options.limit = itemQuery.limit;\n }\n\n // Apply an offset to the result set\n if (itemQuery.offset) {\n options.offset = itemQuery.offset;\n }\n\n // Add orderBy to the query\n if (itemQuery.orderBy) {\n itemQuery.orderBy.forEach((orderBy: OrderBy) => {\n if (!model.getAttributes()[orderBy.field]) {\n throw new Error(`Order by field ${orderBy.field} not found on model ${model.name}`);\n }\n options.order = [\n [orderBy.field, orderBy.direction]\n ];\n });\n }\n\n // Add includes for any associations referenced in conditions\n // This will pick up includes added by reference detection as well as direct association references\n options = addAssociationIncludes(options, model);\n\n return options;\n}\n", "\n/* eslint-disable */\nexport const clean = (obj: any) => {\n return Object.fromEntries(\n Object.entries(obj).filter(([_, v]) => v !== undefined)\n );\n}\n\n//Recursive implementation of jSON.stringify;\nexport const stringifyJSON = function (obj: any, visited: Set<any> = new Set()): string {\n const arrOfKeyVals: string[] = [];\n const arrVals: string[] = [];\n let objKeys: string[] = [];\n\n /*********CHECK FOR PRIMITIVE TYPES**********/\n if (typeof obj === 'number' || typeof obj === 'boolean' || obj === null)\n return '' + obj;\n else if (typeof obj === 'string')\n return '\"' + obj + '\"';\n\n /*********DETECT CIRCULAR REFERENCES**********/\n if (obj instanceof Object && visited.has(obj)) {\n return '\"(circular)\"';\n }\n\n /*********CHECK FOR ARRAY**********/\n else if (Array.isArray(obj)) {\n //check for empty array\n if (obj.length === 0)\n return '[]';\n else {\n // Add array to visited before processing its elements\n visited.add(obj);\n obj.forEach(function (el) {\n arrVals.push(stringifyJSON(el, visited));\n });\n // Remove from visited after processing to allow arrays at different levels\n visited.delete(obj);\n return '[' + arrVals + ']';\n }\n }\n /*********CHECK FOR OBJECT**********/\n else if (obj instanceof Object) {\n // Add object to visited before processing its properties\n visited.add(obj);\n //get object keys\n objKeys = Object.keys(obj);\n //set key output;\n objKeys.forEach(function (key) {\n const keyOut = '\"' + key + '\":';\n const keyValOut = obj[key];\n //skip functions and undefined properties\n if (keyValOut instanceof Function || keyValOut === undefined)\n return; // Skip this entry entirely instead of pushing an empty string\n else if (typeof keyValOut === 'string')\n arrOfKeyVals.push(keyOut + '\"' + keyValOut + '\"');\n else if (typeof keyValOut === 'boolean' || typeof keyValOut === 'number' || keyValOut === null)\n arrOfKeyVals.push(keyOut + keyValOut);\n //check for nested objects, call recursively until no more objects\n else if (keyValOut instanceof Object) {\n arrOfKeyVals.push(keyOut + stringifyJSON(keyValOut, visited));\n }\n });\n // Remove from visited after processing to allow objects at different levels\n visited.delete(obj);\n return '{' + arrOfKeyVals + '}';\n }\n return '';\n};\n", "/* eslint-disable indent */\nimport { ModelStatic } from 'sequelize';\n\nexport interface RelationshipChainResult {\n success: boolean;\n path?: string;\n includes?: any[];\n}\n\nexport interface RelationshipPathResult {\n found: boolean;\n path?: string;\n includes?: any[];\n isDirect?: boolean;\n}\n\n/**\n * Helper function to build relationship chain includes\n */\nexport const buildRelationshipChain = (\n targetModel: ModelStatic<any>,\n kta: string[],\n currentIndex: number,\n targetIndex: number\n): RelationshipChainResult => {\n // Build the association path and validate relationships exist\n const associationParts: string[] = [];\n const modelChain: ModelStatic<any>[] = [targetModel];\n let currentModel = targetModel;\n\n // Validate that all associations exist and build model chain\n for (let i = currentIndex + 1; i <= targetIndex; i++) {\n const intermediateType = kta[i];\n const associationName = intermediateType;\n\n if (!currentModel.associations || !currentModel.associations[associationName]) {\n return { success: false };\n }\n\n associationParts.push(associationName);\n currentModel = currentModel.associations[associationName].target;\n modelChain.push(currentModel);\n }\n\n // Build the full association path for the target field\n const targetPrimaryKey = currentModel.primaryKeyAttribute || 'id';\n const associationPath = `$${associationParts.join('.')}.${targetPrimaryKey}$`;\n\n // Build nested includes structure iteratively (clearer than recursion)\n let deepestInclude: any = null;\n\n // Build from the deepest level back to the root\n for (let i = targetIndex; i > currentIndex; i--) {\n const currentType = kta[i];\n const modelIndex = i - currentIndex;\n\n const includeObj: any = {\n model: modelChain[modelIndex],\n as: currentType,\n required: true\n };\n\n if (deepestInclude) {\n includeObj.include = [deepestInclude];\n }\n\n deepestInclude = includeObj;\n }\n\n const includes = deepestInclude ? [deepestInclude] : [];\n\n return { success: true, path: associationPath, includes };\n};\n\n/**\n * Helper function to build relationship path for a locator\n * @param includeIsDirect Whether to include the isDirect flag in the result\n */\nexport const buildRelationshipPath = (\n targetModel: ModelStatic<any>,\n locatorType: string,\n kta: string[],\n includeIsDirect: boolean = false\n): RelationshipPathResult => {\n\n // First check if the field exists directly\n const directFieldName = `${locatorType}Id`;\n const attributes = targetModel.getAttributes();\n if (attributes && attributes[directFieldName]) {\n const result: RelationshipPathResult = { found: true };\n if (includeIsDirect) {\n result.isDirect = true;\n }\n return result;\n }\n\n // If not direct, look for relationship path\n const targetIndex = kta.indexOf(locatorType);\n if (targetIndex === -1) {\n const result: RelationshipPathResult = { found: false };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n }\n\n const currentIndex = 0; // We're always looking from the base model\n\n if (targetIndex <= currentIndex) {\n const result: RelationshipPathResult = { found: false };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n }\n\n const chainResult = buildRelationshipChain(targetModel, kta, currentIndex, targetIndex);\n if (chainResult.success) {\n const result: RelationshipPathResult = {\n found: true,\n path: chainResult.path,\n includes: chainResult.includes\n };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n }\n\n const result: RelationshipPathResult = { found: false };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n};\n", "/* eslint-disable max-len */\n/* eslint-disable indent */\nimport {\n AllItemTypeArrays,\n Item,\n} from '@fjell/core';\n\nimport LibLogger from './logger';\nimport { Model, ModelStatic } from 'sequelize';\nimport { buildRelationshipPath } from './util/relationshipUtils';\n\nconst logger = LibLogger.get('sequelize', 'KeyMaster');\n\n// Helper function to extract location key value from item\nconst extractLocationKeyValue = (\n model: ModelStatic<any>,\n item: any,\n locatorType: string,\n kta: string[]\n): any => {\n logger.default('Extracting location key value', { locatorType, kta });\n\n const relationshipInfo = buildRelationshipPath(model, locatorType, kta, true);\n\n if (!relationshipInfo.found) {\n throw new Error(`Location key '${locatorType}' cannot be resolved on model '${model.name}' or through its relationships. Key type array: [${kta.join(', ')}]. Available associations: [${Object.keys(model.associations || {}).join(', ')}]`);\n }\n\n if (relationshipInfo.isDirect) {\n // Direct foreign key field\n const foreignKeyField = `${locatorType}Id`;\n const value = item[foreignKeyField];\n if (typeof value === 'undefined' || value === null) {\n throw new Error(`Direct foreign key field '${foreignKeyField}' is missing or null in item. Model: '${model.name}', Locator type: '${locatorType}', Available item properties: [${Object.keys(item || {}).join(', ')}]`);\n }\n return value;\n } else {\n // Need to traverse relationship hierarchy\n // Find the path through the key type array\n const locatorIndex = kta.indexOf(locatorType);\n if (locatorIndex === -1) {\n throw new Error(`Locator type '${locatorType}' not found in key type array. Model: '${model.name}', Key type array: [${kta.join(', ')}]`);\n }\n\n // Start from the current item (index 0 in kta)\n let currentObject = item;\n\n // Traverse through each intermediate relationship to reach the target\n for (let i = 1; i < locatorIndex; i++) {\n const intermediateType = kta[i];\n\n // Check if the intermediate relationship object is loaded\n if (currentObject[intermediateType] && typeof currentObject[intermediateType] === 'object') {\n currentObject = currentObject[intermediateType];\n } else {\n // Try the foreign key approach if the relationship object isn't loaded\n const foreignKeyField = `${intermediateType}Id`;\n if (typeof currentObject[foreignKeyField] !== 'undefined' && currentObject[foreignKeyField] !== null) {\n // We have the foreign key but not the loaded object, we can't traverse further\n throw new Error(`Intermediate relationship '${intermediateType}' is not loaded. Cannot traverse to '${locatorType}'. Model: '${model.name}', Available item properties: [${Object.keys(currentObject || {}).join(', ')}]. Either include the relationship in your query or ensure it's loaded.`);\n }\n throw new Error(`Intermediate relationship '${intermediateType}' is missing in the relationship chain. Model: '${model.name}', Expected path: ${kta.slice(0, locatorIndex + 1).join(' \u2192 ')}, Available item properties: [${Object.keys(currentObject || {}).join(', ')}]`);\n }\n }\n\n // Now extract the target locator value from the current object\n // First try to get it from the loaded relationship object\n if (currentObject[locatorType] && typeof currentObject[locatorType] === 'object' && typeof currentObject[locatorType].id !== 'undefined') {\n return currentObject[locatorType].id;\n }\n\n // If the relationship object isn't loaded, try the foreign key field\n const foreignKeyField = `${locatorType}Id`;\n if (typeof currentObject[foreignKeyField] !== 'undefined' && currentObject[foreignKeyField] !== null) {\n return currentObject[foreignKeyField];\n }\n\n const traversalPath = kta.slice(0, locatorIndex + 1).join(' \u2192 ');\n throw new Error(\n `Unable to extract location key for '${locatorType}'. ` +\n `Neither the relationship object nor direct foreign key is available. ` +\n `Traversal path: ${traversalPath}`\n );\n }\n};\n\nexport const removeKey = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Removing Key', { item });\n delete item.key;\n return item;\n}\n\n// export const populateKey = <\n// S extends string,\n// L1 extends string = never,\n// L2 extends string = never,\n// L3 extends string = never,\n// L4 extends string = never,\n// L5 extends string = never\n// >(\n// item: ItemProperties<S, L1, L2, L3, L4, L5>,\n// keyTypes: AllItemTypeArrays<S, L1, L2, L3, L4, L5>\n// ): ItemProperties<S, L1, L2, L3, L4, L5> => {\n// if (keyTypes.length === 1) {\n// item.key = { kt: keyTypes[0], pk: item.id };\n// delete item.id;\n// } else if (keyTypes.length === 2) {\n// item.key = {\n// kt: keyTypes[0], pk: item.id,\n// // TODO: Shouldn't this be inspecting the model to get the primary key type?\n// loc: [{ kt: keyTypes[1], lk: item[keyTypes[1] + 'Id'] }],\n// };\n// delete item.id;\n// delete item[keyTypes[1] + 'Id'];\n// } else {\n// throw new Error('Not implemented');\n// }\n// return item;\n// }\n\nexport const addKey = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n model: Model<any, any>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n keyTypes: AllItemTypeArrays<S, L1, L2, L3, L4, L5>\n): Item<S, L1, L2, L3, L4, L5> => {\n logger.default('Adding Key', { item });\n const key = {};\n const modelClass = model.constructor as ModelStatic<any>;\n const primaryKeyAttr = modelClass.primaryKeyAttribute;\n\n if (Array.isArray(keyTypes) && keyTypes.length > 1) {\n const type = [...keyTypes];\n const pkType = type.shift();\n Object.assign(key, { kt: pkType, pk: item[primaryKeyAttr] });\n\n // Build location keys for composite key\n const locationKeys = [];\n for (const locatorType of type) {\n try {\n const lk = extractLocationKeyValue(modelClass, item, locatorType, keyTypes as string[]);\n locationKeys.push({ kt: locatorType, lk });\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(`Failed to extract location key for '${locatorType}'`, { error: errorMessage, item, keyTypes });\n throw error;\n }\n }\n\n Object.assign(key, { loc: locationKeys });\n } else {\n Object.assign(key, { kt: keyTypes[0], pk: item[primaryKeyAttr] });\n }\n Object.assign(item, { key });\n return item as Item<S, L1, L2, L3, L4, L5>;\n};\n", "/* eslint-disable indent */\n\nimport { AllItemTypeArrays, Item } from \"@fjell/core\";\nimport { Model } from \"sequelize\";\n\nimport LibLogger from \"./logger\";\nimport { addKey } from \"./KeyMaster\";\nimport { AggregationDefinition, SequelizeReferenceDefinition } from \"./Options\";\nimport * as Library from \"@fjell/lib\";\nimport {\n buildAggregation,\n contextManager,\n createOperationContext,\n OperationContext\n} from \"@fjell/lib\";\nimport { stringifyJSON } from \"./util/general\";\nimport { populateEvents } from \"./EventCoordinator\";\nimport { buildSequelizeReference } from \"./processing/ReferenceBuilder\";\nimport { addRefsToSequelizeItem } from \"./processing/RefsAdapter\";\nimport { addAggsToItem } from \"./processing/AggsAdapter\";\n\nconst logger = LibLogger.get('sequelize', 'RowProcessor');\n\n// Re-export types and functions from @fjell/lib for backwards compatibility\nexport type { OperationContext };\nexport { createOperationContext, contextManager };\n\nexport const processRow = async <S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never>(\n row: Model<any, any>,\n keyTypes: AllItemTypeArrays<S, L1, L2, L3, L4, L5>,\n referenceDefinitions: SequelizeReferenceDefinition[],\n aggregationDefinitions: AggregationDefinition[],\n registry: Library.Registry,\n context?: OperationContext,\n includedAggregations?: string[],\n includedReferences?: string[]\n // eslint-disable-next-line max-params\n ): Promise<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Processing Row', { row });\n\n // Use provided context or create new one\n const operationContext = context || createOperationContext();\n\n // Process the row within the context to ensure all operations share the same context\n return contextManager.withContext(operationContext, async () => {\n let item = row.get({ plain: true }) as any;\n logger.default('Adding Key to Item with Key Types: %s', stringifyJSON(keyTypes));\n item = addKey(row, item, keyTypes);\n item = populateEvents(item);\n logger.default('Key Added to Item: %s', stringifyJSON(item.key));\n\n // Mark this item as in progress to detect circular references\n operationContext.markInProgress(item.key);\n\n try {\n if (referenceDefinitions && referenceDefinitions.length > 0) {\n // Process all references in parallel for better performance\n // Each reference reads from a different column and writes to a different property,\n // so they can safely run in parallel without race conditions\n const referenceStartTime = typeof performance !== 'undefined' ? performance.now() : Date.now();\n const referencePromises = referenceDefinitions.map(async (referenceDefinition) => {\n // Check if this reference was already loaded via INCLUDE (N+1 prevention)\n const alreadyLoaded = includedReferences &&\n includedReferences.includes(referenceDefinition.property) &&\n typeof item[referenceDefinition.property] !== 'undefined';\n\n if (alreadyLoaded) {\n logger.default(\n `Skipping buildSequelizeReference for '${referenceDefinition.property}' - already loaded via INCLUDE (N+1 prevention)`,\n {\n property: referenceDefinition.property,\n itemType: item.key.kt,\n hasData: item[referenceDefinition.property] ? 'loaded' : 'undefined'\n }\n );\n // Data is already on the item, RefsAdapter will move it to refs structure\n return item;\n } else {\n logger.default('Processing Reference for %s to %s', item.key.kt, stringifyJSON(referenceDefinition.kta));\n // buildSequelizeReference modifies item in place, but each modifies a different property\n // so parallel execution is safe\n return buildSequelizeReference(item, referenceDefinition, registry, operationContext);\n }\n });\n\n // Wait for all references to load in parallel\n await Promise.all(referencePromises);\n\n const referenceDuration = (typeof performance !== 'undefined' ? performance.now() : Date.now()) - referenceStartTime;\n if (referenceDuration > 100) {\n logger.debug(`\u23F1\uFE0F REFERENCE_BUILDER_PERF: Loaded ${referenceDefinitions.length} references in parallel for ${item.key.kt} - ${referenceDuration.toFixed(2)}ms`);\n }\n }\n if (aggregationDefinitions && aggregationDefinitions.length > 0) {\n for (const aggregationDefinition of aggregationDefinitions) {\n // Check if this aggregation was already loaded via INCLUDE (Option C optimization)\n const alreadyLoaded = includedAggregations &&\n includedAggregations.includes(aggregationDefinition.property) &&\n typeof item[aggregationDefinition.property] !== 'undefined';\n\n if (alreadyLoaded) {\n logger.default(\n `Skipping buildAggregation for '${aggregationDefinition.property}' - already loaded via INCLUDE (N+1 prevention)`,\n {\n property: aggregationDefinition.property,\n itemType: item.key.kt,\n hasData: Array.isArray(item[aggregationDefinition.property])\n ? `${item[aggregationDefinition.property].length} items`\n : 'single item'\n }\n );\n // Data is already on the item, AggsAdapter will move it to aggs structure\n } else {\n logger.default('Processing Aggregation for %s from %s', item.key.kt, stringifyJSON(aggregationDefinition.kta));\n item = await buildAggregation(item, aggregationDefinition, registry, operationContext);\n }\n }\n }\n\n // Cache the fully processed item\n operationContext.setCached(item.key, item);\n } finally {\n // Mark this item as complete\n operationContext.markComplete(item.key);\n }\n\n // Automatically add refs structure before returning (transparent wrapper)\n // This ensures items leaving the Sequelize library always have Firestore-style refs structure\n if (referenceDefinitions && referenceDefinitions.length > 0) {\n item = addRefsToSequelizeItem(item, referenceDefinitions);\n logger.default('Added refs structure to item (transparent wrapper)', { key: item.key });\n }\n\n // Automatically add aggs structure before returning (transparent wrapper)\n // This ensures items leaving the Sequelize library always have unified aggs structure\n if (aggregationDefinitions && aggregationDefinitions.length > 0) {\n item = addAggsToItem(item, aggregationDefinitions);\n logger.default('Added aggs structure to item (transparent wrapper)', { key: item.key });\n }\n\n logger.default('Processed Row: %j', stringifyJSON(item));\n return item as Item<S, L1, L2, L3, L4, L5>;\n });\n};\n", "import {\n Evented,\n Item,\n ManagedEvents\n} from '@fjell/core';\nimport deepmerge from 'deepmerge';\n\nimport LibLogger from './logger';\n\nconst logger = LibLogger.get(\"sequelize\", \"EventCoordinator\");\n\nexport const createEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>):\n Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Creating Events', { item });\n const currentDate = new Date();\n\n let events = item.events;\n\n if (events) {\n if (!events.created) {\n events = deepmerge(events, { created: { at: currentDate } });\n }\n if (!events.updated) {\n events = deepmerge(events, { updated: { at: currentDate } });\n }\n if (!events.deleted) {\n events = deepmerge(events, { deleted: { at: null } });\n }\n\n } else {\n events = {\n created: { at: currentDate },\n updated: { at: currentDate },\n deleted: { at: null },\n };\n }\n\n return deepmerge(item, { events }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n}\n\nexport const updateEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>):\n Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Updating Events', { item });\n const currentDate = new Date();\n const events: Evented = {\n updated: { at: currentDate },\n };\n\n // TODO: This is clean-up code, we should remove it\n // If the event lacks a created data, let's just insert it here...\n if (!item.events || !item.events.created || !item.events.created.at) {\n events.created = { at: currentDate };\n }\n\n return deepmerge(item, { events }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n}\n//#endregion\n\nexport const populateEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n const events: ManagedEvents = {\n created: { at: item.createdAt || null },\n updated: { at: item.updatedAt || null },\n deleted: { at: null }\n };\n item.events = events;\n return item;\n}\n\nexport const extractEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Extracting Events to database fields', { item });\n\n if (item.events) {\n if (item.events.created?.at) {\n item.createdAt = item.events.created.at;\n }\n if (item.events.updated?.at) {\n item.updatedAt = item.events.updated.at;\n }\n if (item.events.deleted?.at) {\n item.deletedAt = item.events.deleted.at;\n }\n }\n\n return item;\n}\n\nexport const removeEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Removing Events', { item });\n delete item.events;\n return item;\n}\n", "import { ComKey, Item, PriKey } from \"@fjell/core\";\nimport type { Registry } from \"@fjell/lib\";\nimport { OperationContext } from \"@fjell/lib\";\nimport logger from \"../logger\";\n\n/**\n * Sequelize-specific definition for a reference relationship.\n * References in Sequelize are stored as foreign key columns (e.g., \"authorId\")\n * and populated into properties on the item.\n */\nexport interface SequelizeReferenceDefinition {\n /** Column name containing the foreign key value (e.g., \"authorId\") */\n column: string;\n /** Key type array of the referenced item */\n kta: string[];\n /** Property name to populate with the referenced item (e.g., \"author\") */\n property: string;\n /**\n * Optional: Column names for location keys when referencing composite items.\n * If provided, will construct a full ComKey with location context.\n * If omitted for composite items, uses empty loc array to search across all locations.\n *\n * Example: ['phaseId'] for a step reference where you have both stepId and phaseId columns\n */\n locationColumns?: string[];\n}\n\n/**\n * Build a reference by looking up a related item by its key from a column value.\n * The referenced item will be populated directly into a property on the item.\n *\n * @param item - The item to populate with reference data\n * @param referenceDefinition - Sequelize-specific definition of what to reference\n * @param registry - Registry to look up library instances\n * @param context - Optional operation context for caching and cycle detection\n * @returns The item with the reference property populated\n */\nexport const buildSequelizeReference = async (\n item: any,\n referenceDefinition: SequelizeReferenceDefinition,\n registry: Registry,\n context?: OperationContext\n) => {\n const libLogger = logger.get('processing', 'ReferenceBuilder');\n\n // Check if this is a composite item reference (has location hierarchy)\n const isCompositeItem = referenceDefinition.kta.length > 1;\n const primaryKeyType = referenceDefinition.kta[0];\n\n if (isCompositeItem) {\n libLogger.debug(\n 'Detected composite item reference - will use ComKey with empty loc array',\n {\n kta: referenceDefinition.kta,\n primaryKeyType,\n property: referenceDefinition.property,\n column: referenceDefinition.column\n }\n );\n }\n\n // Check if dependencies exist\n if (!registry) {\n throw new Error(\n `This model definition has a reference definition, but the registry is not present. ` +\n `Reference property: '${referenceDefinition.property}', ` +\n `key types: [${referenceDefinition.kta.join(', ')}], column: '${referenceDefinition.column}'`\n );\n }\n\n // Find the Library.Instance for the key type\n const library: any = registry.get(referenceDefinition.kta as any);\n if (!library) {\n throw new Error(\n `This model definition has a reference definition, but the dependency is not present in registry. ` +\n `Reference property: '${referenceDefinition.property}', ` +\n `missing key type: '${primaryKeyType}', column: '${referenceDefinition.column}'`\n );\n }\n\n // Check if the column value is null - if so, skip the reference\n const columnValue = item[referenceDefinition.column];\n if (columnValue == null) {\n item[referenceDefinition.property] = null;\n return item;\n }\n\n // Create the appropriate key type based on whether this is a composite item\n let itemKey: PriKey<string> | ComKey<string>;\n\n if (!isCompositeItem) {\n // Primary item: use PriKey\n itemKey = {\n kt: primaryKeyType,\n pk: columnValue\n };\n } else if (referenceDefinition.locationColumns && referenceDefinition.locationColumns.length > 0) {\n // Composite item with location columns provided: build full ComKey\n const locationTypes = referenceDefinition.kta.slice(1); // Skip primary key type\n const loc: Array<{kt: string, lk: any}> = [];\n let hasNullLocation = false;\n\n for (let i = 0; i < referenceDefinition.locationColumns.length; i++) {\n const columnName = referenceDefinition.locationColumns[i];\n const locValue = item[columnName];\n\n if (locValue == null) {\n libLogger.warning(\n `Location column '${columnName}' is null/undefined for reference '${referenceDefinition.property}'. ` +\n `Falling back to empty loc array search.`\n );\n // Fall back to empty loc array if any location column is missing\n hasNullLocation = true;\n break;\n }\n\n loc.push({\n kt: locationTypes[i],\n lk: locValue\n });\n }\n\n if (hasNullLocation) {\n // Fallback to empty loc array if any location column is missing\n itemKey = {\n kt: primaryKeyType,\n pk: columnValue,\n loc: []\n };\n } else {\n // Build full ComKey with location context\n itemKey = {\n kt: primaryKeyType,\n pk: columnValue,\n loc: loc as any\n };\n\n libLogger.debug('Built full ComKey with location context', {\n itemKey,\n locationColumns: referenceDefinition.locationColumns,\n property: referenceDefinition.property\n });\n }\n } else {\n // Composite item without location columns: use empty loc array\n // This signals \"find this item by primary key across all location contexts\"\n itemKey = {\n kt: primaryKeyType,\n pk: columnValue,\n loc: []\n };\n\n libLogger.default('Using empty loc array for composite item reference', {\n kta: referenceDefinition.kta,\n property: referenceDefinition.property\n });\n }\n\n libLogger.default('Created reference key', {\n itemKey,\n isCompositeItem,\n hasLocationColumns: !!referenceDefinition.locationColumns,\n property: referenceDefinition.property\n });\n\n let referencedItem;\n\n if (context) {\n // Check if we already have this item cached\n if (context.isCached(itemKey)) {\n libLogger.debug('Using cached reference', { itemKey, property: referenceDefinition.property });\n referencedItem = context.getCached(itemKey);\n }\n // Check if this item is currently being loaded (circular dependency)\n else if (context.isInProgress(itemKey)) {\n libLogger.default('Circular dependency detected, creating reference placeholder', {\n itemKey,\n property: referenceDefinition.property\n });\n\n // Create a minimal reference object with just the key to break the cycle\n referencedItem = {\n key: itemKey,\n // Add any other minimal properties that might be needed\n // This prevents infinite loops while still providing the key for identification\n };\n }\n else {\n // Mark this key as in progress before loading\n context.markInProgress(itemKey);\n try {\n // Get the referenced item using the Library.Operations get method (context now managed internally)\n referencedItem = await library!.operations.get(itemKey);\n\n // Cache the result\n context.setCached(itemKey, referencedItem);\n } catch (error: any) {\n throw error; // Re-throw to maintain original behavior\n } finally {\n // Always mark as complete, even if there was an error\n context.markComplete(itemKey);\n }\n }\n } else {\n // Fallback to original behavior if no context provided\n referencedItem = await library!.operations.get(itemKey);\n }\n\n // Store the result in the property on item (Sequelize style - direct property)\n item[referenceDefinition.property] = referencedItem;\n\n return item;\n};\n\n/**\n * Strip populated reference properties from item before writing to database.\n * This ensures we only store the foreign key columns, not the full populated items.\n *\n * @param item - The item to strip references from\n * @param referenceDefinitions - Array of reference definitions to strip\n * @returns The item with only foreign key values (no populated items)\n */\nexport const stripSequelizeReferenceItems = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n referenceDefinitions: SequelizeReferenceDefinition[]\n ): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n const result = { ...item };\n\n // Remove populated reference properties but keep the foreign key columns\n for (const refDef of referenceDefinitions) {\n // Delete the populated property (e.g., delete item.author)\n // Keep the foreign key column (e.g., keep item.authorId)\n delete result[refDef.property as keyof typeof result];\n }\n\n return result;\n};\n\n", "/**\n * RefsAdapter: Transparent wrapper for Sequelize items\n *\n * This module provides transparent conversion between Sequelize's foreign key column pattern\n * and Firestore's refs structure pattern. The wrapper is completely confined to the Sequelize\n * library - items are automatically wrapped when leaving the library and unwrapped when entering.\n *\n * Key Principles:\n * - Transparency: Users never need to think about wrapping/unwrapping\n * - Boundary Confinement: All complexity stays within @fjell/lib-sequelize\n * - Automatic: Wrapping happens on output, unwrapping happens on input\n * - Unified API: External code always sees refs structure, regardless of backend\n */\n\nimport { ComKey, isComKey, isPriKey, Item, PriKey } from \"@fjell/core\";\nimport { SequelizeReferenceDefinition } from \"./ReferenceBuilder\";\nimport logger from \"../logger\";\n\nconst libLogger = logger.get('sequelize', 'processing', 'RefsAdapter');\n\n/**\n * Type for a reference structure with flattened item properties.\n * When populated, item properties are merged directly onto the reference object.\n * This allows access via refs.name.property instead of refs.name.item.property.\n */\nexport type ItemReference = {\n key: PriKey<any> | ComKey<any, any, any, any, any, any>;\n} & Partial<Omit<Item<any, any, any, any, any, any>, 'key'>>;\n\n/**\n * Builds a key structure (PriKey or ComKey) from a foreign key value and reference definition.\n * This converts Sequelize's foreign key column pattern to Fjell's key structure.\n */\nexport function buildKeyFromForeignKey(\n refDef: SequelizeReferenceDefinition,\n foreignKeyValue: any,\n item: any\n): PriKey<any> | ComKey<any, any, any, any, any, any> {\n const primaryKeyType = refDef.kta[0];\n const isCompositeItem = refDef.kta.length > 1;\n\n if (!isCompositeItem) {\n // Primary item reference: use PriKey\n return {\n kt: primaryKeyType,\n pk: foreignKeyValue\n };\n }\n\n // Composite item reference: build ComKey\n const loc: Array<{kt: string, lk: any}> = [];\n\n if (refDef.locationColumns && refDef.locationColumns.length > 0) {\n // Build full ComKey with location context\n for (let i = 0; i < refDef.locationColumns.length; i++) {\n const columnName = refDef.locationColumns[i];\n const locValue = item[columnName];\n\n if (locValue != null) {\n const locationType = refDef.kta[i + 1]; // Skip primary key type\n loc.push({\n kt: locationType,\n lk: locValue\n });\n } else {\n libLogger.debug(\n `Location column '${columnName}' is null/undefined for reference '${refDef.property}'. ` +\n `Using empty loc array.`\n );\n // If any location column is missing, use empty loc array\n break;\n }\n }\n }\n\n return {\n kt: primaryKeyType,\n pk: foreignKeyValue,\n loc: loc.length > 0 ? loc as any : []\n };\n}\n\n/**\n * Converts a Sequelize item to include a flattened refs structure.\n * Foreign key columns are moved to refs[name].key, and populated references\n * have their properties merged directly onto refs[name] (not nested under item).\n *\n * This is called automatically when items leave the Sequelize library (e.g., returned\n * from operations). The refs structure is added transparently - external code always\n * sees items with refs structure, regardless of the underlying storage pattern.\n *\n * @param item - The Sequelize item (plain object)\n * @param referenceDefinitions - Array of SequelizeReferenceDefinition configs\n * @returns The item with a refs structure added\n */\nexport function addRefsToSequelizeItem<T extends Item<any, any, any, any, any, any>>(\n item: T,\n referenceDefinitions: SequelizeReferenceDefinition[]\n): T & { refs: Record<string, ItemReference> } {\n const refs: Record<string, ItemReference> = {};\n\n for (const refDef of referenceDefinitions) {\n const foreignKeyValue = item[refDef.column as keyof T];\n const refName = refDef.property;\n\n if (foreignKeyValue != null) {\n // Build key structure from foreign key\n const key = buildKeyFromForeignKey(refDef, foreignKeyValue, item);\n\n // Get populated reference if available\n const populatedItem = item[refDef.property as keyof T] as Item<any, any, any, any, any, any> | undefined;\n\n if (populatedItem) {\n // Merge item properties directly onto reference object (excluding the item's own key)\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { key: _itemKey, ...itemProperties } = populatedItem;\n refs[refName] = {\n key,\n ...itemProperties\n } as ItemReference;\n } else {\n // Unpopulated reference - just the key\n refs[refName] = {\n key\n };\n }\n } else {\n // Foreign key is null/undefined - still create ref entry but with null key\n refs[refName] = {\n key: {\n kt: refDef.kta[0],\n pk: null as any // Will be handled as null reference\n }\n };\n }\n }\n\n return {\n ...item,\n refs\n } as T & { refs: Record<string, ItemReference> };\n}\n\n/**\n * Updates foreign key columns in a Sequelize item based on refs structure.\n * This is used when writing items that have been modified via the refs structure.\n *\n * With flattened references, item properties are directly on the reference object,\n * so we reconstruct the item if properties beyond 'key' are present.\n *\n * @param item - The Sequelize item to update\n * @param refs - The refs structure containing updated reference keys\n * @param referenceDefinitions - Array of SequelizeReferenceDefinition configs\n */\nexport function updateForeignKeysFromRefs(\n item: any,\n refs: Record<string, ItemReference>,\n referenceDefinitions: SequelizeReferenceDefinition[]\n): void {\n for (const refDef of referenceDefinitions) {\n const refName = refDef.property;\n const ref = refs[refName];\n\n if (ref && ref.key) {\n // Update foreign key column from refs[key].key\n if (isPriKey(ref.key)) {\n item[refDef.column] = ref.key.pk;\n } else if (isComKey(ref.key)) {\n const comKey = ref.key as ComKey<any, any, any, any, any, any>; // Type assertion after isComKey check\n item[refDef.column] = comKey.pk;\n \n // Update location columns if provided\n if (refDef.locationColumns && comKey.loc) {\n comKey.loc.forEach((locItem: any, index: number) => {\n if (refDef.locationColumns && refDef.locationColumns[index]) {\n item[refDef.locationColumns[index]] = locItem.lk;\n }\n });\n }\n }\n\n // Check if reference is populated (has properties beyond 'key')\n // Reconstruct the item from flattened properties\n const { key, ...itemProperties } = ref;\n const hasItemProperties = Object.keys(itemProperties).length > 0;\n \n if (hasItemProperties) {\n // Reconstruct the item with its key and properties\n item[refDef.property] = {\n key,\n ...itemProperties\n } as Item<any, any, any, any, any, any>;\n } else {\n // Unpopulated reference - clear the property\n delete item[refDef.property];\n }\n } else if (ref == null) {\n // Reference was explicitly set to null/undefined in refs - set foreign key to null\n // Only update if the ref was explicitly set (not if it's missing from refs object)\n if (refName in refs) {\n item[refDef.column] = null;\n // Clear populated reference property\n delete item[refDef.property];\n }\n // If ref is not in refs object at all, preserve original foreign key value\n }\n }\n}\n\n/**\n * Removes the refs structure from a Sequelize item, converting it back to\n * the standard Sequelize format with foreign key columns.\n *\n * This is called automatically when items enter the Sequelize library (e.g., passed\n * to create/update operations). The refs structure is removed transparently and\n * foreign key columns are updated from the refs structure if present.\n *\n * @param item - The item with refs structure\n * @param referenceDefinitions - Array of SequelizeReferenceDefinition configs\n * @returns The item without refs structure, with foreign keys updated from refs if present\n */\nexport function removeRefsFromSequelizeItem<T extends Item<any, any, any, any, any, any>>(\n item: Partial<T> & { refs?: Record<string, ItemReference> },\n referenceDefinitions: SequelizeReferenceDefinition[]\n): Partial<T> {\n const result = { ...item } as any;\n\n // If item has refs structure, update foreign keys from it\n if (result.refs) {\n updateForeignKeysFromRefs(result, result.refs, referenceDefinitions);\n // Remove refs property\n delete result.refs;\n }\n // If no refs structure, preserve original foreign key values (no change needed)\n\n return result as T;\n}\n\n/**\n * Creates a Proxy wrapper around a Sequelize item that provides dynamic refs access.\n * This allows reading and writing refs structure while maintaining compatibility\n * with the underlying Sequelize item.\n *\n * @param item - The Sequelize item to wrap\n * @param referenceDefinitions - Array of SequelizeReferenceDefinition configs\n * @returns A proxied item with dynamic refs property\n */\nexport function createRefsProxy<T extends Item<any, any, any, any, any, any>>(\n item: T,\n referenceDefinitions: SequelizeReferenceDefinition[]\n): T & { refs: Record<string, ItemReference> } {\n return new Proxy(item, {\n get(target, prop) {\n if (prop === 'refs') {\n // Rebuild refs structure dynamically to reflect current state\n return addRefsToSequelizeItem(target as T, referenceDefinitions).refs;\n }\n return (target as any)[prop];\n },\n set(target, prop, value) {\n if (prop === 'refs' && typeof value === 'object') {\n // Update foreign keys from refs structure\n updateForeignKeysFromRefs(target, value, referenceDefinitions);\n return true;\n }\n \n // Handle nested refs updates (e.g., item.refs.author.key = {...})\n // This is tricky with Proxy, so we'll rely on the getter rebuilding refs\n (target as any)[prop] = value;\n return true;\n },\n has(target, prop) {\n if (prop === 'refs') {\n return true;\n }\n return prop in target;\n },\n ownKeys(target) {\n return ['refs', ...Object.keys(target)];\n },\n getOwnPropertyDescriptor(target, prop) {\n if (prop === 'refs') {\n return {\n enumerable: true,\n configurable: true,\n value: addRefsToSequelizeItem(target as T, referenceDefinitions).refs\n };\n }\n return Object.getOwnPropertyDescriptor(target, prop);\n }\n }) as T & { refs: Record<string, ItemReference> };\n}\n\n", "/**\n * AggsAdapter: Transparent wrapper for aggregations\n *\n * This module provides transparent conversion between direct aggregation properties\n * and a unified aggs structure pattern. The wrapper is completely confined to the\n * library boundaries - items are automatically wrapped when leaving libraries and\n * unwrapped when entering.\n *\n * Key Principles:\n * - Transparency: Users never need to think about wrapping/unwrapping\n * - Boundary Confinement: All complexity stays within library boundaries\n * - Automatic: Wrapping happens on output, unwrapping happens on input\n * - Unified API: External code always sees aggs structure, regardless of backend\n */\n\nimport { Item } from \"@fjell/core\";\nimport { AggregationDefinition } from \"@fjell/lib\";\nimport logger from \"../logger\";\n\nconst libLogger = logger.get('sequelize', 'processing', 'AggsAdapter');\n\n/**\n * Converts an item to include an aggs structure.\n * Aggregation properties are moved from direct properties to aggs[name].\n *\n * This is called automatically when items leave libraries (e.g., returned\n * from operations). The aggs structure is added transparently - external\n * code always sees items with aggs structure.\n *\n * @param item - The item (plain object)\n * @param aggregationDefinitions - Array of AggregationDefinition configs\n * @returns The item with an aggs structure added\n */\nexport function addAggsToItem<T extends Item<any, any, any, any, any, any>>(\n item: T,\n aggregationDefinitions: AggregationDefinition[]\n): T & { aggs: Record<string, any> } {\n if (!aggregationDefinitions || aggregationDefinitions.length === 0) {\n return item as T & { aggs: Record<string, any> };\n }\n\n const aggs: Record<string, any> = {};\n const result = { ...item } as any;\n\n for (const aggDef of aggregationDefinitions) {\n const aggregationValue = item[aggDef.property as keyof T];\n\n if (typeof aggregationValue !== 'undefined') {\n // Move aggregation from direct property to aggs structure\n aggs[aggDef.property] = aggregationValue;\n // Remove from direct properties\n delete result[aggDef.property];\n libLogger.default(`Moved aggregation '${aggDef.property}' to aggs structure`, {\n property: aggDef.property,\n hasValue: typeof aggregationValue !== 'undefined',\n valueType: Array.isArray(aggregationValue) ? 'array' : typeof aggregationValue\n });\n } else {\n libLogger.debug(`Aggregation '${aggDef.property}' is undefined, skipping`, {\n property: aggDef.property\n });\n }\n }\n\n // Only add aggs property if there are aggregations\n if (Object.keys(aggs).length > 0) {\n return {\n ...result,\n aggs\n } as T & { aggs: Record<string, any> };\n }\n\n return item as T & { aggs: Record<string, any> };\n}\n\n/**\n * Removes the aggs structure from an item, converting it back to\n * direct properties. This is mainly for consistency since aggregations\n * are read-only and typically not written back.\n *\n * This is called automatically when items enter libraries (e.g., passed\n * to create/update operations). The aggs structure is removed transparently.\n *\n * @param item - The item with aggs structure\n * @param aggregationDefinitions - Array of AggregationDefinition configs\n * @returns The item without aggs structure, with aggregations as direct properties\n */\nexport function removeAggsFromItem<T extends Partial<Item<any, any, any, any, any, any>> & { aggs?: Record<string, any> }>(\n item: T,\n aggregationDefinitions: AggregationDefinition[]\n): T {\n if (!aggregationDefinitions || aggregationDefinitions.length === 0) {\n return item;\n }\n\n const result = { ...item } as any;\n\n // If item has aggs structure, move aggregations back to direct properties\n if (result.aggs && typeof result.aggs === 'object') {\n for (const aggDef of aggregationDefinitions) {\n if (typeof result.aggs[aggDef.property] !== 'undefined') {\n result[aggDef.property] = result.aggs[aggDef.property];\n libLogger.debug(`Moved aggregation '${aggDef.property}' from aggs to direct property`, {\n property: aggDef.property\n });\n }\n }\n // Remove aggs property\n delete result.aggs;\n }\n // If no aggs structure, preserve original aggregation values (no change needed)\n\n return result as T;\n}\n\n", "import {\n BusinessLogicError,\n DuplicateError,\n ValidationError\n} from \"@fjell/core\";\n\n/**\n * Transforms Sequelize-specific errors into Fjell error types.\n *\n * Sequelize surfaces both its own error types and raw database error codes:\n * - PostgreSQL: numeric codes like '23505' (unique violation), '23503' (foreign key)\n * - MySQL: named codes like 'ER_DUP_ENTRY', 'ER_NO_REFERENCED_ROW'\n * - SQLite: often no codes, just error messages\n *\n * @param error - The Sequelize error to transform\n * @param itemType - The type of item being operated on\n * @param key - Optional key context for the error\n * @param modelName - Optional model name for enhanced error messages\n * @param itemData - Optional item data for enhanced error messages\n * @returns A Fjell error type or the original error if not recognized\n */\nexport function transformSequelizeError(\n error: any,\n itemType: string,\n key?: any,\n modelName?: string,\n itemData?: any\n): Error {\n // Handle PostgreSQL unique constraint errors (code 23505)\n if (error.code === '23505' || error.original?.code === '23505') {\n const constraint = error.original?.constraint;\n const detail = error.original?.detail;\n \n let message = '';\n if (constraint && detail) {\n message = `Duplicate value violates unique constraint '${constraint}'. ${detail}`;\n } else if (detail) {\n message = `Duplicate value detected. This record already exists. ${detail}`;\n } else {\n message = `${itemType} already exists`;\n }\n \n const field = error.fields ? Object.keys(error.fields)[0] : 'unique constraint';\n return new DuplicateError(message, key, field);\n }\n \n // Handle Sequelize unique constraint errors\n if (error.name === 'SequelizeUniqueConstraintError' || error.code === 'ER_DUP_ENTRY') {\n const field = error.fields ? Object.keys(error.fields)[0] : 'unique constraint';\n return new DuplicateError(\n `${itemType} already exists`,\n key,\n field\n );\n }\n\n // Handle Sequelize validation errors\n if (error.name === 'SequelizeValidationError') {\n const fields = error.errors?.map((e: any) => e.path) || [];\n const message = error.errors?.map((e: any) => e.message).join(', ') ||\n `Validation failed for ${itemType}`;\n return new ValidationError(\n message,\n fields,\n 'Fix validation errors and try again'\n );\n }\n\n // Handle PostgreSQL foreign key constraint errors (code 23503)\n if (error.code === '23503' || error.original?.code === '23503') {\n const constraint = error.original?.constraint;\n const detail = error.original?.detail;\n \n let message = '';\n if (constraint && detail) {\n message = `Foreign key constraint '${constraint}' violated. Referenced record does not exist. ${detail}`;\n } else if (constraint) {\n message = `Foreign key constraint '${constraint}' violated. Referenced record does not exist.`;\n } else if (detail) {\n message = `Referenced record does not exist. Check that all related records are valid. ${detail}`;\n } else {\n message = 'Referenced item does not exist';\n }\n \n return new ValidationError(\n message,\n void 0,\n 'Ensure all referenced items exist before creating this relationship'\n );\n }\n \n // Handle Sequelize foreign key constraint errors\n if (error.name === 'SequelizeForeignKeyConstraintError' || error.code === 'ER_NO_REFERENCED_ROW') {\n return new ValidationError(\n 'Referenced item does not exist',\n void 0,\n 'Ensure all referenced items exist before creating this relationship'\n );\n }\n\n // Handle not null constraint errors (code 23502)\n if (error.code === '23502' || error.original?.code === '23502') {\n const column = error.original?.column;\n const fields = column ? [column] : void 0;\n return new ValidationError(\n column ? `Required field '${column}' cannot be null` : 'Required field is missing or null',\n fields,\n 'Provide all required fields'\n );\n }\n\n // Handle check constraint errors (code 23514)\n if (error.code === '23514' || error.original?.code === '23514') {\n const constraint = error.original?.constraint;\n const detail = error.original?.detail;\n \n let message = '';\n if (constraint && detail) {\n message = `Check constraint '${constraint}' violated. ${detail}`;\n } else if (detail) {\n message = `Data validation failed. Check constraint violated. ${detail}`;\n } else if (constraint) {\n message = `Check constraint '${constraint}' violated`;\n } else {\n message = 'Data validation failed';\n }\n \n return new ValidationError(\n message,\n void 0,\n 'Ensure data meets all constraints'\n );\n }\n\n // Handle unknown column errors\n if (error.name === 'SequelizeDatabaseError' && error.message?.includes('Unknown column')) {\n const match = error.message.match(/Unknown column '(.+?)'/);\n const field = match ? match[1] : 'unknown field';\n return new ValidationError(\n `Invalid field: ${field}`,\n [field],\n 'Check the field names in your request'\n );\n }\n\n // Handle data too long errors (code 22001)\n if (error.code === '22001' || error.original?.code === '22001') {\n const detail = error.original?.detail;\n const message = detail\n ? `Data too long for field. Check string lengths. ${detail}`\n : 'Data too long for field';\n \n return new ValidationError(\n message,\n void 0,\n 'Check string lengths and try again'\n );\n }\n\n // Handle numeric out of range errors (code 22003)\n if (error.code === '22003' || error.original?.code === '22003') {\n const detail = error.original?.detail;\n const message = detail\n ? `Numeric value out of range. Check number values. ${detail}`\n : 'Numeric value out of range';\n \n return new ValidationError(\n message,\n void 0,\n 'Check number values and try again'\n );\n }\n\n // Handle undefined column errors (code 42703)\n if (error.code === '42703' || error.original?.code === '42703') {\n const column = error.original?.column;\n const fields = column ? [column] : void 0;\n const message = column && modelName\n ? `Column '${column}' does not exist in table '${modelName}'`\n : column\n ? `Column '${column}' does not exist`\n : 'Referenced column does not exist';\n \n return new ValidationError(\n message,\n fields,\n 'Check the field names in your request'\n );\n }\n \n // Handle undefined table errors (code 42P01)\n if (error.code === '42P01' || error.original?.code === '42P01') {\n const message = modelName\n ? `Table '${modelName}' does not exist`\n : 'Table does not exist';\n \n return new ValidationError(\n message,\n void 0,\n 'Check the table name and database configuration'\n );\n }\n\n // Handle SQLite-specific errors (no error codes, message-based)\n if (error.message?.includes('notNull Violation') ||\n error.message?.includes('cannot be null')) {\n const fieldMatches = error.message.match(/([a-zA-Z][a-zA-Z0-9_]{0,100}\\.[a-zA-Z][a-zA-Z0-9_]{0,100}) cannot be null/g);\n if (fieldMatches) {\n const fields = fieldMatches.map((match: string) => {\n const parts = match.split('.');\n return parts[1]?.split(' ')[0];\n }).filter(Boolean);\n if (fields.length > 0) {\n return new ValidationError(\n `Required field${fields.length > 1 ? 's' : ''} ${fields.join(', ')} cannot be null`,\n fields,\n 'Provide all required fields'\n );\n }\n }\n return new ValidationError(\n 'Required fields are missing',\n void 0,\n 'Provide all required fields'\n );\n }\n\n // Handle connection errors\n if (error.name === 'SequelizeConnectionError' ||\n error.name === 'SequelizeConnectionRefusedError') {\n return new BusinessLogicError(\n 'Database connection failed',\n 'Check database connectivity and try again',\n true // retryable\n );\n }\n\n // Handle timeout errors\n if (error.name === 'SequelizeTimeoutError') {\n return new BusinessLogicError(\n 'Database operation timed out',\n 'Try again or simplify the operation',\n true // retryable\n );\n }\n\n // Handle database errors without original property but with modelName and itemData\n if (!error.original && modelName && itemData && error.message) {\n const formattedData = JSON.stringify(itemData, null, 2);\n return new Error(\n `Database error in ${modelName}.create(): ${error.message}. Item data: ${formattedData}`\n );\n }\n \n // Handle unknown database errors with original property\n if (error.original && modelName && itemData) {\n const formattedData = JSON.stringify(itemData, null, 2);\n return new Error(\n `Database error in ${modelName}.create(): ${error.message}. Item data: ${formattedData}`\n );\n }\n\n // Pass through other errors unchanged\n return error;\n}\n\n", "import LibLogger from '../logger';\n\nconst logger = LibLogger.get('sequelize', 'metrics', 'QueryMetrics');\n\n/**\n * Tracks query execution metrics for Sequelize operations\n */\nexport class QueryMetrics {\n private totalQueryCount: number = 0;\n private queriesByModel: Map<string, number> = new Map();\n private readonly LOG_INTERVAL: number = 10;\n\n /**\n * Records a query execution for a given model\n * @param modelName - The name of the Sequelize model the query was executed against\n */\n recordQuery(modelName: string): void {\n this.totalQueryCount++;\n \n // Track queries per model\n const currentCount = this.queriesByModel.get(modelName) || 0;\n this.queriesByModel.set(modelName, currentCount + 1);\n\n // Log DEBUG message every 10 queries\n if (this.totalQueryCount % this.LOG_INTERVAL === 0) {\n const modelBreakdown = Array.from(this.queriesByModel.entries())\n .map(([model, count]) => `${model}: ${count}`)\n .join(', ');\n \n logger.debug(\n `Query execution count: ${this.totalQueryCount} total queries. ` +\n `Breakdown by model: ${modelBreakdown || 'none'}`\n );\n }\n }\n\n /**\n * Gets the total number of queries executed\n */\n getTotalQueryCount(): number {\n return this.totalQueryCount;\n }\n\n /**\n * Gets the number of queries executed for a specific model\n */\n getQueryCountForModel(modelName: string): number {\n return this.queriesByModel.get(modelName) || 0;\n }\n\n /**\n * Gets a map of all model query counts\n */\n getQueriesByModel(): Map<string, number> {\n return new Map(this.queriesByModel);\n }\n\n /**\n * Resets all metrics (useful for testing)\n */\n reset(): void {\n this.totalQueryCount = 0;\n this.queriesByModel.clear();\n }\n}\n\n// Export a singleton instance\nexport const queryMetrics = new QueryMetrics();\n\n", "/* eslint-disable indent */\nimport { ComKey, createCreateWrapper, CreateMethod, isComKey, isPriKey, Item, LocKeyArray, PriKey } from \"@fjell/core\";\nimport { validateKeys } from \"@fjell/core/validation\";\n\nimport { Definition } from \"../Definition\";\nimport LibLogger from '../logger';\nimport { processRow } from \"../RowProcessor\";\nimport * as Library from \"@fjell/lib\";\nimport { ModelStatic } from \"sequelize\";\nimport { extractEvents, removeEvents } from \"../EventCoordinator\";\nimport { buildRelationshipChain, buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { stringifyJSON } from \"../util/general\";\nimport { transformSequelizeError } from \"../errors/sequelizeErrorHandler\";\nimport { removeRefsFromSequelizeItem } from \"../processing/RefsAdapter\";\nimport { removeAggsFromItem } from \"../processing/AggsAdapter\";\nimport { queryMetrics } from \"../metrics/QueryMetrics\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'create');\n\n// Helper function to validate hierarchical chain exists\nasync function validateHierarchicalChain(\n models: ModelStatic<any>[],\n locKey: { kt: string; lk: any },\n kta: string[]\n): Promise<void> {\n // Find the direct parent model that contains this locator\n const locatorIndex = kta.indexOf(locKey.kt);\n if (locatorIndex === -1) {\n throw new Error(`Locator type '${locKey.kt}' not found in kta array`);\n }\n\n // Get the model for this locator (define outside try block for catch block access)\n const locatorModel = models[locatorIndex] || models[0]; // Fallback to primary model\n \n try {\n // Build a query to validate the chain exists\n const chainResult = buildRelationshipChain(locatorModel, kta, locatorIndex, kta.length - 1);\n\n if (!chainResult.success) {\n // If we can't build a chain, just validate the record exists\n queryMetrics.recordQuery(locatorModel.name);\n const record = await locatorModel.findByPk(locKey.lk);\n if (!record) {\n throw new Error(`Referenced ${locKey.kt} with id ${locKey.lk} does not exist`);\n }\n return;\n }\n\n // Validate that the chain exists\n const queryOptions: any = {\n where: { id: locKey.lk }\n };\n\n if (chainResult.includes && chainResult.includes.length > 0) {\n queryOptions.include = chainResult.includes;\n }\n\n queryMetrics.recordQuery(locatorModel.name);\n const record = await locatorModel.findOne(queryOptions);\n if (!record) {\n throw new Error(`Referenced ${locKey.kt} with id ${locKey.lk} does not exist or chain is invalid`);\n }\n } catch (error: any) {\n // Transform database errors to Fjell error types\n if (error.original) {\n throw transformSequelizeError(error, locKey.kt, { locKey, kta }, locatorModel.name);\n }\n throw error;\n }\n}\n\nexport const getCreateOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n\n registry: Library.Registry\n): CreateMethod<V, S, L1, L2, L3, L4, L5> => {\n\n const { coordinate, options: { references, aggregations } } = definition;\n const { kta } = coordinate;\n\n return createCreateWrapper(\n coordinate,\n async (\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?: {\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n locations?: never;\n } | {\n key?: never;\n locations: LocKeyArray<L1, L2, L3, L4, L5>,\n }\n ): Promise<V> => {\n const constraints = options?.key\n ? `key: pk=${options.key.pk}, loc=[${isComKey(options.key)\n ? (options.key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')\n : ''}]`\n : options?.locations\n ? `locations: ${options.locations.map(loc => `${loc.kt}=${loc.lk}`).join(', ')}`\n : 'no constraints';\n logger.debug(`CREATE operation called on ${models[0].name} with ${constraints}`);\n logger.default(`Create configured for ${models[0].name} with ${Object.keys(item).length} item fields`);\n\n // Get the primary model (first model in array)\n const model = models[0];\n const modelAttributes = model.getAttributes();\n\n // Validate that all item attributes exist on the model\n let itemData = { ...item } as any;\n\n // TODO: We need the opposite of processRow, something to step down from fjell to database.\n itemData = extractEvents(itemData);\n itemData = removeEvents(itemData);\n \n // Remove refs structure if present (convert back to foreign key columns)\n if (references && references.length > 0) {\n itemData = removeRefsFromSequelizeItem(itemData, references);\n }\n \n // Remove aggs structure if present (convert back to direct properties)\n if (aggregations && aggregations.length > 0) {\n itemData = removeAggsFromItem(itemData, aggregations);\n }\n\n // Validate that all item attributes exist on the model\n const invalidAttributes: string[] = [];\n for (const key of Object.keys(itemData)) {\n if (!modelAttributes[key]) {\n invalidAttributes.push(key);\n }\n }\n\n if (invalidAttributes.length > 0) {\n const availableAttributes = Object.keys(modelAttributes).join(', ');\n throw new Error(\n `Invalid attributes for model '${model.name}': [${invalidAttributes.join(', ')}]. ` +\n `Available attributes: [${availableAttributes}]. ` +\n `Item data: ${JSON.stringify(itemData, null, 2)}`\n );\n }\n\n // Handle key options\n // If a key is supplied, assume its contents are to be assigned to the appropriate ids.\n // For most cases this will be null as key generation is often through autoIncrement.\n // If this is a CItem then the locations will be present.\n if (options?.key) {\n const key = options.key;\n if (isPriKey(key)) {\n // Set the primary key\n itemData.id = key.pk;\n } else if (isComKey(key)) {\n // Set primary key\n itemData.id = key.pk;\n\n // Process location keys - only set direct foreign keys, validate hierarchical chains\n const comKey = key as ComKey<S, L1, L2, L3, L4, L5>;\n const directLocations: Array<{ kt: string; lk: any }> = [];\n const hierarchicalLocations: Array<{ kt: string; lk: any }> = [];\n\n // Categorize location keys as direct or hierarchical\n for (const locKey of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const associations = model.associations ? Object.keys(model.associations) : [];\n const errorMessage = `Composite key locator '${locKey.kt}' cannot be resolved on model '${model.name}' or through its relationships. ` +\n `Available associations: [${associations.join(', ')}]. ` +\n `KTA: [${kta.join(', ')}]. ` +\n `Composite key: ${JSON.stringify(comKey, null, 2)}`;\n logger.error(errorMessage, { key: comKey, kta, associations });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n directLocations.push(locKey);\n } else {\n hierarchicalLocations.push(locKey);\n }\n }\n\n // Set direct foreign keys\n for (const locKey of directLocations) {\n if (locKey.lk == null || locKey.lk === '') {\n logger.error(`Composite key location '${locKey.kt}' has undefined/null lk value`, { locKey, key: comKey });\n throw new Error(`Composite key location '${locKey.kt}' has undefined/null lk value`);\n }\n const foreignKeyField = locKey.kt + 'Id';\n itemData[foreignKeyField] = locKey.lk;\n }\n\n // Validate hierarchical chains exist\n for (const locKey of hierarchicalLocations) {\n await validateHierarchicalChain(models, locKey, kta);\n }\n }\n }\n\n // Handle locations options\n // This is the most frequent way relationship ids will be set\n if (options?.locations) {\n const directLocations: Array<{ kt: string; lk: any }> = [];\n const hierarchicalLocations: Array<{ kt: string; lk: any }> = [];\n\n // Categorize location keys as direct or hierarchical\n for (const locKey of options.locations) {\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const associations = model.associations ? Object.keys(model.associations) : [];\n const errorMessage = `Location key '${locKey.kt}' cannot be resolved on model '${model.name}' or through its relationships. ` +\n `Available associations: [${associations.join(', ')}]. ` +\n `KTA: [${kta.join(', ')}]. ` +\n `Locations: ${JSON.stringify(options.locations, null, 2)}`;\n logger.error(errorMessage, { locations: options.locations, kta, associations });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n directLocations.push(locKey);\n } else {\n hierarchicalLocations.push(locKey);\n }\n }\n\n // Set direct foreign keys\n for (const locKey of directLocations) {\n if (locKey.lk == null || locKey.lk === '') {\n logger.error(`Location option '${locKey.kt}' has undefined/null lk value`, { locKey, locations: options.locations });\n throw new Error(`Location option '${locKey.kt}' has undefined/null lk value`);\n }\n const foreignKeyField = locKey.kt + 'Id';\n itemData[foreignKeyField] = locKey.lk;\n }\n\n // Validate hierarchical chains exist\n for (const locKey of hierarchicalLocations) {\n await validateHierarchicalChain(models, locKey, kta);\n }\n }\n\n // Create the record\n try {\n logger.trace(`[CREATE] Executing ${model.name}.create() with data: ${stringifyJSON(itemData)}`);\n queryMetrics.recordQuery(model.name);\n const createdRecord = await model.create(itemData);\n\n // Add key and events\n // Create operations get their own context since they're top-level operations\n // For create, we don't pre-load aggregations via INCLUDE, so pass void 0\n const processedRecord = await processRow(createdRecord, kta, references || [], aggregations || [], registry, void 0, void 0);\n const result = validateKeys(processedRecord, kta) as V;\n\n logger.debug(`[CREATE] Created ${model.name} with key: ${(result as any).key ? JSON.stringify((result as any).key) : `id=${createdRecord.id}`}`);\n return result;\n } catch (error: any) {\n throw transformSequelizeError(error, kta[0], options?.key, model.name, itemData);\n }\n }\n );\n}\n", "/* eslint-disable indent */\nimport { createFindWrapper, FindMethod, FindOperationResult, FindOptions, Item, LocKeyArray } from \"@fjell/core\";\nimport { validateKeys } from \"@fjell/core/validation\";\n\nimport { Definition } from \"../Definition\";\nimport LibLogger from '../logger';\nimport { ModelStatic } from \"sequelize\";\nimport { processRow } from \"../RowProcessor\";\nimport * as Library from \"@fjell/lib\";\nimport { stringifyJSON } from \"../util/general\";\nimport { transformSequelizeError } from \"../errors/sequelizeErrorHandler\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'find');\n\nexport const getFindOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n): FindMethod<V, S, L1, L2, L3, L4, L5> => {\n\n const { options: { finders, references, aggregations } } = definition;\n\n return createFindWrapper(\n definition.coordinate,\n async (\n finder: string,\n finderParams?: Record<string, string | number | boolean | Date | Array<string | number | boolean | Date>>,\n locations?: LocKeyArray<L1, L2, L3, L4, L5> | [],\n findOptions?: FindOptions\n ): Promise<FindOperationResult<V>> => {\n try {\n const locs = locations ?? [];\n const params = finderParams ?? {};\n const locationFilters = locs.map(loc => `${loc.kt}=${loc.lk}`).join(', ') || 'none';\n logger.debug(\n `FIND operation called on ${models[0].name} with finder '${finder}' ` +\n `and ${locs.length} location filters: ${locationFilters}`\n );\n logger.default(`Find configured for ${models[0].name} using finder '${finder}' with ${Object.keys(params).length} params`);\n\n // Note that we execute the createFinders function here because we want to make sure we're always getting the\n // most up to date methods.\n if (!finders || !finders[finder]) {\n logger.error(`No finders have been defined for this lib`);\n throw new Error(`No finders found`);\n }\n\n const finderMethod = finders[finder];\n if (!finderMethod) {\n logger.error(`Finder %s not found`, finder);\n throw new Error(`Finder ${finder} not found`);\n }\n\n logger.trace(`[FIND] Executing finder '${finder}' on ${models[0].name} with params: ${stringifyJSON(params)}, locations: ${stringifyJSON(locs)}, options: ${stringifyJSON(findOptions)}`);\n // Pass findOptions to finder - finder can opt-in by returning FindOperationResult, or return V[] for legacy behavior\n const finderResult = await finderMethod(params, locs, findOptions);\n\n // Helper function to process items\n const processItems = async (items: any[]): Promise<V[]> => {\n return (await Promise.all(items.map(async (row: any) => {\n // For finders, we don't control the query, so we pass void 0 for includedAggregations\n // The custom finder might have already loaded associations via INCLUDE\n const processedRow = await processRow(row, definition.coordinate.kta, references || [], aggregations || [], registry, void 0, void 0);\n return validateKeys(processedRow, definition.coordinate.kta);\n })) as V[]);\n };\n\n // Check if finder opted-in (returned FindOperationResult) or legacy (returned V[])\n const isOptInResult = finderResult && typeof finderResult === 'object' && 'items' in finderResult && 'metadata' in finderResult;\n\n if (isOptInResult) {\n // Finder opted-in: process items and return FindOperationResult\n const optInResult = finderResult as FindOperationResult<any>;\n const processedResults = optInResult.items && optInResult.items.length > 0\n ? await processItems(optInResult.items)\n : [];\n\n logger.debug(`[FIND] Finder opted-in, found ${processedResults.length} ${models[0].name} records using finder '${finder}' (total: ${optInResult.metadata.total})`);\n return {\n items: processedResults,\n metadata: optInResult.metadata\n };\n }\n\n // Legacy finder: process results as array\n const results = finderResult as V[];\n const processedResults = results && results.length > 0\n ? await processItems(results)\n : [];\n\n logger.debug(`[FIND] Legacy finder, found ${processedResults.length} ${models[0].name} records using finder '${finder}'`);\n // Return as FindOperationResult - createFindWrapper will apply post-processing pagination\n return {\n items: processedResults,\n metadata: {\n total: processedResults.length,\n returned: processedResults.length,\n offset: 0,\n hasMore: false\n }\n };\n } catch (error: any) {\n // Enhanced error logging before transforming\n logger.error('Error in find operation', {\n finder,\n finderParams: finderParams,\n locations: locations,\n findOptions,\n errorMessage: error?.message,\n errorName: error?.name,\n errorStack: error?.stack,\n errorCause: error?.cause,\n errorString: String(error),\n errorJSON: JSON.stringify(error, Object.getOwnPropertyNames(error))\n });\n console.error('ERROR in SequelizeLibrary find:', {\n finder,\n error: error?.message || String(error),\n stack: error?.stack\n });\n // Transform database errors\n throw transformSequelizeError(error, definition.coordinate.kta[0]);\n }\n }\n );\n}\n", "/* eslint-disable max-len */\n/* eslint-disable indent */\nimport {\n ComKey,\n createGetWrapper,\n GetMethod,\n isComKey,\n isPriKey,\n isValidItemKey,\n Item,\n PriKey,\n validateKeys\n} from '@fjell/core';\n\nimport LibLogger from '../logger';\nimport { ModelStatic } from 'sequelize';\nimport { processRow } from '../RowProcessor';\nimport { Definition } from '../Definition';\nimport { NotFoundError } from '@fjell/core';\nimport * as Library from \"@fjell/lib\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { contextManager } from \"../RowProcessor\";\nimport { stringifyJSON } from \"../util/general\";\nimport { transformSequelizeError } from \"../errors/sequelizeErrorHandler\";\nimport { addAggregationIncludes, addReferenceIncludes } from \"../QueryBuilder\";\nimport { queryMetrics } from \"../metrics/QueryMetrics\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'get');\n\n// Helper function to process composite key and build query options\nconst processCompositeKey = (\n comKey: ComKey<any, any, any, any, any, any>,\n model: ModelStatic<any>,\n kta: string[]\n): { where: { [key: string]: any }; include?: any[] } => {\n const where: { [key: string]: any } = { id: comKey.pk };\n const includes: any[] = [];\n\n for (const locator of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locator.kt, kta);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Composite key locator '${locator.kt}' cannot be resolved on model '${model.name}' or through its relationships. Key type array: [${kta.join(', ')}], Composite key: ${stringifyJSON(comKey)}, Available associations: [${Object.keys(model.associations || {}).join(', ')}]`;\n logger.error(errorMessage, { key: comKey, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.path) {\n // This requires a relationship traversal\n where[relationshipInfo.path] = locator.lk;\n if (relationshipInfo.includes) {\n includes.push(...relationshipInfo.includes);\n }\n } else {\n // This is a direct field\n const fieldName = `${locator.kt}Id`;\n where[fieldName] = locator.lk;\n }\n }\n\n const result: { where: { [key: string]: any }; include?: any[] } = { where };\n if (includes.length > 0) {\n result.include = includes;\n }\n\n return result;\n};\n\nexport const getGetOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: Array<ModelStatic<any>>,\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n): GetMethod<V, S, L1, L2, L3, L4, L5> => {\n\n const { coordinate, options: { references, aggregations } } = definition;\n const { kta } = coordinate;\n\n return createGetWrapper(\n coordinate,\n async (key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>): Promise<V> => {\n try {\n if (!isValidItemKey(key)) {\n logger.error('Key for Get is not a valid ItemKey: %j', key);\n throw new Error('Key for Get is not a valid ItemKey');\n }\n\n const keyDescription = isPriKey(key)\n ? `primary key: pk=${key.pk}`\n : `composite key: pk=${key.pk}, loc=[${(key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')}]`;\n logger.debug(`GET operation called on ${models[0].name} with ${keyDescription}`);\n logger.default(`Get configured for ${models[0].name} with ${isPriKey(key) ? 'primary' : 'composite'} key`);\n\n const itemKey = key;\n\n // @ts-ignore\n const model = models[0];\n\n let item;\n let includedAggregations: string[] = [];\n let includedReferences: string[] = [];\n\n if (isPriKey(itemKey)) {\n // For primary key lookups, add reference and aggregation includes\n let options: any = {};\n const refResult = addReferenceIncludes(options, model, references || []);\n includedReferences = refResult.includedReferences;\n options = refResult.options;\n const aggResult = addAggregationIncludes(options, model, aggregations || []);\n includedAggregations = aggResult.includedAggregations;\n options = aggResult.options;\n\n // This is the easy case because we can just find the item by its primary key\n logger.trace(`[GET] Executing ${model.name}.findByPk() with pk: ${(itemKey as PriKey<S>).pk}, ${includedReferences.length} reference includes, and ${includedAggregations.length} aggregation includes`);\n queryMetrics.recordQuery(model.name);\n item = options.include && options.include.length > 0\n ? await model.findByPk((itemKey as PriKey<S>).pk, { include: options.include })\n : await model.findByPk((itemKey as PriKey<S>).pk);\n } else if (isComKey(itemKey)) {\n const comKey = itemKey as ComKey<S, L1, L2, L3, L4, L5>;\n\n // Empty loc array is a special case: find by primary key across all locations\n // This is used for foreign key references to composite items where location context is unknown\n if (comKey.loc.length === 0) {\n // For primary key lookups, add reference and aggregation includes\n let options: any = {};\n const refResult = addReferenceIncludes(options, model, references || []);\n includedReferences = refResult.includedReferences;\n options = refResult.options;\n const aggResult = addAggregationIncludes(options, model, aggregations || []);\n includedAggregations = aggResult.includedAggregations;\n options = aggResult.options;\n\n logger.debug(`[GET] Empty loc array detected - finding by primary key across all locations: ${comKey.pk}`);\n logger.trace(`[GET] Executing ${model.name}.findByPk() with pk: ${comKey.pk}, ${includedReferences.length} reference includes, and ${includedAggregations.length} aggregation includes`);\n queryMetrics.recordQuery(model.name);\n item = options.include && options.include.length > 0\n ? await model.findByPk(comKey.pk, { include: options.include })\n : await model.findByPk(comKey.pk);\n } else {\n // This is a composite key with location context, build a where clause based on the locators\n let queryOptions = processCompositeKey(comKey, model, kta);\n\n // Add reference and aggregation includes to the query\n const refResult = addReferenceIncludes(queryOptions, model, references || []);\n includedReferences = refResult.includedReferences;\n queryOptions = refResult.options;\n const aggResult = addAggregationIncludes(queryOptions, model, aggregations || []);\n includedAggregations = aggResult.includedAggregations;\n queryOptions = aggResult.options;\n\n logger.default('Composite key query', { queryOptions });\n logger.trace(`[GET] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}, ${includedReferences.length} reference includes, and ${includedAggregations.length} aggregation includes`);\n queryMetrics.recordQuery(model.name);\n item = await model.findOne(queryOptions);\n }\n }\n\n if (!item) {\n throw new NotFoundError(\n `${kta[0]} not found`,\n kta[0],\n key\n );\n }\n\n // Use current context if available (prevents infinite recursion in reference loading)\n // This ensures proper circular dependency detection within the same operation\n const currentContext = contextManager.getCurrentContext();\n const result = validateKeys(await processRow(item, kta, references || [], aggregations || [], registry, currentContext, includedAggregations, includedReferences), kta) as V;\n\n logger.debug(`[GET] Retrieved ${model.name} with key: ${(result as any).key ? JSON.stringify((result as any).key) : `id=${item.id}`}`);\n return result;\n } catch (error: any) {\n // Transform database errors but pass through NotFoundError\n if (error instanceof NotFoundError) throw error;\n throw transformSequelizeError(error, kta[0], key);\n }\n }\n );\n}\n", "/* eslint-disable indent */\nimport { createOneWrapper, Item, ItemQuery, LocKeyArray, OneMethod } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport LibLogger from '../logger';\nimport { ModelStatic } from \"sequelize\";\nimport { getAllOperation } from \"./all\";\nimport * as Library from \"@fjell/lib\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'one');\n\nexport const getOneOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n): OneMethod<V, S, L1, L2, L3, L4, L5> => {\n return createOneWrapper(\n definition.coordinate,\n async (\n itemQuery?: ItemQuery,\n locations?: LocKeyArray<L1, L2, L3, L4, L5> | []\n ): Promise<V | null> => {\n const locs = locations ?? [];\n logger.debug(`ONE operation called on ${models[0].name} with ${locs.length} location filters: ${locs.map(loc => `${loc.kt}=${loc.lk}`).join(', ') || 'none'}`);\n logger.default(`One configured for ${models[0].name} delegating to all operation`);\n\n const result = await getAllOperation(models, definition, registry)(itemQuery ?? {}, locs, { limit: 1 });\n if (result.items.length > 0) {\n const item = result.items[0] as V;\n logger.debug(`[ONE] Found ${models[0].name} record with key: ${(item as any).key ? JSON.stringify((item as any).key) : 'unknown'}`);\n return item;\n } else {\n logger.debug(`[ONE] No ${models[0].name} record found`);\n return null;\n }\n }\n );\n}", "/* eslint-disable */\nimport { abbrevIK, ComKey, isComKey, isPriKey, isValidItemKey, Item, PriKey, RemoveMethod, createRemoveWrapper } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport { populateEvents } from \"../EventCoordinator\";\nimport { addKey } from \"../KeyMaster\";\nimport LibLogger from '../logger';\nimport { ModelStatic } from \"sequelize\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { stringifyJSON } from \"../util/general\";\nimport { NotFoundError } from \"@fjell/core\";\nimport { transformSequelizeError } from \"../errors/sequelizeErrorHandler\";\nimport { addRefsToSequelizeItem } from \"../processing/RefsAdapter\";\nimport { queryMetrics } from \"../metrics/QueryMetrics\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'remove');\n\n// Helper function to process composite key and build query options\nconst processCompositeKey = (\n comKey: ComKey<any, any, any, any, any, any>,\n model: ModelStatic<any>,\n kta: string[]\n): { where: { [key: string]: any }; include?: any[] } => {\n const where: { [key: string]: any } = { id: comKey.pk };\n const includes: any[] = [];\n\n for (const locator of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locator.kt, kta);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Composite key locator '${locator.kt}' cannot be resolved on model '${model.name}' or through its relationships.`;\n logger.error(errorMessage, { key: comKey, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.path) {\n // This requires a relationship traversal\n where[relationshipInfo.path] = locator.lk;\n if (relationshipInfo.includes) {\n includes.push(...relationshipInfo.includes);\n }\n } else {\n // This is a direct field\n const fieldName = `${locator.kt}Id`;\n where[fieldName] = locator.lk;\n }\n }\n\n const result: { where: { [key: string]: any }; include?: any[] } = { where };\n if (includes.length > 0) {\n result.include = includes;\n }\n\n return result;\n};\n\nexport const getRemoveOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n _registry: import('@fjell/lib').Registry\n): RemoveMethod<V, S, L1, L2, L3, L4, L5> => {\n const { coordinate, options } = definition;\n const { kta } = coordinate;\n\n return createRemoveWrapper(\n coordinate,\n async (key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>): Promise<V> => {\n try {\n if (!isValidItemKey(key)) {\n logger.error('Key for Remove is not a valid ItemKey: %j', key);\n throw new Error('Key for Remove is not a valid ItemKey');\n }\n\n const keyDescription = isPriKey(key)\n ? `primary key: pk=${key.pk}`\n : `composite key: pk=${key.pk}, loc=[${(key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')}]`;\n logger.debug(`REMOVE operation called on ${models[0].name} with ${keyDescription}`);\n logger.default(`Remove configured for ${models[0].name} with ${isPriKey(key) ? 'primary' : 'composite'} key`);\n\n // @ts-ignore\n const model = models[0];\n\n let item;\n let returnItem;\n\n logger.debug('remove: %s', abbrevIK(key));\n if (isPriKey(key)) {\n logger.debug(`[REMOVE] Executing ${model.name}.findByPk() with pk: ${(key as PriKey<S>).pk}`);\n queryMetrics.recordQuery(model.name);\n item = await model.findByPk((key as PriKey<S>).pk);\n } else if (isComKey(key)) {\n // This is a composite key, so we need to build a where clause based on the composite key's locators\n const comKey = key as ComKey<S, L1, L2, L3, L4, L5>;\n const queryOptions = processCompositeKey(comKey, model, kta);\n\n logger.default(`Remove composite key query for ${model.name} with where fields: ${queryOptions.where ? Object.keys(queryOptions.where).join(', ') : 'none'}`);\n logger.debug(`[REMOVE] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}`);\n queryMetrics.recordQuery(model.name);\n item = await model.findOne(queryOptions);\n }\n\n if (!item) {\n throw new NotFoundError(\n `Cannot remove: ${kta[0]} not found`,\n kta[0],\n key\n );\n }\n\n const isDeletedAttribute = model.getAttributes().isDeleted;\n const deletedAtAttribute = model.getAttributes().deletedAt;\n\n if (isDeletedAttribute || deletedAtAttribute) {\n if (model.getAttributes().isDeleted) {\n item.isDeleted = true;\n }\n\n if (model.getAttributes().deletedAt) {\n item.deletedAt = new Date();\n }\n\n // Save the object\n logger.debug(`[REMOVE] Executing ${model.name}.save() for soft delete`);\n queryMetrics.recordQuery(model.name);\n await item?.save();\n returnItem = item?.get({ plain: true }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n returnItem = addKey(item, returnItem as any, kta);\n returnItem = populateEvents(returnItem);\n } else if (options.deleteOnRemove) {\n logger.debug(`[REMOVE] Executing ${model.name}.destroy() for hard delete`);\n queryMetrics.recordQuery(model.name);\n await item?.destroy();\n returnItem = item?.get({ plain: true }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n returnItem = addKey(item, returnItem as any, kta);\n returnItem = populateEvents(returnItem);\n } else {\n throw new Error('No deletedAt or isDeleted attribute found in model, and deleteOnRemove is not set');\n }\n\n logger.debug(`[REMOVE] Removed ${model.name} with key: ${(returnItem as any).key ? JSON.stringify((returnItem as any).key) : `id=${item.id}`}`);\n \n // Automatically add refs structure before returning (transparent wrapper)\n const { references } = options;\n if (references && references.length > 0) {\n returnItem = addRefsToSequelizeItem(returnItem as any, references);\n }\n \n return returnItem as V;\n } catch (error: any) {\n // Transform database errors but pass through NotFoundError\n if (error instanceof NotFoundError) throw error;\n throw transformSequelizeError(error, kta[0], key);\n }\n }\n );\n}\n", "/* eslint-disable indent */\n/* eslint-disable max-depth */\nimport {\n abbrevIK,\n ComKey,\n createUpdateWrapper,\n isComKey,\n isPriKey,\n Item,\n PriKey,\n UpdateMethod,\n UpdateOptions\n} from \"@fjell/core\";\nimport { validateKeys } from \"@fjell/core/validation\";\n\nimport { Definition } from \"../Definition\";\nimport { extractEvents, removeEvents } from \"../EventCoordinator\";\nimport { removeKey } from \"../KeyMaster\";\nimport LibLogger from '../logger';\nimport { processRow } from \"../RowProcessor\";\n\nimport * as Library from \"@fjell/lib\";\nimport { NotFoundError } from \"@fjell/core\";\nimport { ModelStatic, Op } from \"sequelize\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { stringifyJSON } from \"../util/general\";\nimport { transformSequelizeError } from \"../errors/sequelizeErrorHandler\";\nimport { removeRefsFromSequelizeItem } from \"../processing/RefsAdapter\";\nimport { removeAggsFromItem } from \"../processing/AggsAdapter\";\nimport { queryMetrics } from \"../metrics/QueryMetrics\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'update');\n\n// Helper function to merge includes avoiding duplicates\nconst mergeIncludes = (existingIncludes: any[], newIncludes: any[]): any[] => {\n const mergedIncludes = [...existingIncludes];\n\n for (const newInclude of newIncludes) {\n const existingIndex = mergedIncludes.findIndex(\n (existing: any) => existing.as === newInclude.as && existing.model === newInclude.model\n );\n if (existingIndex === -1) {\n mergedIncludes.push(newInclude);\n } else if (newInclude.include && mergedIncludes[existingIndex].include) {\n mergedIncludes[existingIndex].include = [\n ...mergedIncludes[existingIndex].include,\n ...newInclude.include\n ];\n } else if (newInclude.include) {\n mergedIncludes[existingIndex].include = newInclude.include;\n }\n }\n\n return mergedIncludes;\n};\n\nexport const getUpdateOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n\n registry: Library.Registry\n): UpdateMethod<V, S, L1, L2, L3, L4, L5> => {\n\n const { options: { references, aggregations } } = definition;\n\n return createUpdateWrapper(\n definition.coordinate,\n async (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?: UpdateOptions\n ): Promise<V> => {\n try {\n // Check for unsupported replace option\n if (options?.replace) {\n throw new Error(\n 'UpdateOptions.replace is not supported for SQL databases. ' +\n 'SQL UPDATE operations are always partial (they only update specified fields). ' +\n 'To replace an entire record, use remove() followed by create(), ' +\n 'or explicitly set all fields you want to change/clear.'\n );\n }\n \n const keyDescription = isPriKey(key)\n ? `primary key: pk=${key.pk}`\n : `composite key: pk=${key.pk}, loc=[${(key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')}]`;\n logger.debug(`UPDATE operation called on ${models[0].name} with ${keyDescription}`, { options });\n const { coordinate } = definition;\n const { kta } = coordinate;\n\n logger.debug('update: %s, %j', abbrevIK(key), item);\n // Find the object we're updating\n // @ts-ignore\n const model = models[0];\n\n let response;\n\n if (isPriKey(key)) {\n // Find the model by using the PK\n const priKey = key as PriKey<S>;\n logger.trace(`[UPDATE] Executing ${model.name}.findByPk() with pk: ${priKey.pk}`);\n queryMetrics.recordQuery(model.name);\n response = await model.findByPk(priKey.pk);\n } else if (isComKey(key)) {\n const comKey = key as ComKey<S, L1, L2, L3, L4, L5>;\n\n // Build query options for composite key with multiple location keys\n const where: { [key: string]: any } = { id: comKey.pk };\n const additionalIncludes: any[] = [];\n\n // Process all location keys in the composite key\n for (const locator of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locator.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Composite key locator '${locator.kt}' cannot be resolved on model '${model.name}' or through its relationships.`;\n logger.error(errorMessage, { key: comKey, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n // Direct foreign key field\n const fieldName = `${locator.kt}Id`;\n where[fieldName] = locator.lk;\n } else if (relationshipInfo.path) {\n // Hierarchical relationship requiring traversal\n where[relationshipInfo.path] = {\n [Op.eq]: locator.lk\n };\n\n // Add necessary includes for relationship traversal\n if (relationshipInfo.includes) {\n additionalIncludes.push(...relationshipInfo.includes);\n }\n }\n }\n\n // Build final query options\n const queryOptions: any = { where };\n if (additionalIncludes.length > 0) {\n queryOptions.include = mergeIncludes([], additionalIncludes);\n }\n\n logger.default(`Update composite key query for ${model.name} with where fields: ${queryOptions.where ? Object.keys(queryOptions.where).join(', ') : 'none'}`);\n logger.trace(`[UPDATE] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}`);\n queryMetrics.recordQuery(model.name);\n response = await model.findOne(queryOptions);\n }\n\n if (!response) {\n throw new NotFoundError(\n `Cannot update: ${kta[0]} not found`,\n kta[0],\n key\n );\n }\n\n // Remove the key and events\n let updateProps = removeKey(item)\n // TODO: We need the opposite of processRow, something to step down from fjell to database.\n updateProps = extractEvents(updateProps);\n updateProps = removeEvents(updateProps);\n \n // Remove refs structure if present (convert back to foreign key columns)\n if (references && references.length > 0) {\n updateProps = removeRefsFromSequelizeItem(updateProps, references);\n }\n \n // Remove aggs structure if present (convert back to direct properties)\n if (aggregations && aggregations.length > 0) {\n updateProps = removeAggsFromItem(updateProps, aggregations);\n }\n\n logger.default(`Update found ${model.name} record to modify`);\n logger.default(`Update properties configured: ${Object.keys(updateProps).join(', ')}`);\n\n // Update the object\n logger.trace(`[UPDATE] Executing ${model.name}.update() with properties: ${stringifyJSON(updateProps)}`);\n queryMetrics.recordQuery(model.name);\n response = await response.update(updateProps);\n\n // Populate the key and events\n // Update operations get their own context since they're top-level operations\n // For update, we don't pre-load aggregations via INCLUDE, so pass void 0\n const processedItem = await processRow(response, kta, references || [], aggregations || [], registry, void 0, void 0);\n const returnItem = validateKeys(processedItem, kta);\n\n logger.debug(`[UPDATE] Updated ${model.name} with key: ${(returnItem as any).key ? JSON.stringify((returnItem as any).key) : `id=${response.id}`}`);\n return returnItem as V;\n } catch (error: any) {\n // Transform database errors but pass through NotFoundError\n if (error instanceof NotFoundError) throw error;\n throw transformSequelizeError(error, definition.coordinate.kta[0], key);\n }\n }\n );\n}\n", "/* eslint-disable indent */\nimport { ComKey, createUpsertWrapper, isValidItemKey, Item, LocKeyArray, NotFoundError, PriKey, UpdateOptions, UpsertMethod } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport LibLogger from '../logger';\nimport * as Library from \"@fjell/lib\";\nimport { ModelStatic } from \"sequelize\";\nimport { getGetOperation } from \"./get\";\nimport { getUpdateOperation } from \"./update\";\nimport { getCreateOperation } from \"./create\";\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'upsert');\n\nexport const getUpsertOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: Array<ModelStatic<any>>,\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n): UpsertMethod<V, S, L1, L2, L3, L4, L5> => {\n\n // Get the individual operations we'll use\n const get = getGetOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n const update = getUpdateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n const create = getCreateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n\n return createUpsertWrapper(\n definition.coordinate,\n async (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n locations?: LocKeyArray<L1, L2, L3, L4, L5>,\n options?: UpdateOptions\n ): Promise<V> => {\n if (!isValidItemKey(key)) {\n logger.error('Key for Upsert is not a valid ItemKey: %j', key);\n throw new Error(`Key for Upsert is not a valid ItemKey: ${stringifyJSON(key)}`);\n }\n\n logger.debug(`[UPSERT] Attempting upsert with key: ${stringifyJSON(key)}`, { options });\n\n let resultItem: V | null = null;\n\n try {\n // Try to get the existing item first\n logger.debug(`[UPSERT] Retrieving item by key: ${stringifyJSON(key)}`);\n resultItem = await get(key);\n } catch (error: any) {\n // Check if this is a NotFoundError (preserved by core wrapper)\n // Check both instanceof and error code to handle cases where\n // module duplication might break instanceof checks\n const isNotFound = error instanceof NotFoundError ||\n error?.name === 'NotFoundError' ||\n error?.errorInfo?.code === 'NOT_FOUND';\n\n if (isNotFound) {\n // Item doesn't exist, create it\n logger.debug(`[UPSERT] Item not found, creating new item with key: ${stringifyJSON(key)}, errorType: ${error?.name}, errorCode: ${error?.errorInfo?.code}`);\n const createOptions = locations ? { locations } : { key };\n resultItem = await create(item, createOptions);\n } else {\n // Re-throw other errors (connection issues, permissions, etc.)\n logger.error(`[UPSERT] Unexpected error during get operation`, { error: error?.message, name: error?.name, code: error?.errorInfo?.code });\n throw error;\n }\n }\n\n if (!resultItem) {\n throw new Error(`Failed to retrieve or create item for key: ${stringifyJSON(key)}`);\n }\n\n // Always update the item with the new properties (this is what makes it an \"upsert\")\n // Pass through UpdateOptions to control merge vs replace behavior\n logger.debug(`[UPSERT] Updating item with properties, key: ${stringifyJSON(key)}`, { options });\n resultItem = await update(resultItem.key, item, options);\n logger.debug(`[UPSERT] Item upserted successfully: ${stringifyJSON(resultItem)}`);\n\n return resultItem;\n }\n );\n}\n", "import { Coordinate, Item } from \"@fjell/core\";\nimport { Options } from \"./Options\";\nimport { Registry as LocalRegistry } from \"./Registry\";\nimport { InstanceFactory as BaseInstanceFactory, Registry as BaseRegistry, RegistryHub } from \"@fjell/registry\";\nimport { createSequelizeLibrary, SequelizeLibrary } from \"./SequelizeLibrary\";\nimport { ModelStatic } from \"sequelize\";\nimport SequelizeLogger from \"./logger\";\n\nconst logger = SequelizeLogger.get(\"InstanceFactory\");\n\n/**\n * Sequelize Library Factory type that extends the base factory\n * to include Sequelize-specific models parameter\n */\nexport type SequelizeLibraryFactory<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> = (\n models: ModelStatic<any>[],\n options: Options<V, S, L1, L2, L3, L4, L5>\n) => BaseInstanceFactory<S, L1, L2, L3, L4, L5>;\n\n/**\n * Factory function for creating Sequelize libraries\n * This extends the fjell-lib pattern by adding Sequelize-specific models\n */\nexport const createSequelizeLibraryFactory = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n options: Options<V, S, L1, L2, L3, L4, L5>\n ): BaseInstanceFactory<S, L1, L2, L3, L4, L5> => {\n return (coordinate: Coordinate<S, L1, L2, L3, L4, L5>, context: { registry: BaseRegistry, registryHub?: RegistryHub }) => {\n logger.debug(\"Creating Sequelize instance\", {\n coordinate,\n registry: context.registry,\n models: models.map(m => m.name),\n options\n });\n\n return createSequelizeLibrary<V, S, L1, L2, L3, L4, L5>(\n context.registry as LocalRegistry,\n coordinate,\n models,\n options\n ) as SequelizeLibrary<V, S, L1, L2, L3, L4, L5>;\n };\n};\n", "export * from './SequelizeLibrary';\n", "\nimport { SequelizeLibrary as AbstractSequelizeLibrary } from '../SequelizeLibrary';\nimport { Item, ItemTypeArray } from '@fjell/core';\nimport { Contained } from '@fjell/lib';\nimport * as Library from '@fjell/lib';\nimport { createOperations } from '../Operations';\nimport { ModelStatic } from 'sequelize';\nimport { Registry } from '../Registry';\nimport { createOptions, Options } from '../Options';\nimport { Coordinate, createCoordinate } from '../Coordinate';\n\nexport interface SequelizeLibrary<\n V extends Item<S>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> extends AbstractSequelizeLibrary<V, S, L1, L2, L3, L4, L5> {\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>;\n registry: Registry;\n operations: Library.Operations<V, S, L1, L2, L3, L4, L5>;\n options: Options<V, S, L1, L2, L3, L4, L5>;\n models: ModelStatic<any>[];\n}\n\nexport function createSequelizeLibrary<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n keyTypes: ItemTypeArray<S, L1, L2, L3, L4, L5>,\n models: ModelStatic<any>[],\n libOptions: Partial<Options<V, S, L1, L2, L3, L4, L5>> = {},\n scopes: string[] = [],\n registry: Registry\n): SequelizeLibrary<V, S, L1, L2, L3, L4, L5> {\n\n // Create coordinate and options separately following new pattern\n const coordinate = createCoordinate(keyTypes, scopes);\n const options = createOptions(libOptions);\n\n // Create operations with the new signature\n const operations = createOperations<V, S, L1, L2, L3, L4, L5>(models, coordinate, registry, options);\n\n // Wrap operations for contained pattern\n const wrappedOperations = Contained.wrapOperations(operations, options as any, coordinate, registry);\n\n return {\n coordinate,\n registry,\n operations: wrappedOperations,\n options,\n models,\n } as unknown as SequelizeLibrary<V, S, L1, L2, L3, L4, L5>;\n}\n", "export * from './SequelizeLibrary';\n", "\nimport { SequelizeLibrary as AbstractSequelizeLibrary } from '../SequelizeLibrary';\nimport { Item } from '@fjell/core';\nimport { Primary } from '@fjell/lib';\nimport * as Library from '@fjell/lib';\nimport { createOperations } from '../Operations';\nimport { ModelStatic } from 'sequelize';\nimport { createOptions, Options } from '../Options';\nimport { Registry } from '../Registry';\nimport { Coordinate, createCoordinate } from '../Coordinate';\n\nimport LibLogger from '../logger';\n\nconst logger = LibLogger.get('lib-sequelize', 'primary', 'library');\n\nexport interface SequelizeLibrary<\n V extends Item<S>,\n S extends string\n> extends AbstractSequelizeLibrary<V, S> {\n coordinate: Coordinate<S>;\n registry: Registry;\n operations: Library.Operations<V, S>;\n options: Options<V, S>;\n models: ModelStatic<any>[];\n}\n\nexport function createSequelizeLibrary<\n V extends Item<S>,\n S extends string\n>(\n keyType: S,\n models: ModelStatic<any>[],\n libOptions: Partial<Options<V, S>> = {},\n scopes: string[] = [],\n registry: Registry\n): SequelizeLibrary<V, S> {\n logger.debug('createSequelizeLibrary', { keyType, models, libOptions, scopes });\n\n // Create coordinate and options separately following new pattern\n const coordinate = createCoordinate([keyType], scopes);\n const options = createOptions(libOptions);\n\n // Create operations with the new signature\n const operations = createOperations<V, S>(models, coordinate, registry, options);\n\n // Wrap operations for primary pattern\n const wrappedOperations = Primary.wrapOperations(operations, options as any, coordinate, registry);\n\n return {\n coordinate,\n registry,\n operations: wrappedOperations,\n options,\n models,\n } as unknown as SequelizeLibrary<V, S>;\n}\n"],
5
- "mappings": ";;;;;;;AAAA,YAAY,aAAa;AAkFlB,IAAMA,iBAAgB,CAQ3B,qBAA4F;AAE5F,QAAM,EAAE,YAAY,gBAAgB,GAAG,qBAAqB,IAAI,oBAAoB,CAAC;AAGrF,QAAM,cAAsB,sBAAc,oBAAiE;AAG3G,SAAO;AAAA,IACL,GAAG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Z;AAAA,IACA;AAAA,EACF;AACF;",
6
- "names": ["createOptions", "logger", "createOptions", "Library", "Library", "logger", "attributeName", "sequelizeAssociationColumn", "conditionOp", "result", "logger", "foreignKeyField", "logger", "logger", "libLogger", "isComKey", "isPriKey", "isPriKey", "isComKey", "libLogger", "logger", "logger", "Op", "logger", "logger", "loc", "Op", "isComKey", "isPriKey", "validateKeys", "logger", "record", "isComKey", "isPriKey", "validateKeys", "validateKeys", "logger", "validateKeys", "processedResults", "isComKey", "isPriKey", "validateKeys", "logger", "isPriKey", "isComKey", "validateKeys", "logger", "isComKey", "isPriKey", "isValidItemKey", "NotFoundError", "logger", "processCompositeKey", "isValidItemKey", "isPriKey", "isComKey", "NotFoundError", "abbrevIK", "isComKey", "isPriKey", "validateKeys", "NotFoundError", "Op", "logger", "mergeIncludes", "isPriKey", "abbrevIK", "isComKey", "Op", "NotFoundError", "validateKeys", "isValidItemKey", "NotFoundError", "logger", "isValidItemKey", "NotFoundError", "createOptions", "logger", "logger", "createSequelizeLibrary", "createSequelizeLibrary", "createOptions", "createSequelizeLibrary", "logger", "createSequelizeLibrary", "createOptions"]
4
+ "sourcesContent": ["import * as Library from '@fjell/lib';\nimport { ComKey, Item, LocKeyArray, PriKey } from '@fjell/core';\nimport { SequelizeReferenceDefinition } from './processing/ReferenceBuilder';\n\n// Re-export AggregationDefinition from @fjell/lib for backwards compatibility\nexport type { AggregationDefinition } from '@fjell/lib';\n\n// Export Sequelize-specific reference definition\nexport type { SequelizeReferenceDefinition } from './processing/ReferenceBuilder';\n\n/**\n * Sequelize-specific Options that uses SequelizeReferenceDefinition\n * instead of the generic ReferenceDefinition\n */\nexport interface Options<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> {\n hooks?: {\n preCreate?: (\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?:\n {\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n locations?: never;\n } | {\n key?: never;\n locations: LocKeyArray<L1, L2, L3, L4, L5>,\n }\n ) => Promise<Partial<Item<S, L1, L2, L3, L4, L5>>>;\n postCreate?: (\n item: V,\n ) => Promise<V>;\n preUpdate?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n ) => Promise<Partial<Item<S, L1, L2, L3, L4, L5>>>;\n postUpdate?: (\n item: V,\n ) => Promise<V>;\n preRemove?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n ) => Promise<Partial<Item<S, L1, L2, L3, L4, L5>>>;\n postRemove?: (\n item: V,\n ) => Promise<V>;\n },\n validators?: {\n onCreate?: (\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?:\n {\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n locations?: never;\n } | {\n key?: never;\n locations: LocKeyArray<L1, L2, L3, L4, L5>,\n }\n ) => Promise<boolean>;\n onUpdate?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n ) => Promise<boolean>;\n onRemove?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n ) => Promise<boolean>;\n },\n finders?: Record<string, Library.FinderMethod<V, S, L1, L2, L3, L4, L5>>,\n actions?: Record<string, Library.ActionMethod<V, S, L1, L2, L3, L4, L5>>,\n facets?: Record<string, Library.FacetMethod<V, S, L1, L2, L3, L4, L5>>,\n allActions?: Record<string, Library.AllActionMethod<V, S, L1, L2, L3, L4, L5>>,\n allFacets?: Record<string, Library.AllFacetMethod<L1, L2, L3, L4, L5>>,\n references?: SequelizeReferenceDefinition[], // Sequelize-specific!\n aggregations?: Library.AggregationDefinition[],\n deleteOnRemove?: boolean; // Sequelize-specific option\n}\n\nexport const createOptions = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(sequelizeOptions?: Options<V, S, L1, L2, L3, L4, L5>): Options<V, S, L1, L2, L3, L4, L5> => {\n // Convert Sequelize options to Library options (excluding references which have different types)\n const { references, deleteOnRemove, ...libCompatibleOptions } = sequelizeOptions || {};\n \n // Create base options from Library\n const baseOptions = Library.createOptions(libCompatibleOptions as Library.Options<V, S, L1, L2, L3, L4, L5>);\n\n // Return Sequelize options with Sequelize-specific references, aggregations, and deleteOnRemove\n return {\n ...baseOptions,\n references: references ?? [], // Keep Sequelize-specific references\n aggregations: baseOptions.aggregations ?? [], // Ensure aggregations is always present\n deleteOnRemove: deleteOnRemove ?? false, // Sequelize-specific option\n } as Options<V, S, L1, L2, L3, L4, L5>;\n}\n", "import Logging from '@fjell/logging';\n\nconst LibLogger = Logging.getLogger('@fjell/lib-sequelize');\n\nexport default LibLogger;\n", "import { Coordinate, createCoordinate as createBaseCoordinate, ItemTypeArray } from '@fjell/core';\nimport LibLogger from './logger';\n\nconst logger = LibLogger.get('Coordinate');\n\nexport const SCOPE_SEQUELIZE = 'sequelize';\n\nexport const createCoordinate = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(kta: ItemTypeArray<S, L1, L2, L3, L4, L5>, scopes?: string[]): Coordinate<S, L1, L2, L3, L4, L5> => {\n logger.debug('createCoordinate', { kta, scopes });\n const coordinate = createBaseCoordinate(kta, [SCOPE_SEQUELIZE, ...(scopes || [])]);\n return coordinate;\n};\n\n// Re-export the Coordinate type\nexport type { Coordinate } from '@fjell/core';\n", "import { Item, ItemTypeArray } from '@fjell/core';\nimport { createOptions, Options } from './Options';\nimport LibLogger from './logger';\nimport { createCoordinate } from './Coordinate';\n\nconst logger = LibLogger.get('lib-sequelize', 'Definition');\n\nexport interface Definition<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> {\n coordinate: import('@fjell/core').Coordinate<S, L1, L2, L3, L4, L5>;\n options: Options<V, S, L1, L2, L3, L4, L5>;\n}\n\nexport const createDefinition = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n kta: ItemTypeArray<S, L1, L2, L3, L4, L5>,\n scopes: string[],\n libOptions?: Partial<Options<V, S, L1, L2, L3, L4, L5>>,\n ): Definition<V, S, L1, L2, L3, L4, L5> => {\n logger.debug('createDefinition', { kta, scopes, libOptions });\n const coordinate = createCoordinate(kta, scopes);\n const options = createOptions<V, S, L1, L2, L3, L4, L5>(libOptions);\n\n return {\n coordinate,\n options,\n }\n}\n", "\nimport * as Library from '@fjell/lib';\nimport { Coordinate, Item } from '@fjell/core';\nimport { Registry } from './Registry';\nimport { createOperations } from './Operations';\nimport { ModelStatic } from 'sequelize';\nimport { Options } from './Options';\nimport SequelizeLogger from './logger';\n\nconst logger = SequelizeLogger.get(\"SequelizeLibrary\");\n\n/**\n * The SequelizeLibrary interface extends the fjell-lib Library\n * and adds Sequelize-specific functionality:\n * - models: Array of Sequelize model classes for this library\n *\n * @template V - The type of the data model item, extending Item\n * @template S - The string literal type representing the model's key type\n * @template L1-L5 - Optional string literal types for location hierarchy levels\n */\nexport interface SequelizeLibrary<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> extends Library.Library<V, S, L1, L2, L3, L4, L5> {\n /** Array of Sequelize model classes associated with this library */\n models: ModelStatic<any>[];\n}\n\n/**\n * Creates a new SequelizeLibrary that extends the fjell-lib Library\n * with Sequelize-specific functionality\n */\nexport const createSequelizeLibrary = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n registry: Registry,\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>,\n models: ModelStatic<any>[],\n options: Options<V, S, L1, L2, L3, L4, L5>\n ): SequelizeLibrary<V, S, L1, L2, L3, L4, L5> => {\n logger.debug(\"createSequelizeLibrary\", { coordinate, models, registry, options });\n\n // Create Sequelize-specific operations\n const operations = createOperations<V, S, L1, L2, L3, L4, L5>(models, coordinate, registry, options);\n\n // Wrap operations with validation and hooks from base library\n const wrappedOperations = Library.wrapOperations(operations, options, coordinate, registry);\n\n // Create the base fjell-lib library\n const libLibrary = Library.createLibrary(registry, coordinate, wrappedOperations, options);\n\n return {\n ...libLibrary,\n models,\n };\n}\n\n/**\n * Type guard to check if an object is a SequelizeLibrary\n */\nexport const isSequelizeLibrary = (library: any): library is SequelizeLibrary<any, any, any, any, any, any, any> => {\n return library != null &&\n library.coordinate != null &&\n library.operations != null &&\n library.options != null &&\n library.registry != null &&\n library.models != null &&\n Array.isArray(library.models);\n}\n", "/* eslint-disable indent */\nimport { Coordinate, Item } from \"@fjell/core\";\n\nimport * as Library from \"@fjell/lib\";\nimport { Registry } from \"./Registry\";\nimport { getAllOperation } from \"./ops/all\";\nimport { getCreateOperation } from \"./ops/create\";\nimport { getFindOperation } from \"./ops/find\";\nimport { getGetOperation } from \"./ops/get\";\nimport { getOneOperation } from \"./ops/one\";\nimport { getRemoveOperation } from \"./ops/remove\";\nimport { getUpdateOperation } from \"./ops/update\";\nimport { getUpsertOperation } from \"./ops/upsert\";\nimport { ModelStatic } from \"sequelize\";\n\nexport const createOperations = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never,\n>(\n models: Array<ModelStatic<any>>,\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>,\n registry: Registry,\n options: import('./Options').Options<V, S, L1, L2, L3, L4, L5>\n): Library.Operations<V, S, L1, L2, L3, L4, L5> => {\n\n // Create a definition-like object for backward compatibility with existing operation functions\n const definition = { coordinate, options };\n\n // Create implementation operations (core CRUD and query operations only)\n // These are the operations that lib-sequelize actually implements\n const implOps: Library.ImplementationOperations<V, S, L1, L2, L3, L4, L5> = {\n all: getAllOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n one: getOneOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n create: getCreateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n update: getUpdateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n get: getGetOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n remove: getRemoveOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n find: getFindOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n // findOne depends on find, so set it after\n findOne: null as any,\n upsert: getUpsertOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry),\n };\n\n // Set findOne operation that depends on find\n implOps.findOne = async (finder: string, params?: Library.OperationParams, locations?: any): Promise<V | null> => {\n const results = await implOps.find(finder, params || {}, locations);\n return results.items.length > 0 ? results.items[0] : null;\n };\n\n // Wrap with default stub implementations for extended operations (facets, actions)\n // and add metadata dictionaries (finders, actions, facets, allActions, allFacets)\n return Library.wrapImplementationOperations(implOps, options);\n}\n", "/* eslint-disable no-undefined */\n/* eslint-disable indent */\n/* eslint-disable max-depth */\nimport { AllMethod, AllOperationResult, AllOptions, createAllWrapper } from \"@fjell/core\";\nimport { validateKeys } from \"@fjell/core/validation\";\n\nimport { addAggregationIncludes, addReferenceIncludes, buildQuery } from \"../QueryBuilder\";\n\nimport { Definition } from \"../Definition\";\nimport LibLogger from '../logger';\nimport * as Library from \"@fjell/lib\";\nimport { processRow } from \"../RowProcessor\";\nimport { Item, ItemQuery, LocKeyArray } from \"@fjell/core\";\nimport { ModelStatic, Op } from \"sequelize\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { contextManager } from \"../RowProcessor\";\nimport { transformSequelizeError } from \"../errors/sequelizeErrorHandler\";\n\nimport { stringifyJSON } from \"../util/general\";\nimport { queryMetrics } from \"../metrics/QueryMetrics\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'all');\n\n// Helper function to merge includes avoiding duplicates\nconst mergeIncludes = (existingIncludes: any[], newIncludes: any[]): any[] => {\n const mergedIncludes = [...existingIncludes];\n\n for (const newInclude of newIncludes) {\n const existingIndex = mergedIncludes.findIndex(\n (existing: any) => existing.as === newInclude.as && existing.model === newInclude.model\n );\n if (existingIndex === -1) {\n mergedIncludes.push(newInclude);\n } else if (newInclude.include && mergedIncludes[existingIndex].include) {\n mergedIncludes[existingIndex].include = [\n ...mergedIncludes[existingIndex].include,\n ...newInclude.include\n ];\n } else if (newInclude.include) {\n mergedIncludes[existingIndex].include = newInclude.include;\n }\n }\n\n return mergedIncludes;\n};\n\nexport const getAllOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: Array<ModelStatic<any>>,\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n): AllMethod<V, S, L1, L2, L3, L4, L5> => {\n\n const { coordinate, options: { references, aggregations } } = definition;\n\n return createAllWrapper(\n coordinate,\n async (\n itemQuery?: ItemQuery,\n locations?: LocKeyArray<L1, L2, L3, L4, L5> | [],\n allOptions?: AllOptions\n ): Promise<AllOperationResult<V>> => {\n try {\n const locs = locations ?? [];\n logger.debug(`ALL operation called on ${models[0].name} with ${locs.length} location filters: ${locs.map(loc => `${loc.kt}=${loc.lk}`).join(', ') || 'none'}`);\n\n const loc: LocKeyArray<L1, L2, L3, L4, L5> | [] = locs;\n\n // @ts-ignore\n const model = models[0];\n\n // Build base query from itemQuery (includes limit/offset from query)\n let options = buildQuery(itemQuery ?? {}, model, references, registry);\n\n // Auto-detect and add reference INCLUDES to prevent N+1 queries\n const { options: optionsWithRefs, includedReferences } = addReferenceIncludes(\n options,\n model,\n references || []\n );\n options = optionsWithRefs;\n\n // Auto-detect and add aggregation INCLUDES to prevent N+1 queries\n const { options: optionsWithAggs, includedAggregations } = addAggregationIncludes(\n options,\n model,\n aggregations || []\n );\n options = optionsWithAggs;\n\n // Handle location keys if present\n if (loc.length > 0) {\n const { kta } = coordinate;\n const directLocations: Array<{ kt: string; lk: any }> = [];\n const hierarchicalLocations: Array<{ kt: string; lk: any }> = [];\n const additionalIncludes: any[] = [];\n\n // Categorize location keys as direct or hierarchical\n for (const locKey of loc) {\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Location key '${locKey.kt}' cannot be resolved on model '${model.name}' or through its relationships.`;\n logger.error(errorMessage, { locations: loc, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n directLocations.push(locKey);\n } else {\n hierarchicalLocations.push(locKey);\n }\n }\n\n // Handle direct location keys (simple foreign key constraints)\n for (const locKey of directLocations) {\n if (locKey.lk === undefined || locKey.lk == null || locKey.lk === '' || (typeof locKey.lk === 'object' && Object.keys(locKey.lk).length === 0)) {\n logger.error(`Location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`, { locKey, locations: loc });\n throw new Error(`Location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`);\n }\n const foreignKeyField = locKey.kt + 'Id';\n\n // Check if this field already has a condition from the itemQuery\n if (options.where[foreignKeyField]) {\n logger.debug(`[ALL] Field ${foreignKeyField} already constrained by itemQuery, skipping location constraint to avoid conflicts`);\n continue; // Skip this location constraint to avoid conflicts\n }\n\n logger.trace(`[ALL] Setting direct location where clause: ${foreignKeyField} = ${stringifyJSON(locKey.lk)} (type: ${typeof locKey.lk})`);\n options.where[foreignKeyField] = {\n [Op.eq]: locKey.lk\n };\n }\n\n // Handle hierarchical location keys (requires relationship traversal)\n for (const locKey of hierarchicalLocations) {\n if (locKey.lk === undefined || locKey.lk == null || locKey.lk === '' || (typeof locKey.lk === 'object' && Object.keys(locKey.lk).length === 0)) {\n logger.error(`Hierarchical location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`, { locKey, locations: loc });\n throw new Error(`Hierarchical location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`);\n }\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta);\n\n if (relationshipInfo.found && relationshipInfo.path) {\n // Check if this field already has a condition from the itemQuery\n if (options.where[relationshipInfo.path]) {\n logger.debug(`[ALL] Field ${relationshipInfo.path} already constrained by itemQuery, skipping hierarchical location constraint to avoid conflicts`);\n continue; // Skip this location constraint to avoid conflicts\n }\n\n // Add the relationship constraint using the path\n logger.trace(`[ALL] Setting hierarchical location where clause: ${relationshipInfo.path} = ${stringifyJSON(locKey.lk)} (type: ${typeof locKey.lk})`);\n options.where[relationshipInfo.path] = {\n [Op.eq]: locKey.lk\n };\n\n // Add necessary includes for the relationship traversal\n if (relationshipInfo.includes) {\n additionalIncludes.push(...relationshipInfo.includes);\n }\n }\n }\n\n // Merge additional includes with existing includes\n if (additionalIncludes.length > 0) {\n const existingIncludes = options.include || [];\n options.include = mergeIncludes(existingIncludes, additionalIncludes);\n }\n }\n\n // Determine effective limit/offset (options takes precedence over query)\n const effectiveLimit = allOptions?.limit ?? itemQuery?.limit;\n const effectiveOffset = allOptions?.offset ?? itemQuery?.offset ?? 0;\n\n const whereFields = options.where ? Object.keys(options.where).join(', ') : 'none';\n const includeCount = options.include?.length || 0;\n logger.default(\n `All query configured for ${model.name} with where fields: ${whereFields}, ` +\n `includes: ${includeCount}, limit: ${effectiveLimit}, offset: ${effectiveOffset}`\n );\n\n // Execute COUNT query to get total matching records (before pagination)\n // Use only where and include from options, not limit/offset\n const countOptions: any = {\n where: options.where,\n distinct: true\n };\n if (options.include) {\n countOptions.include = options.include;\n }\n\n queryMetrics.recordQuery(model.name);\n const countResult = await model.count(countOptions);\n // Sequelize count() with distinct:true and include can return GroupedCountResultItem[]\n // Extract the count value properly\n const total = Array.isArray(countResult) ? countResult.length : (countResult as number);\n logger.debug(`[ALL] Total count for ${model.name}: ${total}`);\n\n // Apply effective limit/offset for the data query\n // Remove any limit/offset that came from buildQuery (via itemQuery)\n delete options.limit;\n delete options.offset;\n\n if (effectiveLimit !== undefined) {\n options.limit = effectiveLimit;\n }\n if (effectiveOffset > 0) {\n options.offset = effectiveOffset;\n }\n\n try {\n logger.trace(`[ALL] Executing ${model.name}.findAll() with options: ${JSON.stringify(options, null, 2)}`);\n } catch {\n // Fallback for cases where JSON.stringify fails on Sequelize operators\n logger.trace(`[ALL] Executing ${model.name}.findAll() with options containing non-serializable operators (${Object.keys(options.where || {}).length} where conditions)`);\n }\n queryMetrics.recordQuery(model.name);\n const matchingItems = await model.findAll(options);\n\n // this.logger.default('Matching Items', { matchingItems });\n\n // Pass null as context to let processRow create a new context for each top-level operation\n // This prevents circular dependency false positives between concurrent operations\n // while still detecting legitimate circular references within the same operation\n\n // TODO: Move this Up!\n const currentContext = contextManager.getCurrentContext();\n const items = (await Promise.all(matchingItems.map(async (row: any) => {\n // Each row in an all() operation should get its own context to prevent interference\n const processedRow = await processRow(\n row,\n coordinate.kta,\n references || [],\n aggregations || [],\n registry,\n currentContext,\n includedAggregations,\n includedReferences\n );\n return validateKeys(processedRow, coordinate.kta);\n }))) as V[];\n\n logger.debug(`[ALL] Returning ${items.length} of ${total} ${model.name} records`);\n\n // Build and return AllOperationResult\n return {\n items,\n metadata: {\n total,\n returned: items.length,\n limit: effectiveLimit,\n offset: effectiveOffset,\n hasMore: effectiveOffset + items.length < total\n }\n };\n } catch (error: any) {\n // Transform database errors\n throw transformSequelizeError(error, coordinate.kta[0]);\n }\n }\n );\n\n}\n", "/* eslint-disable max-len */\nimport {\n CompoundCondition,\n Condition,\n EventQuery,\n isComKey,\n isCondition,\n isPriKey,\n ItemQuery,\n OrderBy,\n PriKey,\n References\n} from '@fjell/core';\n\nimport { Association, ModelStatic, Op } from 'sequelize';\nimport LibLogger from './logger';\nimport { stringifyJSON } from './util/general';\nimport { SequelizeReferenceDefinition } from './processing/ReferenceBuilder';\nimport type { Registry } from '@fjell/lib';\n\nconst logger = LibLogger.get('sequelize', 'QueryBuilder');\n\nexport type QueryOptions = {\n where: Record<string, any>;\n limit?: number;\n offset?: number;\n order?: Array<[string, string]>;\n include?: Array<any>;\n}\n\nconst addDeleteQuery = (options: QueryOptions, model: ModelStatic<any>): QueryOptions => {\n logger.default(`QueryBuilder adding delete query with options: ${stringifyJSON(options)}`);\n if (model.getAttributes().deletedAt) {\n options.where['deletedAt'] = {\n [Op.eq]: null\n }\n } else if (model.getAttributes().isDeleted) {\n options.where['isDeleted'] = {\n [Op.eq]: false\n }\n }\n\n return options;\n}\n\nconst addEventQueries = (\n options: QueryOptions, events: Record<string, EventQuery>, model: ModelStatic<any>): QueryOptions => {\n logger.default(`QueryBuilder adding event queries with options: ${stringifyJSON(options)}, events: ${stringifyJSON(events)}`);\n Object.keys(events).forEach((key: string) => {\n\n if (!model.getAttributes()[`${key}At`]) {\n throw new Error(`Event ${key} is not supported on model '${model.name}', column '${key}At' not found. Available columns: [${Object.keys(model.getAttributes()).join(', ')}]. Event query: ${stringifyJSON(events[key])}`);\n }\n\n let whereClauses = {};\n\n const event = events[key];\n if (event.start) {\n whereClauses = { ...whereClauses, [Op.gte]: new Date(event.start) };\n }\n if (event.end) {\n whereClauses = { ...whereClauses, [Op.lt]: new Date(event.end) };\n }\n\n if (event.by) {\n if (!model.getAttributes()[`${key}By`]) {\n throw new Error(`Event ${key} is not supported on model '${model.name}', column '${key}By' not found. Available columns: [${Object.keys(model.getAttributes()).join(', ')}]. Event query: ${stringifyJSON(events[key])}`);\n }\n whereClauses = { ...whereClauses, [Op.eq]: event.by };\n }\n\n options.where[`${key}At`] = whereClauses;\n\n });\n return options;\n}\n\n// Add the references to the query\nconst addReferenceQueries = (options: any, references: References, model: ModelStatic<any>): any => {\n logger.default(`QueryBuilder adding reference queries with options: ${stringifyJSON(options)}, references: ${stringifyJSON(references)}`);\n\n Object.keys(references).forEach((key: string) => {\n logger.default(`QueryBuilder adding reference query for key: ${key}, references: ${stringifyJSON(references)}`);\n\n if (!model.getAttributes()[`${key}Id`]) {\n throw new Error(`Reference ${key} is not supported on model '${model.name}', column '${key}Id' not found. Available columns: [${Object.keys(model.getAttributes()).join(', ')}]. Reference query: ${stringifyJSON(references[key])}`);\n }\n\n const refValue = references[key];\n const keyValue = (refValue as any).key || refValue;\n\n if (isPriKey(keyValue)) {\n const priKey: PriKey<string> = keyValue as PriKey<string>;\n\n if (priKey.pk == null || priKey.pk === '' || (typeof priKey.pk === 'object' && Object.keys(priKey.pk).length === 0)) {\n logger.error(`Reference key '${key}' has invalid pk value: ${stringifyJSON(priKey.pk)}`, { priKey, references });\n throw new Error(`Reference key '${key}' has invalid pk value: ${stringifyJSON(priKey.pk)}. Model: '${model.name}', Key type: '${priKey.kt}', Full reference: ${stringifyJSON(references[key])}`);\n }\n\n logger.trace(`[QueryBuilder] Setting reference where clause: ${key}Id = ${stringifyJSON(priKey.pk)} (type: ${typeof priKey.pk})`);\n options.where[`${key}Id`] = {\n [Op.eq]: priKey.pk\n }\n } else if (isComKey(references[key])) {\n throw new Error(`ComKeys are not supported in Sequelize. Reference key: '${key}', Model: '${model.name}', ComKey: ${stringifyJSON(references[key])}`);\n }\n });\n return options;\n}\n\nexport const addCompoundCondition = (\n options: any,\n compoundCondition: CompoundCondition,\n model: ModelStatic<any>,\n references?: SequelizeReferenceDefinition[],\n allReferences?: Map<string, SequelizeReferenceDefinition[]>,\n registry?: Registry\n) => {\n // Ensure options.where exists\n options.where = options.where || {};\n\n let compoundOp: symbol;\n const compoundType = compoundCondition.compoundType;\n if (compoundType === \"AND\") {\n compoundOp = Op.and;\n } else {\n compoundOp = Op.or;\n };\n\n let conditions: Record<string, any> = {};\n compoundCondition.conditions.forEach((condition: Condition | CompoundCondition) => {\n if (isCondition(condition)) {\n conditions = addCondition(conditions, condition, model, options, references, allReferences, registry);\n } else {\n throw new Error(`Nested Compound conditions not supported. Model: '${model.name}', Compound condition: ${stringifyJSON(compoundCondition)}, Nested condition: ${stringifyJSON(condition)}`);\n }\n });\n\n // Merge with existing where conditions instead of replacing\n if (Object.keys(options.where).length > 0) {\n // If there are existing conditions, wrap everything in an AND\n options.where = {\n [Op.and]: [\n options.where,\n { [compoundOp]: conditions }\n ]\n };\n } else {\n // If no existing conditions, just set the compound condition\n options.where[compoundOp] = conditions;\n }\n\n return options;\n}\n\nconst getSequelizeOperator = (operator: string): symbol => {\n if (operator === '==') {\n return Op.eq;\n } else if (operator === '<') {\n return Op.lt;\n } else if (operator === '>') {\n return Op.gt;\n } else if (operator === '<=') {\n return Op.lte;\n } else if (operator === '>=') {\n return Op.gte;\n } else if (operator === 'in') {\n return Op.in;\n } else if (operator === '!=') {\n return Op.ne;\n } else {\n throw new Error(`Operator ${operator} not supported`);\n }\n};\n\n/**\n * Finds a reference definition that matches the given property name.\n * @param propertyName - The property name to match (e.g., \"phase\")\n * @param references - Array of reference definitions\n * @returns The matching reference definition or null\n */\nconst findReferenceByProperty = (\n propertyName: string,\n references?: SequelizeReferenceDefinition[]\n): SequelizeReferenceDefinition | null => {\n if (!references || references.length === 0) {\n return null;\n }\n return references.find(ref => ref.property === propertyName) || null;\n};\n\n/**\n * Gets reference definitions for a model from the registry by looking up the library\n * associated with the model's primary key type.\n * @param model - The Sequelize model\n * @param registry - The registry to look up libraries\n * @returns Array of reference definitions or undefined if not found\n */\nconst getReferencesFromRegistry = (\n model: ModelStatic<any>,\n registry?: Registry\n): SequelizeReferenceDefinition[] | void => {\n if (!registry) {\n return;\n }\n\n // Try to get the library for this model by its name (which often matches the key type)\n // We'll try the model name first, then try common variations\n const modelName = model.name.toLowerCase();\n try {\n const library = registry.get([modelName] as any);\n if (library && (library as any).options && (library as any).options.references) {\n return (library as any).options.references;\n }\n } catch {\n // Model name might not match key type, that's okay\n }\n\n return;\n};\n\n/**\n * Builds nested include structure for a reference path (e.g., \"step.phase.code\").\n * For the first segment, requires a reference definition match.\n * For subsequent segments, looks up reference definitions from registry if available.\n * @param pathSegments - Array of path segments (e.g., [\"step\", \"phase\"])\n * @param currentModel - The current Sequelize model\n * @param references - Array of reference definitions for the current model (only used for first segment)\n * @param allReferences - Map of all reference definitions by model name (for nested references)\n * @param registry - Registry to look up reference definitions for nested models\n * @param isFirstSegment - Whether this is the first segment (requires reference definition match)\n * @returns Include configuration object or null if path cannot be resolved\n */\nconst buildNestedInclude = (\n pathSegments: string[],\n currentModel: ModelStatic<any>,\n references?: SequelizeReferenceDefinition[],\n allReferences?: Map<string, SequelizeReferenceDefinition[]>,\n registry?: Registry,\n isFirstSegment: boolean = true\n): { include: any; associationName: string } | null => {\n if (pathSegments.length === 0) {\n return null;\n }\n\n const [firstSegment, ...remainingSegments] = pathSegments;\n\n // For the first segment, check if it matches a reference definition\n if (isFirstSegment) {\n const refDef = findReferenceByProperty(firstSegment, references);\n if (!refDef) {\n logger.debug(`[buildNestedInclude] No reference definition found for property '${firstSegment}'`, {\n model: currentModel.name,\n property: firstSegment,\n availableReferences: references?.map(r => r.property) || [],\n referencesCount: references?.length || 0\n });\n return null;\n }\n logger.debug(`[buildNestedInclude] Found reference definition for property '${firstSegment}'`, {\n model: currentModel.name,\n property: firstSegment,\n refDef: { property: refDef.property, column: refDef.column, kta: refDef.kta }\n });\n }\n\n // Check if Sequelize association exists\n const association = currentModel.associations?.[firstSegment];\n if (!association) {\n if (isFirstSegment) {\n logger.debug(`[buildNestedInclude] Reference property '${firstSegment}' found but no Sequelize association exists`, {\n model: currentModel.name,\n property: firstSegment,\n availableAssociations: Object.keys(currentModel.associations || {}),\n associationsObject: currentModel.associations ? Object.keys(currentModel.associations) : 'undefined'\n });\n }\n return null;\n }\n logger.debug(`[buildNestedInclude] Found Sequelize association for '${firstSegment}'`, {\n model: currentModel.name,\n property: firstSegment,\n associationType: association.associationType,\n targetModel: association.target?.name\n });\n\n const targetModel = association.target;\n const includeConfig: any = {\n model: targetModel,\n as: firstSegment,\n required: true // Use INNER JOIN for filtering conditions\n };\n\n // If there are remaining segments, recursively build nested includes\n // For nested segments, we use Sequelize associations directly (no reference definition required)\n if (remainingSegments.length === 0) {\n return { include: includeConfig, associationName: firstSegment };\n }\n\n // Try to get nested references from registry first, then fall back to allReferences map\n let nestedReferences: SequelizeReferenceDefinition[] | undefined = getReferencesFromRegistry(targetModel, registry);\n if (!nestedReferences) {\n nestedReferences = allReferences?.get(targetModel.name);\n }\n const nestedInclude = buildNestedInclude(\n remainingSegments,\n targetModel,\n nestedReferences,\n allReferences,\n registry,\n false // Subsequent segments don't require reference definition match\n );\n\n if (nestedInclude) {\n includeConfig.include = [nestedInclude.include];\n return { include: includeConfig, associationName: firstSegment };\n }\n\n // Fallback: try direct Sequelize association lookup for nested paths\n // This allows \"step.phase.code\" to work even if Step model doesn't have \"phase\" in its references\n const [nextSegment, ...restSegments] = remainingSegments;\n const nextAssociation = targetModel.associations?.[nextSegment];\n\n if (!nextAssociation) {\n return null;\n }\n\n if (restSegments.length === 0) {\n // Final segment - just add the include\n includeConfig.include = [{\n model: nextAssociation.target,\n as: nextSegment,\n required: true\n }];\n return { include: includeConfig, associationName: firstSegment };\n }\n\n // Continue building deeper nested includes\n const deeperInclude = buildNestedInclude(\n remainingSegments,\n targetModel,\n nestedReferences,\n allReferences,\n registry,\n false\n );\n if (!deeperInclude) {\n return null;\n }\n includeConfig.include = [deeperInclude.include];\n\n return { include: includeConfig, associationName: firstSegment };\n};\n\n/**\n * Detects if a condition field path matches a reference property and returns include configuration.\n * @param fieldPath - The condition field path (e.g., \"phase.code\" or \"step.phase.code\")\n * @param model - The Sequelize model\n * @param references - Array of reference definitions\n * @param allReferences - Optional map of all reference definitions by model name\n * @returns Object with include config and remaining attribute path, or null if no match\n */\nconst detectReferenceJoin = (\n fieldPath: string,\n model: ModelStatic<any>,\n references?: SequelizeReferenceDefinition[],\n allReferences?: Map<string, SequelizeReferenceDefinition[]>,\n registry?: Registry\n): { include: any; attributePath: string; associationName: string } | null => {\n const pathSegments = fieldPath.split('.');\n\n if (pathSegments.length < 2) {\n // Need at least \"property.attribute\" format\n return null;\n }\n\n // Try to match progressively longer paths (e.g., \"phase\", \"step.phase\")\n // Start from the longest possible path and work backwards to find the best match\n for (let i = pathSegments.length - 1; i >= 1; i--) {\n const referencePath = pathSegments.slice(0, i);\n const attributePath = pathSegments.slice(i).join('.');\n\n const includeResult = buildNestedInclude(referencePath, model, references, allReferences, registry);\n\n if (!includeResult) {\n continue;\n }\n\n // Verify that the attribute path resolves to a single attribute on the final model\n // Traverse the include structure to get the final model\n let finalModel = model;\n for (const segment of referencePath) {\n const assoc = finalModel.associations?.[segment];\n if (!assoc) {\n break;\n }\n finalModel = assoc.target;\n }\n\n // Check if attributePath is a single attribute (not nested)\n const attributeSegments = attributePath.split('.');\n if (attributeSegments.length !== 1 || !finalModel.getAttributes()[attributePath]) {\n continue;\n }\n\n logger.debug(`Auto-detected reference join for condition '${fieldPath}'`, {\n model: model.name,\n referencePath: referencePath.join('.'),\n attributePath,\n associationName: includeResult.associationName\n });\n\n return {\n include: includeResult.include,\n attributePath,\n associationName: includeResult.associationName\n };\n }\n\n return null;\n};\n\n/**\n * Adds an include to options if it doesn't already exist.\n * Handles nested includes by merging them properly.\n */\nconst addIncludeIfNotExists = (options: any, newInclude: any): void => {\n options.include = options.include || [];\n\n // Check if this include already exists (by model and alias)\n const exists = options.include.some((inc: any) => {\n if (typeof inc === 'string') {\n return inc === newInclude.as;\n }\n if (inc.model === newInclude.model && inc.as === newInclude.as) {\n // If it exists and has nested includes, merge them\n if (newInclude.include && inc.include) {\n newInclude.include.forEach((nested: any) => {\n const nestedExists = inc.include.some((existingNested: any) =>\n existingNested.model === nested.model && existingNested.as === nested.as\n );\n if (!nestedExists) {\n inc.include.push(nested);\n }\n });\n } else if (newInclude.include) {\n inc.include = newInclude.include;\n }\n return true;\n }\n return false;\n });\n\n if (!exists) {\n options.include.push(newInclude);\n }\n};\n\nconst addAssociationCondition = (\n conditions: Record<string, any>,\n condition: Condition,\n model: ModelStatic<any>,\n options?: any,\n references?: SequelizeReferenceDefinition[],\n allReferences?: Map<string, SequelizeReferenceDefinition[]>,\n registry?: Registry\n): Record<string, any> => {\n const fieldPath = condition.column;\n const pathSegments = fieldPath.split('.');\n\n // First, try to detect if this matches a reference property\n logger.debug(`[addAssociationCondition] Processing condition '${fieldPath}'`, {\n model: model.name,\n hasReferences: !!references,\n referencesCount: references?.length || 0,\n pathSegmentsLength: pathSegments.length,\n pathSegments,\n willAttemptDetection: !!(references && pathSegments.length >= 2)\n });\n\n if (references && pathSegments.length >= 2) {\n logger.debug(`[addAssociationCondition] Attempting reference join detection for '${fieldPath}'`, {\n model: model.name,\n referencesCount: references.length,\n references: references.map(r => ({ property: r.property, column: r.column })),\n pathSegments,\n hasOptions: !!options\n });\n const referenceJoin = detectReferenceJoin(fieldPath, model, references, allReferences, registry);\n\n if (!referenceJoin) {\n logger.debug(`[addAssociationCondition] Reference join detection returned null for '${fieldPath}'`, {\n model: model.name,\n fieldPath\n });\n }\n\n if (referenceJoin && options) {\n logger.debug(`[addAssociationCondition] Reference join detected successfully for '${fieldPath}'`, {\n model: model.name,\n associationName: referenceJoin.associationName,\n attributePath: referenceJoin.attributePath\n });\n // Add the include to options\n addIncludeIfNotExists(options, referenceJoin.include);\n\n // Build the Sequelize association column syntax\n // For nested paths like \"step.phase.code\", we need \"$step.phase.code$\"\n // The referenceJoin.attributePath already contains just the final attribute name (e.g., \"code\")\n const attributeName = referenceJoin.attributePath;\n // Build the full association path (everything except the final attribute)\n const associationPath = fieldPath.substring(0, fieldPath.length - attributeName.length - 1);\n const sequelizeAssociationColumn = `$${associationPath}.${attributeName}$`;\n\n // Verify the attribute exists on the target model\n // Traverse the association path to get to the final model\n const finalPathSegments = associationPath.split('.');\n let currentModel = model;\n let targetModel = model;\n\n for (const segment of finalPathSegments) {\n const assoc = currentModel.associations?.[segment];\n if (!assoc) {\n throw new Error(`Association ${segment} not found on model ${currentModel.name}`);\n }\n targetModel = assoc.target;\n currentModel = targetModel;\n }\n\n if (!targetModel.getAttributes()[attributeName]) {\n throw new Error(`Attribute ${attributeName} not found on associated model ${targetModel.name} for path ${associationPath}`);\n }\n\n // Handle null values with proper SQL IS NULL / IS NOT NULL syntax\n if (condition.value === null) {\n if (condition.operator === '==' || !condition.operator) {\n logger.trace(`[QueryBuilder] Setting reference condition: ${sequelizeAssociationColumn} IS NULL`);\n conditions[sequelizeAssociationColumn] = {\n [Op.is]: null\n };\n } else if (condition.operator === '!=') {\n logger.trace(`[QueryBuilder] Setting reference condition: ${sequelizeAssociationColumn} IS NOT NULL`);\n conditions[sequelizeAssociationColumn] = {\n [Op.not]: null\n };\n } else {\n logger.error(`Operator ${condition.operator} cannot be used with null value on reference`, { condition });\n throw new Error(`Operator ${condition.operator} cannot be used with null value. Use '==' for IS NULL or '!=' for IS NOT NULL.`);\n }\n return conditions;\n }\n\n const conditionOp = getSequelizeOperator(condition.operator);\n logger.trace(`[QueryBuilder] Setting reference condition: ${sequelizeAssociationColumn} = ${stringifyJSON(condition.value)} (type: ${typeof condition.value})`);\n conditions[sequelizeAssociationColumn] = {\n [conditionOp]: condition.value\n };\n\n return conditions;\n }\n }\n\n // Fall back to original behavior: check for direct Sequelize association\n const [associationName, attributeName] = fieldPath.split('.', 2);\n\n // Check if the association exists on the model\n if (!model.associations || !model.associations[associationName]) {\n throw new Error(`Association ${associationName} not found on model ${model.name}`);\n }\n\n const association: Association<any, any> = model.associations[associationName];\n const associatedModel = association.target;\n\n // Check if the attribute exists on the associated model\n if (!associatedModel.getAttributes()[attributeName]) {\n throw new Error(`Attribute ${attributeName} not found on associated model ${associatedModel.name} for association ${associationName}`);\n }\n\n // Use Sequelize's $association.attribute$ syntax for querying associated models\n const sequelizeAssociationColumn = `$${associationName}.${attributeName}$`;\n\n // Handle null values with proper SQL IS NULL / IS NOT NULL syntax\n if (condition.value === null) {\n if (condition.operator === '==' || !condition.operator) {\n // Use Op.is for IS NULL\n logger.trace(`[QueryBuilder] Setting association condition: ${sequelizeAssociationColumn} IS NULL`);\n conditions[sequelizeAssociationColumn] = {\n [Op.is]: null\n };\n } else if (condition.operator === '!=') {\n // Use Op.not for IS NOT NULL\n logger.trace(`[QueryBuilder] Setting association condition: ${sequelizeAssociationColumn} IS NOT NULL`);\n conditions[sequelizeAssociationColumn] = {\n [Op.not]: null\n };\n } else {\n logger.error(`Operator ${condition.operator} cannot be used with null value on association`, { condition });\n throw new Error(`Operator ${condition.operator} cannot be used with null value. Use '==' for IS NULL or '!=' for IS NOT NULL.`);\n }\n return conditions;\n }\n\n const conditionOp = getSequelizeOperator(condition.operator);\n\n logger.trace(`[QueryBuilder] Setting association condition: ${sequelizeAssociationColumn} = ${stringifyJSON(condition.value)} (type: ${typeof condition.value})`);\n conditions[sequelizeAssociationColumn] = {\n [conditionOp]: condition.value\n };\n\n return conditions;\n};\n\nconst addAttributeCondition = (\n conditions: Record<string, any>,\n condition: Condition,\n model: ModelStatic<any>\n): Record<string, any> => {\n const conditionColumn = condition.column;\n\n if (!model.getAttributes()[conditionColumn]) {\n throw new Error(`Condition column ${conditionColumn} not found on model ${model.name}`);\n }\n\n // Handle null values with proper SQL IS NULL / IS NOT NULL syntax\n if (condition.value === null) {\n if (condition.operator === '==' || !condition.operator) {\n // Use Op.is for IS NULL\n logger.trace(`[QueryBuilder] Setting attribute condition: ${conditionColumn} IS NULL`);\n conditions[conditionColumn] = {\n [Op.is]: null\n };\n } else if (condition.operator === '!=') {\n // Use Op.not for IS NOT NULL\n logger.trace(`[QueryBuilder] Setting attribute condition: ${conditionColumn} IS NOT NULL`);\n conditions[conditionColumn] = {\n [Op.not]: null\n };\n } else {\n logger.error(`Operator ${condition.operator} cannot be used with null value`, { condition });\n throw new Error(`Operator ${condition.operator} cannot be used with null value. Use '==' for IS NULL or '!=' for IS NOT NULL.`);\n }\n return conditions;\n }\n\n const conditionOp = getSequelizeOperator(condition.operator);\n\n logger.trace(`[QueryBuilder] Setting attribute condition: ${conditionColumn} = ${stringifyJSON(condition.value)} (type: ${typeof condition.value})`);\n conditions[conditionColumn] = {\n [conditionOp]: condition.value\n };\n\n return conditions;\n};\n\nexport const addCondition = (\n conditions: Record<string, any>,\n condition: Condition,\n model: ModelStatic<any>,\n options?: any,\n references?: SequelizeReferenceDefinition[],\n allReferences?: Map<string, SequelizeReferenceDefinition[]>,\n registry?: Registry\n) => {\n const conditionColumn: string = condition.column;\n\n // Check if this is an association query (contains a dot)\n if (conditionColumn.includes('.')) {\n return addAssociationCondition(conditions, condition, model, options, references, allReferences, registry);\n }\n\n // Handle regular column queries\n return addAttributeCondition(conditions, condition, model);\n}\n\nconst collectAssociationsFromConditions = (conditions: any): Set<string> => {\n const associations = new Set<string>();\n\n const processObject = (obj: any) => {\n if (typeof obj === 'object' && obj !== null) {\n // Check string keys\n Object.keys(obj).forEach(key => {\n // Check if this is an association reference ($association.attribute$)\n if (typeof key === 'string' && key.startsWith('$') && key.endsWith('$') && key.includes('.')) {\n const associationName = key.substring(1, key.indexOf('.'));\n associations.add(associationName);\n }\n\n // Recursively process nested objects\n if (typeof obj[key] === 'object') {\n processObject(obj[key]);\n }\n });\n\n // Also check Symbol keys (for compound conditions like Op.and, Op.or)\n Object.getOwnPropertySymbols(obj).forEach(symbol => {\n if (typeof obj[symbol] === 'object') {\n processObject(obj[symbol]);\n }\n });\n }\n\n // Handle arrays (for compound conditions that might be arrays)\n if (Array.isArray(obj)) {\n obj.forEach(item => {\n if (typeof item === 'object') {\n processObject(item);\n }\n });\n }\n };\n\n processObject(conditions);\n return associations;\n};\n\nconst addAssociationIncludes = (options: any, model: ModelStatic<any>): any => {\n // Collect all association names used in conditions\n const referencedAssociations = collectAssociationsFromConditions(options.where);\n\n if (referencedAssociations.size > 0) {\n options.include = options.include || [];\n\n // Add each referenced association to the include array\n referencedAssociations.forEach(associationName => {\n // Check if this association is already included\n const alreadyIncluded = options.include.some((inc: any) =>\n (typeof inc === 'string' && inc === associationName) ||\n (typeof inc === 'object' && inc.association === associationName)\n );\n\n if (!alreadyIncluded && model.associations && model.associations[associationName]) {\n options.include.push({\n model: model.associations[associationName].target,\n as: associationName,\n required: false // Use LEFT JOIN so records without associations are still returned\n });\n }\n });\n }\n\n return options;\n};\n\n/**\n * Detects references that can be loaded via Sequelize INCLUDE and adds them to options.\n * This prevents N+1 queries by using JOIN instead of separate queries per item.\n *\n * @param options - Query options to modify\n * @param model - Sequelize model to check for associations\n * @param referenceDefinitions - Reference definitions from library config\n * @returns Modified options with includes added, plus array of property names that were included\n */\nexport const addReferenceIncludes = (\n options: any,\n model: ModelStatic<any>,\n referenceDefinitions: SequelizeReferenceDefinition[]\n): { options: any; includedReferences: string[] } => {\n if (!referenceDefinitions || referenceDefinitions.length === 0) {\n return { options, includedReferences: [] };\n }\n\n const includedReferences: string[] = [];\n options.include = options.include || [];\n\n for (const refDef of referenceDefinitions) {\n // Check if the model has an association matching the reference property\n const association = model.associations && model.associations[refDef.property];\n\n if (association) {\n // Check if this association is already included\n const alreadyIncluded = options.include.some((inc: any) =>\n (typeof inc === 'string' && inc === refDef.property) ||\n (typeof inc === 'object' && inc.as === refDef.property)\n );\n\n if (!alreadyIncluded) {\n logger.default(`Auto-detected association for reference '${refDef.property}' - using INCLUDE to prevent N+1`, {\n property: refDef.property,\n associationType: association.associationType,\n targetModel: association.target.name\n });\n\n // Add the association to includes\n options.include.push({\n model: association.target,\n as: refDef.property,\n required: false // Use LEFT JOIN to preserve items without references\n });\n\n includedReferences.push(refDef.property);\n } else {\n logger.debug(`Association '${refDef.property}' already included in query`, {\n property: refDef.property\n });\n includedReferences.push(refDef.property);\n }\n } else {\n logger.debug(`No association found for reference '${refDef.property}' - will use separate query`, {\n property: refDef.property,\n availableAssociations: Object.keys(model.associations || {})\n });\n }\n }\n\n return { options, includedReferences };\n};\n\n/**\n * Detects aggregations that can be loaded via Sequelize INCLUDE and adds them to options.\n * This prevents N+1 queries by using JOIN instead of separate queries per item.\n *\n * @param options - Query options to modify\n * @param model - Sequelize model to check for associations\n * @param aggregationDefinitions - Aggregation definitions from library config\n * @returns Modified options with includes added, plus array of property names that were included\n */\nexport const addAggregationIncludes = (\n options: any,\n model: ModelStatic<any>,\n aggregationDefinitions: any[]\n): { options: any; includedAggregations: string[] } => {\n if (!aggregationDefinitions || aggregationDefinitions.length === 0) {\n return { options, includedAggregations: [] };\n }\n\n const includedAggregations: string[] = [];\n options.include = options.include || [];\n\n for (const aggDef of aggregationDefinitions) {\n // Check if the model has an association matching the aggregation property\n const association = model.associations && model.associations[aggDef.property];\n\n if (association) {\n // Check if this association is already included\n const alreadyIncluded = options.include.some((inc: any) =>\n (typeof inc === 'string' && inc === aggDef.property) ||\n (typeof inc === 'object' && inc.as === aggDef.property)\n );\n\n if (!alreadyIncluded) {\n logger.default(`Auto-detected association for aggregation '${aggDef.property}' - using INCLUDE to prevent N+1`, {\n property: aggDef.property,\n associationType: association.associationType,\n targetModel: association.target.name\n });\n\n // Add the association to includes\n options.include.push({\n model: association.target,\n as: aggDef.property,\n required: false // Use LEFT JOIN to preserve items without aggregations\n });\n\n includedAggregations.push(aggDef.property);\n } else {\n logger.debug(`Association '${aggDef.property}' already included in query`, {\n property: aggDef.property\n });\n includedAggregations.push(aggDef.property);\n }\n } else {\n logger.debug(`No association found for aggregation '${aggDef.property}' - will use separate query`, {\n property: aggDef.property,\n availableAssociations: Object.keys(model.associations || {})\n });\n }\n }\n\n return { options, includedAggregations };\n};\n\nexport const buildQuery = (\n itemQuery: ItemQuery,\n model: ModelStatic<any>,\n references?: SequelizeReferenceDefinition[],\n registry?: Registry\n): any => {\n logger.default(`QueryBuilder build called with itemQuery: ${stringifyJSON(itemQuery)}`);\n logger.debug(`[buildQuery] Parameters:`, {\n modelName: model.name,\n referencesCount: references?.length || 0,\n references: references?.map(r => ({ property: r.property, column: r.column })) || [],\n hasRegistry: !!registry,\n hasCompoundCondition: !!itemQuery.compoundCondition\n });\n\n let options: any = {\n where: {},\n };\n\n // Build a map of references by model name for nested reference lookups\n // This is a simplified approach - in a real scenario, we'd need to resolve\n // model names from the registry, but for now we'll use the references array\n const allReferences = new Map<string, SequelizeReferenceDefinition[]>();\n if (references) {\n // For now, we'll store references under the current model name\n // In a full implementation, we'd need to resolve model names from the registry\n allReferences.set(model.name, references);\n }\n\n if (itemQuery.compoundCondition) {\n logger.default(`QueryBuilder adding conditions: ${stringifyJSON(itemQuery.compoundCondition)}`);\n options = addCompoundCondition(options, itemQuery.compoundCondition, model, references, allReferences, registry);\n }\n\n // If the model has a deletedAt column, we need to add a delete query\n if (model.getAttributes().deletedAt || model.getAttributes().isDeleted) {\n options = addDeleteQuery(options, model);\n }\n\n if (itemQuery.refs) {\n options = addReferenceQueries(options, itemQuery.refs, model);\n }\n if (itemQuery.events) {\n options = addEventQueries(options, itemQuery.events, model);\n }\n\n // TODO: Once we start to support Aggs on the server-side, we'll need to parse agg queries\n\n // Apply a limit to the result set\n if (itemQuery.limit) {\n logger.default(`QueryBuilder applying limit: ${itemQuery.limit}`);\n options.limit = itemQuery.limit;\n }\n\n // Apply an offset to the result set\n if (itemQuery.offset) {\n options.offset = itemQuery.offset;\n }\n\n // Add orderBy to the query\n if (itemQuery.orderBy) {\n itemQuery.orderBy.forEach((orderBy: OrderBy) => {\n if (!model.getAttributes()[orderBy.field]) {\n throw new Error(`Order by field ${orderBy.field} not found on model ${model.name}`);\n }\n options.order = [\n [orderBy.field, orderBy.direction]\n ];\n });\n }\n\n // Add includes for any associations referenced in conditions\n // This will pick up includes added by reference detection as well as direct association references\n options = addAssociationIncludes(options, model);\n\n return options;\n}\n", "\n/* eslint-disable */\nexport const clean = (obj: any) => {\n return Object.fromEntries(\n Object.entries(obj).filter(([_, v]) => v !== undefined)\n );\n}\n\n//Recursive implementation of jSON.stringify;\nexport const stringifyJSON = function (obj: any, visited: Set<any> = new Set()): string {\n const arrOfKeyVals: string[] = [];\n const arrVals: string[] = [];\n let objKeys: string[] = [];\n\n /*********CHECK FOR PRIMITIVE TYPES**********/\n if (typeof obj === 'number' || typeof obj === 'boolean' || obj === null)\n return '' + obj;\n else if (typeof obj === 'string')\n return '\"' + obj + '\"';\n\n /*********DETECT CIRCULAR REFERENCES**********/\n if (obj instanceof Object && visited.has(obj)) {\n return '\"(circular)\"';\n }\n\n /*********CHECK FOR ARRAY**********/\n else if (Array.isArray(obj)) {\n //check for empty array\n if (obj.length === 0)\n return '[]';\n else {\n // Add array to visited before processing its elements\n visited.add(obj);\n obj.forEach(function (el) {\n arrVals.push(stringifyJSON(el, visited));\n });\n // Remove from visited after processing to allow arrays at different levels\n visited.delete(obj);\n return '[' + arrVals + ']';\n }\n }\n /*********CHECK FOR OBJECT**********/\n else if (obj instanceof Object) {\n // Add object to visited before processing its properties\n visited.add(obj);\n //get object keys\n objKeys = Object.keys(obj);\n //set key output;\n objKeys.forEach(function (key) {\n const keyOut = '\"' + key + '\":';\n const keyValOut = obj[key];\n //skip functions and undefined properties\n if (keyValOut instanceof Function || keyValOut === undefined)\n return; // Skip this entry entirely instead of pushing an empty string\n else if (typeof keyValOut === 'string')\n arrOfKeyVals.push(keyOut + '\"' + keyValOut + '\"');\n else if (typeof keyValOut === 'boolean' || typeof keyValOut === 'number' || keyValOut === null)\n arrOfKeyVals.push(keyOut + keyValOut);\n //check for nested objects, call recursively until no more objects\n else if (keyValOut instanceof Object) {\n arrOfKeyVals.push(keyOut + stringifyJSON(keyValOut, visited));\n }\n });\n // Remove from visited after processing to allow objects at different levels\n visited.delete(obj);\n return '{' + arrOfKeyVals + '}';\n }\n return '';\n};\n", "/* eslint-disable indent */\nimport { ModelStatic } from 'sequelize';\n\nexport interface RelationshipChainResult {\n success: boolean;\n path?: string;\n includes?: any[];\n}\n\nexport interface RelationshipPathResult {\n found: boolean;\n path?: string;\n includes?: any[];\n isDirect?: boolean;\n}\n\n/**\n * Helper function to build relationship chain includes\n */\nexport const buildRelationshipChain = (\n targetModel: ModelStatic<any>,\n kta: string[],\n currentIndex: number,\n targetIndex: number\n): RelationshipChainResult => {\n // Build the association path and validate relationships exist\n const associationParts: string[] = [];\n const modelChain: ModelStatic<any>[] = [targetModel];\n let currentModel = targetModel;\n\n // Validate that all associations exist and build model chain\n for (let i = currentIndex + 1; i <= targetIndex; i++) {\n const intermediateType = kta[i];\n const associationName = intermediateType;\n\n if (!currentModel.associations || !currentModel.associations[associationName]) {\n return { success: false };\n }\n\n associationParts.push(associationName);\n currentModel = currentModel.associations[associationName].target;\n modelChain.push(currentModel);\n }\n\n // Build the full association path for the target field\n const targetPrimaryKey = currentModel.primaryKeyAttribute || 'id';\n const associationPath = `$${associationParts.join('.')}.${targetPrimaryKey}$`;\n\n // Build nested includes structure iteratively (clearer than recursion)\n let deepestInclude: any = null;\n\n // Build from the deepest level back to the root\n for (let i = targetIndex; i > currentIndex; i--) {\n const currentType = kta[i];\n const modelIndex = i - currentIndex;\n\n const includeObj: any = {\n model: modelChain[modelIndex],\n as: currentType,\n required: true\n };\n\n if (deepestInclude) {\n includeObj.include = [deepestInclude];\n }\n\n deepestInclude = includeObj;\n }\n\n const includes = deepestInclude ? [deepestInclude] : [];\n\n return { success: true, path: associationPath, includes };\n};\n\n/**\n * Helper function to build relationship path for a locator\n * @param includeIsDirect Whether to include the isDirect flag in the result\n */\nexport const buildRelationshipPath = (\n targetModel: ModelStatic<any>,\n locatorType: string,\n kta: string[],\n includeIsDirect: boolean = false\n): RelationshipPathResult => {\n\n // First check if the field exists directly\n const directFieldName = `${locatorType}Id`;\n const attributes = targetModel.getAttributes();\n if (attributes && attributes[directFieldName]) {\n const result: RelationshipPathResult = { found: true };\n if (includeIsDirect) {\n result.isDirect = true;\n }\n return result;\n }\n\n // If not direct, look for relationship path\n const targetIndex = kta.indexOf(locatorType);\n if (targetIndex === -1) {\n const result: RelationshipPathResult = { found: false };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n }\n\n const currentIndex = 0; // We're always looking from the base model\n\n if (targetIndex <= currentIndex) {\n const result: RelationshipPathResult = { found: false };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n }\n\n const chainResult = buildRelationshipChain(targetModel, kta, currentIndex, targetIndex);\n if (chainResult.success) {\n const result: RelationshipPathResult = {\n found: true,\n path: chainResult.path,\n includes: chainResult.includes\n };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n }\n\n const result: RelationshipPathResult = { found: false };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n};\n", "/* eslint-disable max-len */\n/* eslint-disable indent */\nimport {\n AllItemTypeArrays,\n Item,\n} from '@fjell/core';\n\nimport LibLogger from './logger';\nimport { Model, ModelStatic } from 'sequelize';\nimport { buildRelationshipPath } from './util/relationshipUtils';\n\nconst logger = LibLogger.get('sequelize', 'KeyMaster');\n\n// Helper function to extract location key value from item\nconst extractLocationKeyValue = (\n model: ModelStatic<any>,\n item: any,\n locatorType: string,\n kta: string[]\n): any => {\n logger.default('Extracting location key value', { locatorType, kta });\n\n const relationshipInfo = buildRelationshipPath(model, locatorType, kta, true);\n\n if (!relationshipInfo.found) {\n throw new Error(`Location key '${locatorType}' cannot be resolved on model '${model.name}' or through its relationships. Key type array: [${kta.join(', ')}]. Available associations: [${Object.keys(model.associations || {}).join(', ')}]`);\n }\n\n if (relationshipInfo.isDirect) {\n // Direct foreign key field\n const foreignKeyField = `${locatorType}Id`;\n const value = item[foreignKeyField];\n if (typeof value === 'undefined' || value === null) {\n throw new Error(`Direct foreign key field '${foreignKeyField}' is missing or null in item. Model: '${model.name}', Locator type: '${locatorType}', Available item properties: [${Object.keys(item || {}).join(', ')}]`);\n }\n return value;\n } else {\n // Need to traverse relationship hierarchy\n // Find the path through the key type array\n const locatorIndex = kta.indexOf(locatorType);\n if (locatorIndex === -1) {\n throw new Error(`Locator type '${locatorType}' not found in key type array. Model: '${model.name}', Key type array: [${kta.join(', ')}]`);\n }\n\n // Start from the current item (index 0 in kta)\n let currentObject = item;\n\n // Traverse through each intermediate relationship to reach the target\n for (let i = 1; i < locatorIndex; i++) {\n const intermediateType = kta[i];\n\n // Check if the intermediate relationship object is loaded\n if (currentObject[intermediateType] && typeof currentObject[intermediateType] === 'object') {\n currentObject = currentObject[intermediateType];\n } else {\n // Try the foreign key approach if the relationship object isn't loaded\n const foreignKeyField = `${intermediateType}Id`;\n if (typeof currentObject[foreignKeyField] !== 'undefined' && currentObject[foreignKeyField] !== null) {\n // We have the foreign key but not the loaded object, we can't traverse further\n throw new Error(`Intermediate relationship '${intermediateType}' is not loaded. Cannot traverse to '${locatorType}'. Model: '${model.name}', Available item properties: [${Object.keys(currentObject || {}).join(', ')}]. Either include the relationship in your query or ensure it's loaded.`);\n }\n throw new Error(`Intermediate relationship '${intermediateType}' is missing in the relationship chain. Model: '${model.name}', Expected path: ${kta.slice(0, locatorIndex + 1).join(' \u2192 ')}, Available item properties: [${Object.keys(currentObject || {}).join(', ')}]`);\n }\n }\n\n // Now extract the target locator value from the current object\n // First try to get it from the loaded relationship object\n if (currentObject[locatorType] && typeof currentObject[locatorType] === 'object' && typeof currentObject[locatorType].id !== 'undefined') {\n return currentObject[locatorType].id;\n }\n\n // If the relationship object isn't loaded, try the foreign key field\n const foreignKeyField = `${locatorType}Id`;\n if (typeof currentObject[foreignKeyField] !== 'undefined' && currentObject[foreignKeyField] !== null) {\n return currentObject[foreignKeyField];\n }\n\n const traversalPath = kta.slice(0, locatorIndex + 1).join(' \u2192 ');\n throw new Error(\n `Unable to extract location key for '${locatorType}'. ` +\n `Neither the relationship object nor direct foreign key is available. ` +\n `Traversal path: ${traversalPath}`\n );\n }\n};\n\nexport const removeKey = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Removing Key', { item });\n delete item.key;\n return item;\n}\n\n// export const populateKey = <\n// S extends string,\n// L1 extends string = never,\n// L2 extends string = never,\n// L3 extends string = never,\n// L4 extends string = never,\n// L5 extends string = never\n// >(\n// item: ItemProperties<S, L1, L2, L3, L4, L5>,\n// keyTypes: AllItemTypeArrays<S, L1, L2, L3, L4, L5>\n// ): ItemProperties<S, L1, L2, L3, L4, L5> => {\n// if (keyTypes.length === 1) {\n// item.key = { kt: keyTypes[0], pk: item.id };\n// delete item.id;\n// } else if (keyTypes.length === 2) {\n// item.key = {\n// kt: keyTypes[0], pk: item.id,\n// // TODO: Shouldn't this be inspecting the model to get the primary key type?\n// loc: [{ kt: keyTypes[1], lk: item[keyTypes[1] + 'Id'] }],\n// };\n// delete item.id;\n// delete item[keyTypes[1] + 'Id'];\n// } else {\n// throw new Error('Not implemented');\n// }\n// return item;\n// }\n\nexport const addKey = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n model: Model<any, any>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n keyTypes: AllItemTypeArrays<S, L1, L2, L3, L4, L5>\n): Item<S, L1, L2, L3, L4, L5> => {\n logger.default('Adding Key', { item });\n const key = {};\n const modelClass = model.constructor as ModelStatic<any>;\n const primaryKeyAttr = modelClass.primaryKeyAttribute;\n\n if (Array.isArray(keyTypes) && keyTypes.length > 1) {\n const type = [...keyTypes];\n const pkType = type.shift();\n Object.assign(key, { kt: pkType, pk: item[primaryKeyAttr] });\n\n // Build location keys for composite key\n const locationKeys = [];\n for (const locatorType of type) {\n try {\n const lk = extractLocationKeyValue(modelClass, item, locatorType, keyTypes as string[]);\n locationKeys.push({ kt: locatorType, lk });\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(`Failed to extract location key for '${locatorType}'`, { error: errorMessage, item, keyTypes });\n throw error;\n }\n }\n\n Object.assign(key, { loc: locationKeys });\n } else {\n Object.assign(key, { kt: keyTypes[0], pk: item[primaryKeyAttr] });\n }\n Object.assign(item, { key });\n return item as Item<S, L1, L2, L3, L4, L5>;\n};\n", "/* eslint-disable indent */\n\nimport { AllItemTypeArrays, Item } from \"@fjell/core\";\nimport { Model } from \"sequelize\";\n\nimport LibLogger from \"./logger\";\nimport { addKey } from \"./KeyMaster\";\nimport { AggregationDefinition, SequelizeReferenceDefinition } from \"./Options\";\nimport * as Library from \"@fjell/lib\";\nimport {\n buildAggregation,\n contextManager,\n createOperationContext,\n OperationContext\n} from \"@fjell/lib\";\nimport { stringifyJSON } from \"./util/general\";\nimport { populateEvents } from \"./EventCoordinator\";\nimport { buildSequelizeReference } from \"./processing/ReferenceBuilder\";\nimport { addRefsToSequelizeItem } from \"./processing/RefsAdapter\";\nimport { addAggsToItem } from \"./processing/AggsAdapter\";\n\nconst logger = LibLogger.get('sequelize', 'RowProcessor');\n\n// Re-export types and functions from @fjell/lib for backwards compatibility\nexport type { OperationContext };\nexport { createOperationContext, contextManager };\n\nexport const processRow = async <S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never>(\n row: Model<any, any>,\n keyTypes: AllItemTypeArrays<S, L1, L2, L3, L4, L5>,\n referenceDefinitions: SequelizeReferenceDefinition[],\n aggregationDefinitions: AggregationDefinition[],\n registry: Library.Registry,\n context?: OperationContext,\n includedAggregations?: string[],\n includedReferences?: string[]\n // eslint-disable-next-line max-params\n ): Promise<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Processing Row', { row });\n\n // Use provided context or create new one\n const operationContext = context || createOperationContext();\n\n // Process the row within the context to ensure all operations share the same context\n return contextManager.withContext(operationContext, async () => {\n let item = row.get({ plain: true }) as any;\n logger.default('Adding Key to Item with Key Types: %s', stringifyJSON(keyTypes));\n item = addKey(row, item, keyTypes);\n item = populateEvents(item);\n logger.default('Key Added to Item: %s', stringifyJSON(item.key));\n\n // Mark this item as in progress to detect circular references\n operationContext.markInProgress(item.key);\n\n try {\n if (referenceDefinitions && referenceDefinitions.length > 0) {\n // Process all references in parallel for better performance\n // Each reference reads from a different column and writes to a different property,\n // so they can safely run in parallel without race conditions\n const referenceStartTime = typeof performance !== 'undefined' ? performance.now() : Date.now();\n const referencePromises = referenceDefinitions.map(async (referenceDefinition) => {\n // Check if this reference was already loaded via INCLUDE (N+1 prevention)\n const alreadyLoaded = includedReferences &&\n includedReferences.includes(referenceDefinition.property) &&\n typeof item[referenceDefinition.property] !== 'undefined';\n\n if (alreadyLoaded) {\n logger.default(\n `Skipping buildSequelizeReference for '${referenceDefinition.property}' - already loaded via INCLUDE (N+1 prevention)`,\n {\n property: referenceDefinition.property,\n itemType: item.key.kt,\n hasData: item[referenceDefinition.property] ? 'loaded' : 'undefined'\n }\n );\n // Data is already on the item, RefsAdapter will move it to refs structure\n return item;\n } else {\n logger.default('Processing Reference for %s to %s', item.key.kt, stringifyJSON(referenceDefinition.kta));\n // buildSequelizeReference modifies item in place, but each modifies a different property\n // so parallel execution is safe\n return buildSequelizeReference(item, referenceDefinition, registry, operationContext);\n }\n });\n\n // Wait for all references to load in parallel\n await Promise.all(referencePromises);\n\n const referenceDuration = (typeof performance !== 'undefined' ? performance.now() : Date.now()) - referenceStartTime;\n if (referenceDuration > 100) {\n logger.debug(`\u23F1\uFE0F REFERENCE_BUILDER_PERF: Loaded ${referenceDefinitions.length} references in parallel for ${item.key.kt} - ${referenceDuration.toFixed(2)}ms`);\n }\n }\n if (aggregationDefinitions && aggregationDefinitions.length > 0) {\n for (const aggregationDefinition of aggregationDefinitions) {\n // Check if this aggregation was already loaded via INCLUDE (Option C optimization)\n const alreadyLoaded = includedAggregations &&\n includedAggregations.includes(aggregationDefinition.property) &&\n typeof item[aggregationDefinition.property] !== 'undefined';\n\n if (alreadyLoaded) {\n logger.default(\n `Skipping buildAggregation for '${aggregationDefinition.property}' - already loaded via INCLUDE (N+1 prevention)`,\n {\n property: aggregationDefinition.property,\n itemType: item.key.kt,\n hasData: Array.isArray(item[aggregationDefinition.property])\n ? `${item[aggregationDefinition.property].length} items`\n : 'single item'\n }\n );\n // Data is already on the item, AggsAdapter will move it to aggs structure\n } else {\n logger.default('Processing Aggregation for %s from %s', item.key.kt, stringifyJSON(aggregationDefinition.kta));\n item = await buildAggregation(item, aggregationDefinition, registry, operationContext);\n }\n }\n }\n\n // Cache the fully processed item\n operationContext.setCached(item.key, item);\n } finally {\n // Mark this item as complete\n operationContext.markComplete(item.key);\n }\n\n // Automatically add refs structure before returning (transparent wrapper)\n // This ensures items leaving the Sequelize library always have Firestore-style refs structure\n if (referenceDefinitions && referenceDefinitions.length > 0) {\n item = addRefsToSequelizeItem(item, referenceDefinitions);\n logger.default('Added refs structure to item (transparent wrapper)', { key: item.key });\n }\n\n // Automatically add aggs structure before returning (transparent wrapper)\n // This ensures items leaving the Sequelize library always have unified aggs structure\n if (aggregationDefinitions && aggregationDefinitions.length > 0) {\n item = addAggsToItem(item, aggregationDefinitions);\n logger.default('Added aggs structure to item (transparent wrapper)', { key: item.key });\n }\n\n logger.default('Processed Row: %j', stringifyJSON(item));\n return item as Item<S, L1, L2, L3, L4, L5>;\n });\n};\n", "import {\n Evented,\n Item,\n ManagedEvents\n} from '@fjell/core';\nimport deepmerge from 'deepmerge';\n\nimport LibLogger from './logger';\n\nconst logger = LibLogger.get(\"sequelize\", \"EventCoordinator\");\n\nexport const createEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>):\n Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Creating Events', { item });\n const currentDate = new Date();\n\n let events = item.events;\n\n if (events) {\n if (!events.created) {\n events = deepmerge(events, { created: { at: currentDate } });\n }\n if (!events.updated) {\n events = deepmerge(events, { updated: { at: currentDate } });\n }\n if (!events.deleted) {\n events = deepmerge(events, { deleted: { at: null } });\n }\n\n } else {\n events = {\n created: { at: currentDate },\n updated: { at: currentDate },\n deleted: { at: null },\n };\n }\n\n return deepmerge(item, { events }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n}\n\nexport const updateEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>):\n Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Updating Events', { item });\n const currentDate = new Date();\n const events: Evented = {\n updated: { at: currentDate },\n };\n\n // TODO: This is clean-up code, we should remove it\n // If the event lacks a created data, let's just insert it here...\n if (!item.events || !item.events.created || !item.events.created.at) {\n events.created = { at: currentDate };\n }\n\n return deepmerge(item, { events }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n}\n//#endregion\n\nexport const populateEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n const events: ManagedEvents = {\n created: { at: item.createdAt || null },\n updated: { at: item.updatedAt || null },\n deleted: { at: null }\n };\n item.events = events;\n return item;\n}\n\nexport const extractEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Extracting Events to database fields', { item });\n\n if (item.events) {\n if (item.events.created?.at) {\n item.createdAt = item.events.created.at;\n }\n if (item.events.updated?.at) {\n item.updatedAt = item.events.updated.at;\n }\n if (item.events.deleted?.at) {\n item.deletedAt = item.events.deleted.at;\n }\n }\n\n return item;\n}\n\nexport const removeEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Removing Events', { item });\n delete item.events;\n return item;\n}\n", "import { ComKey, Item, PriKey } from \"@fjell/core\";\nimport type { Registry } from \"@fjell/lib\";\nimport { OperationContext } from \"@fjell/lib\";\nimport logger from \"../logger\";\n\n/**\n * Sequelize-specific definition for a reference relationship.\n * References in Sequelize are stored as foreign key columns (e.g., \"authorId\")\n * and populated into properties on the item.\n */\nexport interface SequelizeReferenceDefinition {\n /** Column name containing the foreign key value (e.g., \"authorId\") */\n column: string;\n /** Key type array of the referenced item */\n kta: string[];\n /** Property name to populate with the referenced item (e.g., \"author\") */\n property: string;\n /**\n * Optional: Column names for location keys when referencing composite items.\n * If provided, will construct a full ComKey with location context.\n * If omitted for composite items, uses empty loc array to search across all locations.\n *\n * Example: ['phaseId'] for a step reference where you have both stepId and phaseId columns\n */\n locationColumns?: string[];\n}\n\n/**\n * Build a reference by looking up a related item by its key from a column value.\n * The referenced item will be populated directly into a property on the item.\n *\n * @param item - The item to populate with reference data\n * @param referenceDefinition - Sequelize-specific definition of what to reference\n * @param registry - Registry to look up library instances\n * @param context - Optional operation context for caching and cycle detection\n * @returns The item with the reference property populated\n */\nexport const buildSequelizeReference = async (\n item: any,\n referenceDefinition: SequelizeReferenceDefinition,\n registry: Registry,\n context?: OperationContext\n) => {\n const libLogger = logger.get('processing', 'ReferenceBuilder');\n\n // Check if this is a composite item reference (has location hierarchy)\n const isCompositeItem = referenceDefinition.kta.length > 1;\n const primaryKeyType = referenceDefinition.kta[0];\n\n if (isCompositeItem) {\n libLogger.debug(\n 'Detected composite item reference - will use ComKey with empty loc array',\n {\n kta: referenceDefinition.kta,\n primaryKeyType,\n property: referenceDefinition.property,\n column: referenceDefinition.column\n }\n );\n }\n\n // Check if dependencies exist\n if (!registry) {\n libLogger.error('Registry not provided for reference processing', {\n component: 'lib-sequelize',\n subcomponent: 'ReferenceBuilder',\n operation: 'buildSequelizeReference',\n property: referenceDefinition.property,\n kta: referenceDefinition.kta,\n column: referenceDefinition.column,\n suggestion: 'Ensure registry is passed to library configuration'\n });\n throw new Error(\n `This model definition has a reference definition, but the registry is not present. ` +\n `Reference property: '${referenceDefinition.property}', ` +\n `key types: [${referenceDefinition.kta.join(', ')}], column: '${referenceDefinition.column}'. ` +\n `Suggestion: Pass registry to library initialization.`\n );\n }\n\n // Find the Library.Instance for the key type\n const library: any = registry.get(referenceDefinition.kta as any);\n if (!library) {\n libLogger.error('Referenced library not found in registry', {\n component: 'lib-sequelize',\n subcomponent: 'ReferenceBuilder',\n operation: 'buildSequelizeReference',\n property: referenceDefinition.property,\n kta: referenceDefinition.kta,\n column: referenceDefinition.column,\n suggestion: `Register a library for [${referenceDefinition.kta.join(', ')}] in the registry`\n });\n throw new Error(\n `This model definition has a reference definition, but the dependency is not present in registry. ` +\n `Reference property: '${referenceDefinition.property}', ` +\n `missing key type: '${primaryKeyType}', column: '${referenceDefinition.column}'`\n );\n }\n\n // Check if the column value is null - if so, skip the reference\n const columnValue = item[referenceDefinition.column];\n if (columnValue == null) {\n item[referenceDefinition.property] = null;\n return item;\n }\n\n // Create the appropriate key type based on whether this is a composite item\n let itemKey: PriKey<string> | ComKey<string>;\n\n if (!isCompositeItem) {\n // Primary item: use PriKey\n itemKey = {\n kt: primaryKeyType,\n pk: columnValue\n };\n } else if (referenceDefinition.locationColumns && referenceDefinition.locationColumns.length > 0) {\n // Composite item with location columns provided: build full ComKey\n const locationTypes = referenceDefinition.kta.slice(1); // Skip primary key type\n const loc: Array<{kt: string, lk: any}> = [];\n let hasNullLocation = false;\n\n for (let i = 0; i < referenceDefinition.locationColumns.length; i++) {\n const columnName = referenceDefinition.locationColumns[i];\n const locValue = item[columnName];\n\n if (locValue == null) {\n libLogger.warning(\n `Location column '${columnName}' is null/undefined for reference '${referenceDefinition.property}'. ` +\n `Falling back to empty loc array search.`\n );\n // Fall back to empty loc array if any location column is missing\n hasNullLocation = true;\n break;\n }\n\n loc.push({\n kt: locationTypes[i],\n lk: locValue\n });\n }\n\n if (hasNullLocation) {\n // Fallback to empty loc array if any location column is missing\n itemKey = {\n kt: primaryKeyType,\n pk: columnValue,\n loc: []\n };\n } else {\n // Build full ComKey with location context\n itemKey = {\n kt: primaryKeyType,\n pk: columnValue,\n loc: loc as any\n };\n\n libLogger.debug('Built full ComKey with location context', {\n itemKey,\n locationColumns: referenceDefinition.locationColumns,\n property: referenceDefinition.property\n });\n }\n } else {\n // Composite item without location columns: use empty loc array\n // This signals \"find this item by primary key across all location contexts\"\n itemKey = {\n kt: primaryKeyType,\n pk: columnValue,\n loc: []\n };\n\n libLogger.default('Using empty loc array for composite item reference', {\n kta: referenceDefinition.kta,\n property: referenceDefinition.property\n });\n }\n\n libLogger.default('Created reference key', {\n itemKey,\n isCompositeItem,\n hasLocationColumns: !!referenceDefinition.locationColumns,\n property: referenceDefinition.property\n });\n\n let referencedItem;\n\n if (context) {\n // Check if we already have this item cached\n if (context.isCached(itemKey)) {\n libLogger.debug('Using cached reference', { itemKey, property: referenceDefinition.property });\n referencedItem = context.getCached(itemKey);\n }\n // Check if this item is currently being loaded (circular dependency)\n else if (context.isInProgress(itemKey)) {\n libLogger.default('Circular dependency detected, creating reference placeholder', {\n itemKey,\n property: referenceDefinition.property\n });\n\n // Create a minimal reference object with just the key to break the cycle\n referencedItem = {\n key: itemKey,\n // Add any other minimal properties that might be needed\n // This prevents infinite loops while still providing the key for identification\n };\n }\n else {\n // Mark this key as in progress before loading\n context.markInProgress(itemKey);\n try {\n // Get the referenced item using the Library.Operations get method (context now managed internally)\n referencedItem = await library!.operations.get(itemKey);\n\n // Cache the result\n context.setCached(itemKey, referencedItem);\n } catch (error: any) {\n libLogger.error('Failed to load reference', {\n component: 'lib-sequelize',\n subcomponent: 'ReferenceBuilder',\n operation: 'buildSequelizeReference',\n property: referenceDefinition.property,\n referenceKey: JSON.stringify(itemKey),\n referencedItemType: primaryKeyType,\n errorType: error?.constructor?.name,\n errorMessage: error?.message,\n errorCode: error?.code || error?.errorInfo?.code,\n suggestion: 'Check referenced item exists, registry is configured, and database connectivity'\n });\n throw error; // Re-throw to maintain original behavior\n } finally {\n // Always mark as complete, even if there was an error\n context.markComplete(itemKey);\n }\n }\n } else {\n // Fallback to original behavior if no context provided\n referencedItem = await library!.operations.get(itemKey);\n }\n\n // Store the result in the property on item (Sequelize style - direct property)\n item[referenceDefinition.property] = referencedItem;\n\n return item;\n};\n\n/**\n * Strip populated reference properties from item before writing to database.\n * This ensures we only store the foreign key columns, not the full populated items.\n *\n * @param item - The item to strip references from\n * @param referenceDefinitions - Array of reference definitions to strip\n * @returns The item with only foreign key values (no populated items)\n */\nexport const stripSequelizeReferenceItems = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n referenceDefinitions: SequelizeReferenceDefinition[]\n ): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n const result = { ...item };\n\n // Remove populated reference properties but keep the foreign key columns\n for (const refDef of referenceDefinitions) {\n // Delete the populated property (e.g., delete item.author)\n // Keep the foreign key column (e.g., keep item.authorId)\n delete result[refDef.property as keyof typeof result];\n }\n\n return result;\n};\n\n", "/**\n * RefsAdapter: Transparent wrapper for Sequelize items\n *\n * This module provides transparent conversion between Sequelize's foreign key column pattern\n * and Firestore's refs structure pattern. The wrapper is completely confined to the Sequelize\n * library - items are automatically wrapped when leaving the library and unwrapped when entering.\n *\n * Key Principles:\n * - Transparency: Users never need to think about wrapping/unwrapping\n * - Boundary Confinement: All complexity stays within @fjell/lib-sequelize\n * - Automatic: Wrapping happens on output, unwrapping happens on input\n * - Unified API: External code always sees refs structure, regardless of backend\n */\n\nimport { ComKey, isComKey, isPriKey, Item, PriKey } from \"@fjell/core\";\nimport { SequelizeReferenceDefinition } from \"./ReferenceBuilder\";\nimport logger from \"../logger\";\n\nconst libLogger = logger.get('sequelize', 'processing', 'RefsAdapter');\n\n/**\n * Type for a reference structure with flattened item properties.\n * When populated, item properties are merged directly onto the reference object.\n * This allows access via refs.name.property instead of refs.name.item.property.\n */\nexport type ItemReference = {\n key: PriKey<any> | ComKey<any, any, any, any, any, any>;\n} & Partial<Omit<Item<any, any, any, any, any, any>, 'key'>>;\n\n/**\n * Builds a key structure (PriKey or ComKey) from a foreign key value and reference definition.\n * This converts Sequelize's foreign key column pattern to Fjell's key structure.\n */\nexport function buildKeyFromForeignKey(\n refDef: SequelizeReferenceDefinition,\n foreignKeyValue: any,\n item: any\n): PriKey<any> | ComKey<any, any, any, any, any, any> {\n const primaryKeyType = refDef.kta[0];\n const isCompositeItem = refDef.kta.length > 1;\n\n if (!isCompositeItem) {\n // Primary item reference: use PriKey\n return {\n kt: primaryKeyType,\n pk: foreignKeyValue\n };\n }\n\n // Composite item reference: build ComKey\n const loc: Array<{kt: string, lk: any}> = [];\n\n if (refDef.locationColumns && refDef.locationColumns.length > 0) {\n // Build full ComKey with location context\n for (let i = 0; i < refDef.locationColumns.length; i++) {\n const columnName = refDef.locationColumns[i];\n const locValue = item[columnName];\n\n if (locValue != null) {\n const locationType = refDef.kta[i + 1]; // Skip primary key type\n loc.push({\n kt: locationType,\n lk: locValue\n });\n } else {\n libLogger.debug(\n `Location column '${columnName}' is null/undefined for reference '${refDef.property}'. ` +\n `Using empty loc array.`\n );\n // If any location column is missing, use empty loc array\n break;\n }\n }\n }\n\n return {\n kt: primaryKeyType,\n pk: foreignKeyValue,\n loc: loc.length > 0 ? loc as any : []\n };\n}\n\n/**\n * Converts a Sequelize item to include a flattened refs structure.\n * Foreign key columns are moved to refs[name].key, and populated references\n * have their properties merged directly onto refs[name] (not nested under item).\n *\n * This is called automatically when items leave the Sequelize library (e.g., returned\n * from operations). The refs structure is added transparently - external code always\n * sees items with refs structure, regardless of the underlying storage pattern.\n *\n * @param item - The Sequelize item (plain object)\n * @param referenceDefinitions - Array of SequelizeReferenceDefinition configs\n * @returns The item with a refs structure added\n */\nexport function addRefsToSequelizeItem<T extends Item<any, any, any, any, any, any>>(\n item: T,\n referenceDefinitions: SequelizeReferenceDefinition[]\n): T & { refs: Record<string, ItemReference> } {\n const refs: Record<string, ItemReference> = {};\n\n for (const refDef of referenceDefinitions) {\n const foreignKeyValue = item[refDef.column as keyof T];\n const refName = refDef.property;\n\n if (foreignKeyValue != null) {\n // Build key structure from foreign key\n const key = buildKeyFromForeignKey(refDef, foreignKeyValue, item);\n\n // Get populated reference if available\n const populatedItem = item[refDef.property as keyof T] as Item<any, any, any, any, any, any> | undefined;\n\n if (populatedItem) {\n // Merge item properties directly onto reference object (excluding the item's own key)\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { key: _itemKey, ...itemProperties } = populatedItem;\n refs[refName] = {\n key,\n ...itemProperties\n } as ItemReference;\n } else {\n // Unpopulated reference - just the key\n refs[refName] = {\n key\n };\n }\n } else {\n // Foreign key is null/undefined - still create ref entry but with null key\n refs[refName] = {\n key: {\n kt: refDef.kta[0],\n pk: null as any // Will be handled as null reference\n }\n };\n }\n }\n\n return {\n ...item,\n refs\n } as T & { refs: Record<string, ItemReference> };\n}\n\n/**\n * Updates foreign key columns in a Sequelize item based on refs structure.\n * This is used when writing items that have been modified via the refs structure.\n *\n * With flattened references, item properties are directly on the reference object,\n * so we reconstruct the item if properties beyond 'key' are present.\n *\n * @param item - The Sequelize item to update\n * @param refs - The refs structure containing updated reference keys\n * @param referenceDefinitions - Array of SequelizeReferenceDefinition configs\n */\nexport function updateForeignKeysFromRefs(\n item: any,\n refs: Record<string, ItemReference>,\n referenceDefinitions: SequelizeReferenceDefinition[]\n): void {\n for (const refDef of referenceDefinitions) {\n const refName = refDef.property;\n const ref = refs[refName];\n\n if (ref && ref.key) {\n // Update foreign key column from refs[key].key\n if (isPriKey(ref.key)) {\n item[refDef.column] = ref.key.pk;\n } else if (isComKey(ref.key)) {\n const comKey = ref.key as ComKey<any, any, any, any, any, any>; // Type assertion after isComKey check\n item[refDef.column] = comKey.pk;\n \n // Update location columns if provided\n if (refDef.locationColumns && comKey.loc) {\n comKey.loc.forEach((locItem: any, index: number) => {\n if (refDef.locationColumns && refDef.locationColumns[index]) {\n item[refDef.locationColumns[index]] = locItem.lk;\n }\n });\n }\n }\n\n // Check if reference is populated (has properties beyond 'key')\n // Reconstruct the item from flattened properties\n const { key, ...itemProperties } = ref;\n const hasItemProperties = Object.keys(itemProperties).length > 0;\n \n if (hasItemProperties) {\n // Reconstruct the item with its key and properties\n item[refDef.property] = {\n key,\n ...itemProperties\n } as Item<any, any, any, any, any, any>;\n } else {\n // Unpopulated reference - clear the property\n delete item[refDef.property];\n }\n } else if (ref == null) {\n // Reference was explicitly set to null/undefined in refs - set foreign key to null\n // Only update if the ref was explicitly set (not if it's missing from refs object)\n if (refName in refs) {\n item[refDef.column] = null;\n // Clear populated reference property\n delete item[refDef.property];\n }\n // If ref is not in refs object at all, preserve original foreign key value\n }\n }\n}\n\n/**\n * Removes the refs structure from a Sequelize item, converting it back to\n * the standard Sequelize format with foreign key columns.\n *\n * This is called automatically when items enter the Sequelize library (e.g., passed\n * to create/update operations). The refs structure is removed transparently and\n * foreign key columns are updated from the refs structure if present.\n *\n * @param item - The item with refs structure\n * @param referenceDefinitions - Array of SequelizeReferenceDefinition configs\n * @returns The item without refs structure, with foreign keys updated from refs if present\n */\nexport function removeRefsFromSequelizeItem<T extends Item<any, any, any, any, any, any>>(\n item: Partial<T> & { refs?: Record<string, ItemReference> },\n referenceDefinitions: SequelizeReferenceDefinition[]\n): Partial<T> {\n const result = { ...item } as any;\n\n // If item has refs structure, update foreign keys from it\n if (result.refs) {\n updateForeignKeysFromRefs(result, result.refs, referenceDefinitions);\n // Remove refs property\n delete result.refs;\n }\n // If no refs structure, preserve original foreign key values (no change needed)\n\n return result as T;\n}\n\n/**\n * Creates a Proxy wrapper around a Sequelize item that provides dynamic refs access.\n * This allows reading and writing refs structure while maintaining compatibility\n * with the underlying Sequelize item.\n *\n * @param item - The Sequelize item to wrap\n * @param referenceDefinitions - Array of SequelizeReferenceDefinition configs\n * @returns A proxied item with dynamic refs property\n */\nexport function createRefsProxy<T extends Item<any, any, any, any, any, any>>(\n item: T,\n referenceDefinitions: SequelizeReferenceDefinition[]\n): T & { refs: Record<string, ItemReference> } {\n return new Proxy(item, {\n get(target, prop) {\n if (prop === 'refs') {\n // Rebuild refs structure dynamically to reflect current state\n return addRefsToSequelizeItem(target as T, referenceDefinitions).refs;\n }\n return (target as any)[prop];\n },\n set(target, prop, value) {\n if (prop === 'refs' && typeof value === 'object') {\n // Update foreign keys from refs structure\n updateForeignKeysFromRefs(target, value, referenceDefinitions);\n return true;\n }\n \n // Handle nested refs updates (e.g., item.refs.author.key = {...})\n // This is tricky with Proxy, so we'll rely on the getter rebuilding refs\n (target as any)[prop] = value;\n return true;\n },\n has(target, prop) {\n if (prop === 'refs') {\n return true;\n }\n return prop in target;\n },\n ownKeys(target) {\n return ['refs', ...Object.keys(target)];\n },\n getOwnPropertyDescriptor(target, prop) {\n if (prop === 'refs') {\n return {\n enumerable: true,\n configurable: true,\n value: addRefsToSequelizeItem(target as T, referenceDefinitions).refs\n };\n }\n return Object.getOwnPropertyDescriptor(target, prop);\n }\n }) as T & { refs: Record<string, ItemReference> };\n}\n\n", "/**\n * AggsAdapter: Transparent wrapper for aggregations\n *\n * This module provides transparent conversion between direct aggregation properties\n * and a unified aggs structure pattern. The wrapper is completely confined to the\n * library boundaries - items are automatically wrapped when leaving libraries and\n * unwrapped when entering.\n *\n * Key Principles:\n * - Transparency: Users never need to think about wrapping/unwrapping\n * - Boundary Confinement: All complexity stays within library boundaries\n * - Automatic: Wrapping happens on output, unwrapping happens on input\n * - Unified API: External code always sees aggs structure, regardless of backend\n */\n\nimport { Item } from \"@fjell/core\";\nimport { AggregationDefinition } from \"@fjell/lib\";\nimport logger from \"../logger\";\n\nconst libLogger = logger.get('sequelize', 'processing', 'AggsAdapter');\n\n/**\n * Converts an item to include an aggs structure.\n * Aggregation properties are moved from direct properties to aggs[name].\n *\n * This is called automatically when items leave libraries (e.g., returned\n * from operations). The aggs structure is added transparently - external\n * code always sees items with aggs structure.\n *\n * @param item - The item (plain object)\n * @param aggregationDefinitions - Array of AggregationDefinition configs\n * @returns The item with an aggs structure added\n */\nexport function addAggsToItem<T extends Item<any, any, any, any, any, any>>(\n item: T,\n aggregationDefinitions: AggregationDefinition[]\n): T & { aggs: Record<string, any> } {\n if (!aggregationDefinitions || aggregationDefinitions.length === 0) {\n return item as T & { aggs: Record<string, any> };\n }\n\n const aggs: Record<string, any> = {};\n const result = { ...item } as any;\n\n for (const aggDef of aggregationDefinitions) {\n const aggregationValue = item[aggDef.property as keyof T];\n\n if (typeof aggregationValue !== 'undefined') {\n // Move aggregation from direct property to aggs structure\n aggs[aggDef.property] = aggregationValue;\n // Remove from direct properties\n delete result[aggDef.property];\n libLogger.default(`Moved aggregation '${aggDef.property}' to aggs structure`, {\n property: aggDef.property,\n hasValue: typeof aggregationValue !== 'undefined',\n valueType: Array.isArray(aggregationValue) ? 'array' : typeof aggregationValue\n });\n } else {\n libLogger.debug(`Aggregation '${aggDef.property}' is undefined, skipping`, {\n property: aggDef.property\n });\n }\n }\n\n // Only add aggs property if there are aggregations\n if (Object.keys(aggs).length > 0) {\n return {\n ...result,\n aggs\n } as T & { aggs: Record<string, any> };\n }\n\n return item as T & { aggs: Record<string, any> };\n}\n\n/**\n * Removes the aggs structure from an item, converting it back to\n * direct properties. This is mainly for consistency since aggregations\n * are read-only and typically not written back.\n *\n * This is called automatically when items enter libraries (e.g., passed\n * to create/update operations). The aggs structure is removed transparently.\n *\n * @param item - The item with aggs structure\n * @param aggregationDefinitions - Array of AggregationDefinition configs\n * @returns The item without aggs structure, with aggregations as direct properties\n */\nexport function removeAggsFromItem<T extends Partial<Item<any, any, any, any, any, any>> & { aggs?: Record<string, any> }>(\n item: T,\n aggregationDefinitions: AggregationDefinition[]\n): T {\n if (!aggregationDefinitions || aggregationDefinitions.length === 0) {\n return item;\n }\n\n const result = { ...item } as any;\n\n // If item has aggs structure, move aggregations back to direct properties\n if (result.aggs && typeof result.aggs === 'object') {\n for (const aggDef of aggregationDefinitions) {\n if (typeof result.aggs[aggDef.property] !== 'undefined') {\n result[aggDef.property] = result.aggs[aggDef.property];\n libLogger.debug(`Moved aggregation '${aggDef.property}' from aggs to direct property`, {\n property: aggDef.property\n });\n }\n }\n // Remove aggs property\n delete result.aggs;\n }\n // If no aggs structure, preserve original aggregation values (no change needed)\n\n return result as T;\n}\n\n", "import {\n BusinessLogicError,\n DuplicateError,\n ValidationError\n} from \"@fjell/core\";\nimport LibLogger from '../logger';\n\nconst logger = LibLogger.get('sequelize', 'errors', 'errorHandler');\n\n/**\n * Transforms Sequelize-specific errors into Fjell error types.\n *\n * Sequelize surfaces both its own error types and raw database error codes:\n * - PostgreSQL: numeric codes like '23505' (unique violation), '23503' (foreign key)\n * - MySQL: named codes like 'ER_DUP_ENTRY', 'ER_NO_REFERENCED_ROW'\n * - SQLite: often no codes, just error messages\n *\n * @param error - The Sequelize error to transform\n * @param itemType - The type of item being operated on\n * @param key - Optional key context for the error\n * @param modelName - Optional model name for enhanced error messages\n * @param itemData - Optional item data for enhanced error messages\n * @returns A Fjell error type or the original error if not recognized\n */\nexport function transformSequelizeError(\n error: any,\n itemType: string,\n key?: any,\n modelName?: string,\n itemData?: any\n): Error {\n // Handle PostgreSQL unique constraint errors (code 23505)\n if (error.code === '23505' || error.original?.code === '23505') {\n const constraint = error.original?.constraint;\n const detail = error.original?.detail;\n \n let message = '';\n if (constraint && detail) {\n message = `Duplicate value violates unique constraint '${constraint}'. ${detail}`;\n } else if (detail) {\n message = `Duplicate value detected. This record already exists. ${detail}`;\n } else {\n message = `${itemType} already exists`;\n }\n \n const field = error.fields ? Object.keys(error.fields)[0] : 'unique constraint';\n \n logger.debug('Transformed PostgreSQL unique constraint error to DuplicateError', {\n component: 'lib-sequelize',\n transformation: 'sequelizeErrorHandler',\n originalError: 'PostgreSQL 23505',\n transformedError: 'DuplicateError',\n itemType,\n constraint,\n field,\n model: modelName\n });\n \n return new DuplicateError(message, key, field);\n }\n \n // Handle Sequelize unique constraint errors\n if (error.name === 'SequelizeUniqueConstraintError' || error.code === 'ER_DUP_ENTRY') {\n const field = error.fields ? Object.keys(error.fields)[0] : 'unique constraint';\n return new DuplicateError(\n `${itemType} already exists`,\n key,\n field\n );\n }\n\n // Handle Sequelize validation errors\n if (error.name === 'SequelizeValidationError') {\n const fields = error.errors?.map((e: any) => e.path) || [];\n const message = error.errors?.map((e: any) => e.message).join(', ') ||\n `Validation failed for ${itemType}`;\n return new ValidationError(\n message,\n fields,\n 'Fix validation errors and try again'\n );\n }\n\n // Handle PostgreSQL foreign key constraint errors (code 23503)\n if (error.code === '23503' || error.original?.code === '23503') {\n const constraint = error.original?.constraint;\n const detail = error.original?.detail;\n \n let message = '';\n if (constraint && detail) {\n message = `Foreign key constraint '${constraint}' violated. Referenced record does not exist. ${detail}`;\n } else if (constraint) {\n message = `Foreign key constraint '${constraint}' violated. Referenced record does not exist.`;\n } else if (detail) {\n message = `Referenced record does not exist. Check that all related records are valid. ${detail}`;\n } else {\n message = 'Referenced item does not exist';\n }\n \n return new ValidationError(\n message,\n void 0,\n 'Ensure all referenced items exist before creating this relationship'\n );\n }\n \n // Handle Sequelize foreign key constraint errors\n if (error.name === 'SequelizeForeignKeyConstraintError' || error.code === 'ER_NO_REFERENCED_ROW') {\n return new ValidationError(\n 'Referenced item does not exist',\n void 0,\n 'Ensure all referenced items exist before creating this relationship'\n );\n }\n\n // Handle not null constraint errors (code 23502)\n if (error.code === '23502' || error.original?.code === '23502') {\n const column = error.original?.column;\n const fields = column ? [column] : void 0;\n return new ValidationError(\n column ? `Required field '${column}' cannot be null` : 'Required field is missing or null',\n fields,\n 'Provide all required fields'\n );\n }\n\n // Handle check constraint errors (code 23514)\n if (error.code === '23514' || error.original?.code === '23514') {\n const constraint = error.original?.constraint;\n const detail = error.original?.detail;\n \n let message = '';\n if (constraint && detail) {\n message = `Check constraint '${constraint}' violated. ${detail}`;\n } else if (detail) {\n message = `Data validation failed. Check constraint violated. ${detail}`;\n } else if (constraint) {\n message = `Check constraint '${constraint}' violated`;\n } else {\n message = 'Data validation failed';\n }\n \n return new ValidationError(\n message,\n void 0,\n 'Ensure data meets all constraints'\n );\n }\n\n // Handle unknown column errors\n if (error.name === 'SequelizeDatabaseError' && error.message?.includes('Unknown column')) {\n const match = error.message.match(/Unknown column '(.+?)'/);\n const field = match ? match[1] : 'unknown field';\n return new ValidationError(\n `Invalid field: ${field}`,\n [field],\n 'Check the field names in your request'\n );\n }\n\n // Handle data too long errors (code 22001)\n if (error.code === '22001' || error.original?.code === '22001') {\n const detail = error.original?.detail;\n const message = detail\n ? `Data too long for field. Check string lengths. ${detail}`\n : 'Data too long for field';\n \n return new ValidationError(\n message,\n void 0,\n 'Check string lengths and try again'\n );\n }\n\n // Handle numeric out of range errors (code 22003)\n if (error.code === '22003' || error.original?.code === '22003') {\n const detail = error.original?.detail;\n const message = detail\n ? `Numeric value out of range. Check number values. ${detail}`\n : 'Numeric value out of range';\n \n return new ValidationError(\n message,\n void 0,\n 'Check number values and try again'\n );\n }\n\n // Handle undefined column errors (code 42703)\n if (error.code === '42703' || error.original?.code === '42703') {\n const column = error.original?.column;\n const fields = column ? [column] : void 0;\n const message = column && modelName\n ? `Column '${column}' does not exist in table '${modelName}'`\n : column\n ? `Column '${column}' does not exist`\n : 'Referenced column does not exist';\n \n return new ValidationError(\n message,\n fields,\n 'Check the field names in your request'\n );\n }\n \n // Handle undefined table errors (code 42P01)\n if (error.code === '42P01' || error.original?.code === '42P01') {\n const message = modelName\n ? `Table '${modelName}' does not exist`\n : 'Table does not exist';\n \n return new ValidationError(\n message,\n void 0,\n 'Check the table name and database configuration'\n );\n }\n\n // Handle SQLite-specific errors (no error codes, message-based)\n if (error.message?.includes('notNull Violation') ||\n error.message?.includes('cannot be null')) {\n const fieldMatches = error.message.match(/([a-zA-Z][a-zA-Z0-9_]{0,100}\\.[a-zA-Z][a-zA-Z0-9_]{0,100}) cannot be null/g);\n if (fieldMatches) {\n const fields = fieldMatches.map((match: string) => {\n const parts = match.split('.');\n return parts[1]?.split(' ')[0];\n }).filter(Boolean);\n if (fields.length > 0) {\n return new ValidationError(\n `Required field${fields.length > 1 ? 's' : ''} ${fields.join(', ')} cannot be null`,\n fields,\n 'Provide all required fields'\n );\n }\n }\n return new ValidationError(\n 'Required fields are missing',\n void 0,\n 'Provide all required fields'\n );\n }\n\n // Handle connection errors\n if (error.name === 'SequelizeConnectionError' ||\n error.name === 'SequelizeConnectionRefusedError') {\n logger.error('Transformed database connection error to BusinessLogicError', {\n component: 'lib-sequelize',\n transformation: 'sequelizeErrorHandler',\n originalError: error.name,\n transformedError: 'BusinessLogicError',\n itemType,\n retryable: true,\n model: modelName,\n suggestion: 'Check database is running, connection string is correct, and network connectivity'\n });\n \n return new BusinessLogicError(\n 'Database connection failed',\n 'Check database connectivity and try again',\n true // retryable\n );\n }\n\n // Handle timeout errors\n if (error.name === 'SequelizeTimeoutError') {\n logger.error('Transformed database timeout error to BusinessLogicError', {\n component: 'lib-sequelize',\n transformation: 'sequelizeErrorHandler',\n originalError: 'SequelizeTimeoutError',\n transformedError: 'BusinessLogicError',\n itemType,\n retryable: true,\n model: modelName,\n suggestion: 'Reduce query complexity, add indexes, or increase timeout limits'\n });\n \n return new BusinessLogicError(\n 'Database operation timed out',\n 'Try again or simplify the operation',\n true // retryable\n );\n }\n\n // Handle database errors without original property but with modelName and itemData\n if (!error.original && modelName && itemData && error.message) {\n const formattedData = JSON.stringify(itemData, null, 2);\n return new Error(\n `Database error in ${modelName}.create(): ${error.message}. Item data: ${formattedData}`\n );\n }\n \n // Handle unknown database errors with original property\n if (error.original && modelName && itemData) {\n const formattedData = JSON.stringify(itemData, null, 2);\n return new Error(\n `Database error in ${modelName}.create(): ${error.message}. Item data: ${formattedData}`\n );\n }\n\n // Pass through other errors unchanged\n return error;\n}\n\n", "import LibLogger from '../logger';\n\nconst logger = LibLogger.get('sequelize', 'metrics', 'QueryMetrics');\n\n/**\n * Tracks query execution metrics for Sequelize operations\n */\nexport class QueryMetrics {\n private totalQueryCount: number = 0;\n private queriesByModel: Map<string, number> = new Map();\n private readonly LOG_INTERVAL: number = 10;\n\n /**\n * Records a query execution for a given model\n * @param modelName - The name of the Sequelize model the query was executed against\n */\n recordQuery(modelName: string): void {\n this.totalQueryCount++;\n \n // Track queries per model\n const currentCount = this.queriesByModel.get(modelName) || 0;\n this.queriesByModel.set(modelName, currentCount + 1);\n\n // Log DEBUG message every 10 queries\n if (this.totalQueryCount % this.LOG_INTERVAL === 0) {\n const modelBreakdown = Array.from(this.queriesByModel.entries())\n .map(([model, count]) => `${model}: ${count}`)\n .join(', ');\n \n logger.debug(\n `Query execution count: ${this.totalQueryCount} total queries. ` +\n `Breakdown by model: ${modelBreakdown || 'none'}`\n );\n }\n }\n\n /**\n * Gets the total number of queries executed\n */\n getTotalQueryCount(): number {\n return this.totalQueryCount;\n }\n\n /**\n * Gets the number of queries executed for a specific model\n */\n getQueryCountForModel(modelName: string): number {\n return this.queriesByModel.get(modelName) || 0;\n }\n\n /**\n * Gets a map of all model query counts\n */\n getQueriesByModel(): Map<string, number> {\n return new Map(this.queriesByModel);\n }\n\n /**\n * Resets all metrics (useful for testing)\n */\n reset(): void {\n this.totalQueryCount = 0;\n this.queriesByModel.clear();\n }\n}\n\n// Export a singleton instance\nexport const queryMetrics = new QueryMetrics();\n\n", "/* eslint-disable indent */\nimport { ComKey, createCreateWrapper, CreateMethod, isComKey, isPriKey, Item, LocKeyArray, PriKey } from \"@fjell/core\";\nimport { validateKeys } from \"@fjell/core/validation\";\n\nimport { Definition } from \"../Definition\";\nimport LibLogger from '../logger';\nimport { processRow } from \"../RowProcessor\";\nimport * as Library from \"@fjell/lib\";\nimport { ModelStatic } from \"sequelize\";\nimport { extractEvents, removeEvents } from \"../EventCoordinator\";\nimport { buildRelationshipChain, buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { stringifyJSON } from \"../util/general\";\nimport { transformSequelizeError } from \"../errors/sequelizeErrorHandler\";\nimport { removeRefsFromSequelizeItem } from \"../processing/RefsAdapter\";\nimport { removeAggsFromItem } from \"../processing/AggsAdapter\";\nimport { queryMetrics } from \"../metrics/QueryMetrics\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'create');\n\n// Helper function to validate hierarchical chain exists\nasync function validateHierarchicalChain(\n models: ModelStatic<any>[],\n locKey: { kt: string; lk: any },\n kta: string[]\n): Promise<void> {\n // Find the direct parent model that contains this locator\n const locatorIndex = kta.indexOf(locKey.kt);\n if (locatorIndex === -1) {\n throw new Error(`Locator type '${locKey.kt}' not found in kta array`);\n }\n\n // Get the model for this locator (define outside try block for catch block access)\n const locatorModel = models[locatorIndex] || models[0]; // Fallback to primary model\n \n try {\n // Build a query to validate the chain exists\n const chainResult = buildRelationshipChain(locatorModel, kta, locatorIndex, kta.length - 1);\n\n if (!chainResult.success) {\n // If we can't build a chain, just validate the record exists\n queryMetrics.recordQuery(locatorModel.name);\n const record = await locatorModel.findByPk(locKey.lk);\n if (!record) {\n throw new Error(`Referenced ${locKey.kt} with id ${locKey.lk} does not exist`);\n }\n return;\n }\n\n // Validate that the chain exists\n const queryOptions: any = {\n where: { id: locKey.lk }\n };\n\n if (chainResult.includes && chainResult.includes.length > 0) {\n queryOptions.include = chainResult.includes;\n }\n\n queryMetrics.recordQuery(locatorModel.name);\n const record = await locatorModel.findOne(queryOptions);\n if (!record) {\n throw new Error(`Referenced ${locKey.kt} with id ${locKey.lk} does not exist or chain is invalid`);\n }\n } catch (error: any) {\n // Transform database errors to Fjell error types\n if (error.original) {\n throw transformSequelizeError(error, locKey.kt, { locKey, kta }, locatorModel.name);\n }\n throw error;\n }\n}\n\nexport const getCreateOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n\n registry: Library.Registry\n): CreateMethod<V, S, L1, L2, L3, L4, L5> => {\n\n const { coordinate, options: { references, aggregations } } = definition;\n const { kta } = coordinate;\n\n return createCreateWrapper(\n coordinate,\n async (\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?: {\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n locations?: never;\n } | {\n key?: never;\n locations: LocKeyArray<L1, L2, L3, L4, L5>,\n }\n ): Promise<V> => {\n const constraints = options?.key\n ? `key: pk=${options.key.pk}, loc=[${isComKey(options.key)\n ? (options.key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')\n : ''}]`\n : options?.locations\n ? `locations: ${options.locations.map(loc => `${loc.kt}=${loc.lk}`).join(', ')}`\n : 'no constraints';\n logger.debug(`CREATE operation called on ${models[0].name} with ${constraints}`);\n logger.default(`Create configured for ${models[0].name} with ${Object.keys(item).length} item fields`);\n\n // Get the primary model (first model in array)\n const model = models[0];\n const modelAttributes = model.getAttributes();\n\n // Validate that all item attributes exist on the model\n let itemData = { ...item } as any;\n\n // TODO: We need the opposite of processRow, something to step down from fjell to database.\n itemData = extractEvents(itemData);\n itemData = removeEvents(itemData);\n \n // Remove refs structure if present (convert back to foreign key columns)\n if (references && references.length > 0) {\n itemData = removeRefsFromSequelizeItem(itemData, references);\n }\n \n // Remove aggs structure if present (convert back to direct properties)\n if (aggregations && aggregations.length > 0) {\n itemData = removeAggsFromItem(itemData, aggregations);\n }\n\n // Validate that all item attributes exist on the model\n const invalidAttributes: string[] = [];\n for (const key of Object.keys(itemData)) {\n if (!modelAttributes[key]) {\n invalidAttributes.push(key);\n }\n }\n\n if (invalidAttributes.length > 0) {\n const availableAttributes = Object.keys(modelAttributes).join(', ');\n const errorMessage = `Invalid attributes for model '${model.name}': [${invalidAttributes.join(', ')}]. ` +\n `Available attributes: [${availableAttributes}].`;\n \n logger.error('Create operation failed - invalid attributes', {\n operation: 'create',\n model: model.name,\n invalidAttributes,\n availableAttributes: Object.keys(modelAttributes),\n providedAttributes: Object.keys(itemData),\n itemData: JSON.stringify(itemData, null, 2),\n suggestion: `Remove invalid attributes or add them to the model definition. Valid attributes are: ${availableAttributes}`,\n coordinate: JSON.stringify(definition.coordinate)\n });\n \n throw new Error(errorMessage + ` Item data: ${JSON.stringify(itemData, null, 2)}`);\n }\n\n // Handle key options\n // If a key is supplied, assume its contents are to be assigned to the appropriate ids.\n // For most cases this will be null as key generation is often through autoIncrement.\n // If this is a CItem then the locations will be present.\n if (options?.key) {\n const key = options.key;\n if (isPriKey(key)) {\n // Set the primary key\n itemData.id = key.pk;\n } else if (isComKey(key)) {\n // Set primary key\n itemData.id = key.pk;\n\n // Process location keys - only set direct foreign keys, validate hierarchical chains\n const comKey = key as ComKey<S, L1, L2, L3, L4, L5>;\n const directLocations: Array<{ kt: string; lk: any }> = [];\n const hierarchicalLocations: Array<{ kt: string; lk: any }> = [];\n\n // Categorize location keys as direct or hierarchical\n for (const locKey of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const associations = model.associations ? Object.keys(model.associations) : [];\n const errorMessage = `Composite key locator '${locKey.kt}' cannot be resolved on model '${model.name}' or through its relationships. ` +\n `Available associations: [${associations.join(', ')}]. ` +\n `KTA: [${kta.join(', ')}]. ` +\n `Composite key: ${JSON.stringify(comKey, null, 2)}`;\n logger.error(errorMessage, { key: comKey, kta, associations });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n directLocations.push(locKey);\n } else {\n hierarchicalLocations.push(locKey);\n }\n }\n\n // Set direct foreign keys\n for (const locKey of directLocations) {\n if (locKey.lk == null || locKey.lk === '') {\n logger.error(`Composite key location '${locKey.kt}' has undefined/null lk value`, { locKey, key: comKey });\n throw new Error(`Composite key location '${locKey.kt}' has undefined/null lk value`);\n }\n const foreignKeyField = locKey.kt + 'Id';\n itemData[foreignKeyField] = locKey.lk;\n }\n\n // Validate hierarchical chains exist\n for (const locKey of hierarchicalLocations) {\n await validateHierarchicalChain(models, locKey, kta);\n }\n }\n }\n\n // Handle locations options\n // This is the most frequent way relationship ids will be set\n if (options?.locations) {\n const directLocations: Array<{ kt: string; lk: any }> = [];\n const hierarchicalLocations: Array<{ kt: string; lk: any }> = [];\n\n // Categorize location keys as direct or hierarchical\n for (const locKey of options.locations) {\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const associations = model.associations ? Object.keys(model.associations) : [];\n const errorMessage = `Location key '${locKey.kt}' cannot be resolved on model '${model.name}' or through its relationships. ` +\n `Available associations: [${associations.join(', ')}]. ` +\n `KTA: [${kta.join(', ')}]. ` +\n `Locations: ${JSON.stringify(options.locations, null, 2)}`;\n logger.error(errorMessage, { locations: options.locations, kta, associations });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n directLocations.push(locKey);\n } else {\n hierarchicalLocations.push(locKey);\n }\n }\n\n // Set direct foreign keys\n for (const locKey of directLocations) {\n if (locKey.lk == null || locKey.lk === '') {\n logger.error(`Location option '${locKey.kt}' has undefined/null lk value`, { locKey, locations: options.locations });\n throw new Error(`Location option '${locKey.kt}' has undefined/null lk value`);\n }\n const foreignKeyField = locKey.kt + 'Id';\n itemData[foreignKeyField] = locKey.lk;\n }\n\n // Validate hierarchical chains exist\n for (const locKey of hierarchicalLocations) {\n await validateHierarchicalChain(models, locKey, kta);\n }\n }\n\n // Create the record\n try {\n logger.trace(`[CREATE] Executing ${model.name}.create() with data: ${stringifyJSON(itemData)}`);\n queryMetrics.recordQuery(model.name);\n const createdRecord = await model.create(itemData);\n\n // Add key and events\n // Create operations get their own context since they're top-level operations\n // For create, we don't pre-load aggregations via INCLUDE, so pass void 0\n const processedRecord = await processRow(createdRecord, kta, references || [], aggregations || [], registry, void 0, void 0);\n const result = validateKeys(processedRecord, kta) as V;\n\n logger.debug(`[CREATE] Created ${model.name} with key: ${(result as any).key ? JSON.stringify((result as any).key) : `id=${createdRecord.id}`}`);\n return result;\n } catch (error: any) {\n // Log detailed error information for debugging\n logger.error('Create operation failed', {\n operation: 'create',\n model: model.name,\n itemData: JSON.stringify(itemData, null, 2),\n options: JSON.stringify(options),\n errorType: error?.constructor?.name || typeof error,\n errorMessage: error?.message,\n errorName: error?.name,\n sqlError: error?.original?.message,\n sqlCode: error?.original?.code,\n constraint: error?.original?.constraint,\n detail: error?.original?.detail,\n suggestion: 'Check validation rules, unique constraints, foreign keys, required fields, and data types',\n coordinate: JSON.stringify(definition.coordinate)\n });\n \n throw transformSequelizeError(error, kta[0], options?.key, model.name, itemData);\n }\n }\n );\n}\n", "/* eslint-disable indent */\nimport { createFindWrapper, FindMethod, FindOperationResult, FindOptions, Item, LocKeyArray } from \"@fjell/core\";\nimport { validateKeys } from \"@fjell/core/validation\";\n\nimport { Definition } from \"../Definition\";\nimport LibLogger from '../logger';\nimport { ModelStatic } from \"sequelize\";\nimport { processRow } from \"../RowProcessor\";\nimport * as Library from \"@fjell/lib\";\nimport { stringifyJSON } from \"../util/general\";\nimport { transformSequelizeError } from \"../errors/sequelizeErrorHandler\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'find');\n\nexport const getFindOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n): FindMethod<V, S, L1, L2, L3, L4, L5> => {\n\n const { options: { finders, references, aggregations } } = definition;\n\n return createFindWrapper(\n definition.coordinate,\n async (\n finder: string,\n finderParams?: Record<string, string | number | boolean | Date | Array<string | number | boolean | Date>>,\n locations?: LocKeyArray<L1, L2, L3, L4, L5> | [],\n findOptions?: FindOptions\n ): Promise<FindOperationResult<V>> => {\n try {\n const locs = locations ?? [];\n const params = finderParams ?? {};\n const locationFilters = locs.map(loc => `${loc.kt}=${loc.lk}`).join(', ') || 'none';\n logger.debug(\n `FIND operation called on ${models[0].name} with finder '${finder}' ` +\n `and ${locs.length} location filters: ${locationFilters}`\n );\n logger.default(`Find configured for ${models[0].name} using finder '${finder}' with ${Object.keys(params).length} params`);\n\n // Note that we execute the createFinders function here because we want to make sure we're always getting the\n // most up to date methods.\n if (!finders || !finders[finder]) {\n const availableFinders = finders ? Object.keys(finders) : [];\n logger.error(`No finders defined for library`, {\n operation: 'find',\n model: models[0]?.name,\n requestedFinder: finder,\n availableFinders,\n suggestion: availableFinders.length > 0\n ? `Use one of the available finders: ${availableFinders.join(', ')}`\n : 'Define finders in your library configuration',\n coordinate: JSON.stringify(definition.coordinate)\n });\n throw new Error(`No finders found. ${availableFinders.length > 0 ? `Available finders: ${availableFinders.join(', ')}` : 'No finders defined.'}`);\n }\n\n const finderMethod = finders[finder];\n if (!finderMethod) {\n const availableFinders = Object.keys(finders);\n logger.error(`Finder not found`, {\n operation: 'find',\n model: models[0]?.name,\n requestedFinder: finder,\n availableFinders,\n suggestion: `Use one of: ${availableFinders.join(', ')}`,\n coordinate: JSON.stringify(definition.coordinate)\n });\n throw new Error(`Finder '${finder}' not found. Available finders: ${availableFinders.join(', ')}`);\n }\n\n logger.trace(`[FIND] Executing finder '${finder}' on ${models[0].name} with params: ${stringifyJSON(params)}, locations: ${stringifyJSON(locs)}, options: ${stringifyJSON(findOptions)}`);\n // Pass findOptions to finder - finder can opt-in by returning FindOperationResult, or return V[] for legacy behavior\n const finderResult = await finderMethod(params, locs, findOptions);\n\n // Helper function to process items\n const processItems = async (items: any[]): Promise<V[]> => {\n return (await Promise.all(items.map(async (row: any) => {\n // For finders, we don't control the query, so we pass void 0 for includedAggregations\n // The custom finder might have already loaded associations via INCLUDE\n const processedRow = await processRow(row, definition.coordinate.kta, references || [], aggregations || [], registry, void 0, void 0);\n return validateKeys(processedRow, definition.coordinate.kta);\n })) as V[]);\n };\n\n // Check if finder opted-in (returned FindOperationResult) or legacy (returned V[])\n const isOptInResult = finderResult && typeof finderResult === 'object' && 'items' in finderResult && 'metadata' in finderResult;\n\n if (isOptInResult) {\n // Finder opted-in: process items and return FindOperationResult\n const optInResult = finderResult as FindOperationResult<any>;\n const processedResults = optInResult.items && optInResult.items.length > 0\n ? await processItems(optInResult.items)\n : [];\n\n logger.debug(`[FIND] Finder opted-in, found ${processedResults.length} ${models[0].name} records using finder '${finder}' (total: ${optInResult.metadata.total})`);\n return {\n items: processedResults,\n metadata: optInResult.metadata\n };\n }\n\n // Legacy finder: process results as array\n const results = finderResult as V[];\n const processedResults = results && results.length > 0\n ? await processItems(results)\n : [];\n\n logger.debug(`[FIND] Legacy finder, found ${processedResults.length} ${models[0].name} records using finder '${finder}'`);\n // Return as FindOperationResult - createFindWrapper will apply post-processing pagination\n return {\n items: processedResults,\n metadata: {\n total: processedResults.length,\n returned: processedResults.length,\n offset: 0,\n hasMore: false\n }\n };\n } catch (error: any) {\n // Enhanced error logging before transforming\n logger.error('Error in find operation', {\n finder,\n finderParams: finderParams,\n locations: locations,\n findOptions,\n errorMessage: error?.message,\n errorName: error?.name,\n errorStack: error?.stack,\n errorCause: error?.cause,\n errorString: String(error),\n errorJSON: JSON.stringify(error, Object.getOwnPropertyNames(error))\n });\n console.error('ERROR in SequelizeLibrary find:', {\n finder,\n error: error?.message || String(error),\n stack: error?.stack\n });\n // Transform database errors\n throw transformSequelizeError(error, definition.coordinate.kta[0]);\n }\n }\n );\n}\n", "/* eslint-disable max-len */\n/* eslint-disable indent */\nimport {\n ComKey,\n createGetWrapper,\n GetMethod,\n isComKey,\n isPriKey,\n isValidItemKey,\n Item,\n PriKey,\n validateKeys\n} from '@fjell/core';\n\nimport LibLogger from '../logger';\nimport { ModelStatic } from 'sequelize';\nimport { processRow } from '../RowProcessor';\nimport { Definition } from '../Definition';\nimport { NotFoundError } from '@fjell/core';\nimport * as Library from \"@fjell/lib\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { contextManager } from \"../RowProcessor\";\nimport { stringifyJSON } from \"../util/general\";\nimport { transformSequelizeError } from \"../errors/sequelizeErrorHandler\";\nimport { addAggregationIncludes, addReferenceIncludes } from \"../QueryBuilder\";\nimport { queryMetrics } from \"../metrics/QueryMetrics\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'get');\n\n// Helper function to process composite key and build query options\nconst processCompositeKey = (\n comKey: ComKey<any, any, any, any, any, any>,\n model: ModelStatic<any>,\n kta: string[]\n): { where: { [key: string]: any }; include?: any[] } => {\n const where: { [key: string]: any } = { id: comKey.pk };\n const includes: any[] = [];\n\n for (const locator of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locator.kt, kta);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Composite key locator '${locator.kt}' cannot be resolved on model '${model.name}' or through its relationships. Key type array: [${kta.join(', ')}], Composite key: ${stringifyJSON(comKey)}, Available associations: [${Object.keys(model.associations || {}).join(', ')}]`;\n logger.error(errorMessage, { key: comKey, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.path) {\n // This requires a relationship traversal\n where[relationshipInfo.path] = locator.lk;\n if (relationshipInfo.includes) {\n includes.push(...relationshipInfo.includes);\n }\n } else {\n // This is a direct field\n const fieldName = `${locator.kt}Id`;\n where[fieldName] = locator.lk;\n }\n }\n\n const result: { where: { [key: string]: any }; include?: any[] } = { where };\n if (includes.length > 0) {\n result.include = includes;\n }\n\n return result;\n};\n\nexport const getGetOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: Array<ModelStatic<any>>,\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n): GetMethod<V, S, L1, L2, L3, L4, L5> => {\n\n const { coordinate, options: { references, aggregations } } = definition;\n const { kta } = coordinate;\n\n return createGetWrapper(\n coordinate,\n async (key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>): Promise<V> => {\n try {\n if (!isValidItemKey(key)) {\n logger.error('Key for Get is not a valid ItemKey: %j', key);\n throw new Error('Key for Get is not a valid ItemKey');\n }\n\n const keyDescription = isPriKey(key)\n ? `primary key: pk=${key.pk}`\n : `composite key: pk=${key.pk}, loc=[${(key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')}]`;\n logger.debug(`GET operation called on ${models[0].name} with ${keyDescription}`);\n logger.default(`Get configured for ${models[0].name} with ${isPriKey(key) ? 'primary' : 'composite'} key`);\n\n const itemKey = key;\n\n // @ts-ignore\n const model = models[0];\n\n let item;\n let includedAggregations: string[] = [];\n let includedReferences: string[] = [];\n\n if (isPriKey(itemKey)) {\n // For primary key lookups, add reference and aggregation includes\n let options: any = {};\n const refResult = addReferenceIncludes(options, model, references || []);\n includedReferences = refResult.includedReferences;\n options = refResult.options;\n const aggResult = addAggregationIncludes(options, model, aggregations || []);\n includedAggregations = aggResult.includedAggregations;\n options = aggResult.options;\n\n // This is the easy case because we can just find the item by its primary key\n logger.trace(`[GET] Executing ${model.name}.findByPk() with pk: ${(itemKey as PriKey<S>).pk}, ${includedReferences.length} reference includes, and ${includedAggregations.length} aggregation includes`);\n queryMetrics.recordQuery(model.name);\n item = options.include && options.include.length > 0\n ? await model.findByPk((itemKey as PriKey<S>).pk, { include: options.include })\n : await model.findByPk((itemKey as PriKey<S>).pk);\n } else if (isComKey(itemKey)) {\n const comKey = itemKey as ComKey<S, L1, L2, L3, L4, L5>;\n\n // Empty loc array is a special case: find by primary key across all locations\n // This is used for foreign key references to composite items where location context is unknown\n if (comKey.loc.length === 0) {\n // For primary key lookups, add reference and aggregation includes\n let options: any = {};\n const refResult = addReferenceIncludes(options, model, references || []);\n includedReferences = refResult.includedReferences;\n options = refResult.options;\n const aggResult = addAggregationIncludes(options, model, aggregations || []);\n includedAggregations = aggResult.includedAggregations;\n options = aggResult.options;\n\n logger.debug(`[GET] Empty loc array detected - finding by primary key across all locations: ${comKey.pk}`);\n logger.trace(`[GET] Executing ${model.name}.findByPk() with pk: ${comKey.pk}, ${includedReferences.length} reference includes, and ${includedAggregations.length} aggregation includes`);\n queryMetrics.recordQuery(model.name);\n item = options.include && options.include.length > 0\n ? await model.findByPk(comKey.pk, { include: options.include })\n : await model.findByPk(comKey.pk);\n } else {\n // This is a composite key with location context, build a where clause based on the locators\n let queryOptions = processCompositeKey(comKey, model, kta);\n\n // Add reference and aggregation includes to the query\n const refResult = addReferenceIncludes(queryOptions, model, references || []);\n includedReferences = refResult.includedReferences;\n queryOptions = refResult.options;\n const aggResult = addAggregationIncludes(queryOptions, model, aggregations || []);\n includedAggregations = aggResult.includedAggregations;\n queryOptions = aggResult.options;\n\n logger.default('Composite key query', { queryOptions });\n logger.trace(`[GET] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}, ${includedReferences.length} reference includes, and ${includedAggregations.length} aggregation includes`);\n queryMetrics.recordQuery(model.name);\n item = await model.findOne(queryOptions);\n }\n }\n\n if (!item) {\n throw new NotFoundError(\n `${kta[0]} not found`,\n kta[0],\n key\n );\n }\n\n // Use current context if available (prevents infinite recursion in reference loading)\n // This ensures proper circular dependency detection within the same operation\n const currentContext = contextManager.getCurrentContext();\n const result = validateKeys(await processRow(item, kta, references || [], aggregations || [], registry, currentContext, includedAggregations, includedReferences), kta) as V;\n\n logger.debug(`[GET] Retrieved ${model.name} with key: ${(result as any).key ? JSON.stringify((result as any).key) : `id=${item.id}`}`);\n return result;\n } catch (error: any) {\n // Transform database errors but pass through NotFoundError\n if (error instanceof NotFoundError) throw error;\n throw transformSequelizeError(error, kta[0], key);\n }\n }\n );\n}\n", "/* eslint-disable indent */\nimport { createOneWrapper, Item, ItemQuery, LocKeyArray, OneMethod } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport LibLogger from '../logger';\nimport { ModelStatic } from \"sequelize\";\nimport { getAllOperation } from \"./all\";\nimport * as Library from \"@fjell/lib\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'one');\n\nexport const getOneOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n): OneMethod<V, S, L1, L2, L3, L4, L5> => {\n return createOneWrapper(\n definition.coordinate,\n async (\n itemQuery?: ItemQuery,\n locations?: LocKeyArray<L1, L2, L3, L4, L5> | []\n ): Promise<V | null> => {\n const locs = locations ?? [];\n logger.debug(`ONE operation called on ${models[0].name} with ${locs.length} location filters: ${locs.map(loc => `${loc.kt}=${loc.lk}`).join(', ') || 'none'}`);\n logger.default(`One configured for ${models[0].name} delegating to all operation`);\n\n const result = await getAllOperation(models, definition, registry)(itemQuery ?? {}, locs, { limit: 1 });\n if (result.items.length > 0) {\n const item = result.items[0] as V;\n logger.debug(`[ONE] Found ${models[0].name} record with key: ${(item as any).key ? JSON.stringify((item as any).key) : 'unknown'}`);\n return item;\n } else {\n logger.debug(`[ONE] No ${models[0].name} record found`);\n return null;\n }\n }\n );\n}", "/* eslint-disable */\nimport { abbrevIK, ComKey, isComKey, isPriKey, isValidItemKey, Item, PriKey, RemoveMethod, createRemoveWrapper } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport { populateEvents } from \"../EventCoordinator\";\nimport { addKey } from \"../KeyMaster\";\nimport LibLogger from '../logger';\nimport { ModelStatic } from \"sequelize\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { stringifyJSON } from \"../util/general\";\nimport { NotFoundError } from \"@fjell/core\";\nimport { transformSequelizeError } from \"../errors/sequelizeErrorHandler\";\nimport { addRefsToSequelizeItem } from \"../processing/RefsAdapter\";\nimport { queryMetrics } from \"../metrics/QueryMetrics\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'remove');\n\n// Helper function to process composite key and build query options\nconst processCompositeKey = (\n comKey: ComKey<any, any, any, any, any, any>,\n model: ModelStatic<any>,\n kta: string[]\n): { where: { [key: string]: any }; include?: any[] } => {\n const where: { [key: string]: any } = { id: comKey.pk };\n const includes: any[] = [];\n\n for (const locator of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locator.kt, kta);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Composite key locator '${locator.kt}' cannot be resolved on model '${model.name}' or through its relationships.`;\n logger.error(errorMessage, { key: comKey, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.path) {\n // This requires a relationship traversal\n where[relationshipInfo.path] = locator.lk;\n if (relationshipInfo.includes) {\n includes.push(...relationshipInfo.includes);\n }\n } else {\n // This is a direct field\n const fieldName = `${locator.kt}Id`;\n where[fieldName] = locator.lk;\n }\n }\n\n const result: { where: { [key: string]: any }; include?: any[] } = { where };\n if (includes.length > 0) {\n result.include = includes;\n }\n\n return result;\n};\n\nexport const getRemoveOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n _registry: import('@fjell/lib').Registry\n): RemoveMethod<V, S, L1, L2, L3, L4, L5> => {\n const { coordinate, options } = definition;\n const { kta } = coordinate;\n\n return createRemoveWrapper(\n coordinate,\n async (key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>): Promise<V> => {\n try {\n if (!isValidItemKey(key)) {\n logger.error('Key for Remove is not a valid ItemKey: %j', key);\n throw new Error('Key for Remove is not a valid ItemKey');\n }\n\n const keyDescription = isPriKey(key)\n ? `primary key: pk=${key.pk}`\n : `composite key: pk=${key.pk}, loc=[${(key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')}]`;\n logger.debug(`REMOVE operation called on ${models[0].name} with ${keyDescription}`);\n logger.default(`Remove configured for ${models[0].name} with ${isPriKey(key) ? 'primary' : 'composite'} key`);\n\n // @ts-ignore\n const model = models[0];\n\n let item;\n let returnItem;\n\n logger.debug('remove: %s', abbrevIK(key));\n if (isPriKey(key)) {\n logger.debug(`[REMOVE] Executing ${model.name}.findByPk() with pk: ${(key as PriKey<S>).pk}`);\n queryMetrics.recordQuery(model.name);\n item = await model.findByPk((key as PriKey<S>).pk);\n } else if (isComKey(key)) {\n // This is a composite key, so we need to build a where clause based on the composite key's locators\n const comKey = key as ComKey<S, L1, L2, L3, L4, L5>;\n const queryOptions = processCompositeKey(comKey, model, kta);\n\n logger.default(`Remove composite key query for ${model.name} with where fields: ${queryOptions.where ? Object.keys(queryOptions.where).join(', ') : 'none'}`);\n logger.debug(`[REMOVE] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}`);\n queryMetrics.recordQuery(model.name);\n item = await model.findOne(queryOptions);\n }\n\n if (!item) {\n throw new NotFoundError(\n `Cannot remove: ${kta[0]} not found`,\n kta[0],\n key\n );\n }\n\n const isDeletedAttribute = model.getAttributes().isDeleted;\n const deletedAtAttribute = model.getAttributes().deletedAt;\n\n if (isDeletedAttribute || deletedAtAttribute) {\n if (model.getAttributes().isDeleted) {\n item.isDeleted = true;\n }\n\n if (model.getAttributes().deletedAt) {\n item.deletedAt = new Date();\n }\n\n // Save the object\n logger.debug(`[REMOVE] Executing ${model.name}.save() for soft delete`);\n queryMetrics.recordQuery(model.name);\n await item?.save();\n returnItem = item?.get({ plain: true }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n returnItem = addKey(item, returnItem as any, kta);\n returnItem = populateEvents(returnItem);\n } else if (options.deleteOnRemove) {\n logger.debug(`[REMOVE] Executing ${model.name}.destroy() for hard delete`);\n queryMetrics.recordQuery(model.name);\n await item?.destroy();\n returnItem = item?.get({ plain: true }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n returnItem = addKey(item, returnItem as any, kta);\n returnItem = populateEvents(returnItem);\n } else {\n throw new Error('No deletedAt or isDeleted attribute found in model, and deleteOnRemove is not set');\n }\n\n logger.debug(`[REMOVE] Removed ${model.name} with key: ${(returnItem as any).key ? JSON.stringify((returnItem as any).key) : `id=${item.id}`}`);\n \n // Automatically add refs structure before returning (transparent wrapper)\n const { references } = options;\n if (references && references.length > 0) {\n returnItem = addRefsToSequelizeItem(returnItem as any, references);\n }\n \n return returnItem as V;\n } catch (error: any) {\n // Transform database errors but pass through NotFoundError\n if (error instanceof NotFoundError) throw error;\n throw transformSequelizeError(error, kta[0], key);\n }\n }\n );\n}\n", "/* eslint-disable indent */\n/* eslint-disable max-depth */\nimport {\n abbrevIK,\n ComKey,\n createUpdateWrapper,\n isComKey,\n isPriKey,\n Item,\n PriKey,\n UpdateMethod,\n UpdateOptions\n} from \"@fjell/core\";\nimport { validateKeys } from \"@fjell/core/validation\";\n\nimport { Definition } from \"../Definition\";\nimport { extractEvents, removeEvents } from \"../EventCoordinator\";\nimport { removeKey } from \"../KeyMaster\";\nimport LibLogger from '../logger';\nimport { processRow } from \"../RowProcessor\";\n\nimport * as Library from \"@fjell/lib\";\nimport { NotFoundError } from \"@fjell/core\";\nimport { ModelStatic, Op } from \"sequelize\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { stringifyJSON } from \"../util/general\";\nimport { transformSequelizeError } from \"../errors/sequelizeErrorHandler\";\nimport { removeRefsFromSequelizeItem } from \"../processing/RefsAdapter\";\nimport { removeAggsFromItem } from \"../processing/AggsAdapter\";\nimport { queryMetrics } from \"../metrics/QueryMetrics\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'update');\n\n// Helper function to merge includes avoiding duplicates\nconst mergeIncludes = (existingIncludes: any[], newIncludes: any[]): any[] => {\n const mergedIncludes = [...existingIncludes];\n\n for (const newInclude of newIncludes) {\n const existingIndex = mergedIncludes.findIndex(\n (existing: any) => existing.as === newInclude.as && existing.model === newInclude.model\n );\n if (existingIndex === -1) {\n mergedIncludes.push(newInclude);\n } else if (newInclude.include && mergedIncludes[existingIndex].include) {\n mergedIncludes[existingIndex].include = [\n ...mergedIncludes[existingIndex].include,\n ...newInclude.include\n ];\n } else if (newInclude.include) {\n mergedIncludes[existingIndex].include = newInclude.include;\n }\n }\n\n return mergedIncludes;\n};\n\nexport const getUpdateOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n\n registry: Library.Registry\n): UpdateMethod<V, S, L1, L2, L3, L4, L5> => {\n\n const { options: { references, aggregations } } = definition;\n\n return createUpdateWrapper(\n definition.coordinate,\n async (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?: UpdateOptions\n ): Promise<V> => {\n try {\n // Check for unsupported replace option\n if (options?.replace) {\n throw new Error(\n 'UpdateOptions.replace is not supported for SQL databases. ' +\n 'SQL UPDATE operations are always partial (they only update specified fields). ' +\n 'To replace an entire record, use remove() followed by create(), ' +\n 'or explicitly set all fields you want to change/clear.'\n );\n }\n \n const keyDescription = isPriKey(key)\n ? `primary key: pk=${key.pk}`\n : `composite key: pk=${key.pk}, loc=[${(key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')}]`;\n logger.debug(`UPDATE operation called on ${models[0].name} with ${keyDescription}`, { options });\n const { coordinate } = definition;\n const { kta } = coordinate;\n\n logger.debug('update: %s, %j', abbrevIK(key), item);\n // Find the object we're updating\n // @ts-ignore\n const model = models[0];\n\n let response;\n\n if (isPriKey(key)) {\n // Find the model by using the PK\n const priKey = key as PriKey<S>;\n logger.trace(`[UPDATE] Executing ${model.name}.findByPk() with pk: ${priKey.pk}`);\n queryMetrics.recordQuery(model.name);\n response = await model.findByPk(priKey.pk);\n } else if (isComKey(key)) {\n const comKey = key as ComKey<S, L1, L2, L3, L4, L5>;\n\n // Build query options for composite key with multiple location keys\n const where: { [key: string]: any } = { id: comKey.pk };\n const additionalIncludes: any[] = [];\n\n // Process all location keys in the composite key\n for (const locator of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locator.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Composite key locator '${locator.kt}' cannot be resolved on model '${model.name}' or through its relationships.`;\n logger.error(errorMessage, { key: comKey, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n // Direct foreign key field\n const fieldName = `${locator.kt}Id`;\n where[fieldName] = locator.lk;\n } else if (relationshipInfo.path) {\n // Hierarchical relationship requiring traversal\n where[relationshipInfo.path] = {\n [Op.eq]: locator.lk\n };\n\n // Add necessary includes for relationship traversal\n if (relationshipInfo.includes) {\n additionalIncludes.push(...relationshipInfo.includes);\n }\n }\n }\n\n // Build final query options\n const queryOptions: any = { where };\n if (additionalIncludes.length > 0) {\n queryOptions.include = mergeIncludes([], additionalIncludes);\n }\n\n logger.default(`Update composite key query for ${model.name} with where fields: ${queryOptions.where ? Object.keys(queryOptions.where).join(', ') : 'none'}`);\n logger.trace(`[UPDATE] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}`);\n queryMetrics.recordQuery(model.name);\n response = await model.findOne(queryOptions);\n }\n\n if (!response) {\n throw new NotFoundError(\n `Cannot update: ${kta[0]} not found`,\n kta[0],\n key\n );\n }\n\n // Remove the key and events\n let updateProps = removeKey(item)\n // TODO: We need the opposite of processRow, something to step down from fjell to database.\n updateProps = extractEvents(updateProps);\n updateProps = removeEvents(updateProps);\n \n // Remove refs structure if present (convert back to foreign key columns)\n if (references && references.length > 0) {\n updateProps = removeRefsFromSequelizeItem(updateProps, references);\n }\n \n // Remove aggs structure if present (convert back to direct properties)\n if (aggregations && aggregations.length > 0) {\n updateProps = removeAggsFromItem(updateProps, aggregations);\n }\n\n logger.default(`Update found ${model.name} record to modify`);\n logger.default(`Update properties configured: ${Object.keys(updateProps).join(', ')}`);\n\n // Update the object\n logger.trace(`[UPDATE] Executing ${model.name}.update() with properties: ${stringifyJSON(updateProps)}`);\n queryMetrics.recordQuery(model.name);\n response = await response.update(updateProps);\n\n // Populate the key and events\n // Update operations get their own context since they're top-level operations\n // For update, we don't pre-load aggregations via INCLUDE, so pass void 0\n const processedItem = await processRow(response, kta, references || [], aggregations || [], registry, void 0, void 0);\n const returnItem = validateKeys(processedItem, kta);\n\n logger.debug(`[UPDATE] Updated ${model.name} with key: ${(returnItem as any).key ? JSON.stringify((returnItem as any).key) : `id=${response.id}`}`);\n return returnItem as V;\n } catch (error: any) {\n // Transform database errors but pass through NotFoundError\n if (error instanceof NotFoundError) throw error;\n throw transformSequelizeError(error, definition.coordinate.kta[0], key);\n }\n }\n );\n}\n", "/* eslint-disable indent */\nimport { ComKey, createUpsertWrapper, isValidItemKey, Item, LocKeyArray, NotFoundError, PriKey, UpdateOptions, UpsertMethod } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport LibLogger from '../logger';\nimport * as Library from \"@fjell/lib\";\nimport { ModelStatic } from \"sequelize\";\nimport { getGetOperation } from \"./get\";\nimport { getUpdateOperation } from \"./update\";\nimport { getCreateOperation } from \"./create\";\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'upsert');\n\nexport const getUpsertOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: Array<ModelStatic<any>>,\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n): UpsertMethod<V, S, L1, L2, L3, L4, L5> => {\n\n // Get the individual operations we'll use\n const get = getGetOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n const update = getUpdateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n const create = getCreateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n\n return createUpsertWrapper(\n definition.coordinate,\n async (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n locations?: LocKeyArray<L1, L2, L3, L4, L5>,\n options?: UpdateOptions\n ): Promise<V> => {\n if (!isValidItemKey(key)) {\n logger.error('Invalid key for upsert operation', {\n operation: 'upsert',\n model: models[0]?.name,\n key: stringifyJSON(key),\n keyType: typeof key,\n reason: 'Key validation failed',\n suggestion: 'Ensure key has valid PriKey or ComKey structure',\n coordinate: JSON.stringify(definition.coordinate)\n });\n throw new Error(`Invalid key for upsert operation: ${stringifyJSON(key)}. Expected valid PriKey or ComKey structure.`);\n }\n\n logger.debug(`[UPSERT] Attempting upsert with key: ${stringifyJSON(key)}`, { options });\n\n let resultItem: V | null = null;\n\n try {\n // Try to get the existing item first\n logger.debug(`[UPSERT] Retrieving item by key: ${stringifyJSON(key)}`);\n resultItem = await get(key);\n } catch (error: any) {\n // Check if this is a NotFoundError (preserved by core wrapper)\n // Check both instanceof and error code to handle cases where\n // module duplication might break instanceof checks\n const isNotFound = error instanceof NotFoundError ||\n error?.name === 'NotFoundError' ||\n error?.errorInfo?.code === 'NOT_FOUND';\n\n if (isNotFound) {\n // Item doesn't exist, create it\n logger.debug(`[UPSERT] Item not found, creating new item with key: ${stringifyJSON(key)}, errorType: ${error?.name}, errorCode: ${error?.errorInfo?.code}`);\n const createOptions = locations ? { locations } : { key };\n resultItem = await create(item, createOptions);\n } else {\n // Re-throw other errors (connection issues, permissions, etc.)\n logger.error(`[UPSERT] Unexpected error during get operation`, {\n operation: 'upsert',\n phase: 'get-existing',\n model: models[0]?.name,\n key: stringifyJSON(key),\n errorType: error?.constructor?.name || typeof error,\n errorMessage: error?.message,\n errorName: error?.name,\n errorCode: error?.errorInfo?.code,\n suggestion: 'Check database connectivity, permissions, and key validity',\n coordinate: JSON.stringify(definition.coordinate)\n });\n throw error;\n }\n }\n\n if (!resultItem) {\n throw new Error(`Failed to retrieve or create item for key: ${stringifyJSON(key)}`);\n }\n\n // Always update the item with the new properties (this is what makes it an \"upsert\")\n // Pass through UpdateOptions to control merge vs replace behavior\n logger.debug(`[UPSERT] Updating item with properties, key: ${stringifyJSON(key)}`, { options });\n resultItem = await update(resultItem.key, item, options);\n logger.debug(`[UPSERT] Item upserted successfully: ${stringifyJSON(resultItem)}`);\n\n return resultItem;\n }\n );\n}\n", "import { Coordinate, Item } from \"@fjell/core\";\nimport { Options } from \"./Options\";\nimport { Registry as LocalRegistry } from \"./Registry\";\nimport { InstanceFactory as BaseInstanceFactory, Registry as BaseRegistry, RegistryHub } from \"@fjell/registry\";\nimport { createSequelizeLibrary, SequelizeLibrary } from \"./SequelizeLibrary\";\nimport { ModelStatic } from \"sequelize\";\nimport SequelizeLogger from \"./logger\";\n\nconst logger = SequelizeLogger.get(\"InstanceFactory\");\n\n/**\n * Sequelize Library Factory type that extends the base factory\n * to include Sequelize-specific models parameter\n */\nexport type SequelizeLibraryFactory<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> = (\n models: ModelStatic<any>[],\n options: Options<V, S, L1, L2, L3, L4, L5>\n) => BaseInstanceFactory<S, L1, L2, L3, L4, L5>;\n\n/**\n * Factory function for creating Sequelize libraries\n * This extends the fjell-lib pattern by adding Sequelize-specific models\n */\nexport const createSequelizeLibraryFactory = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n options: Options<V, S, L1, L2, L3, L4, L5>\n ): BaseInstanceFactory<S, L1, L2, L3, L4, L5> => {\n return (coordinate: Coordinate<S, L1, L2, L3, L4, L5>, context: { registry: BaseRegistry, registryHub?: RegistryHub }) => {\n logger.debug(\"Creating Sequelize instance\", {\n coordinate,\n registry: context.registry,\n models: models.map(m => m.name),\n options\n });\n\n return createSequelizeLibrary<V, S, L1, L2, L3, L4, L5>(\n context.registry as LocalRegistry,\n coordinate,\n models,\n options\n ) as SequelizeLibrary<V, S, L1, L2, L3, L4, L5>;\n };\n};\n", "export * from './SequelizeLibrary';\n", "\nimport { SequelizeLibrary as AbstractSequelizeLibrary } from '../SequelizeLibrary';\nimport { Item, ItemTypeArray } from '@fjell/core';\nimport { Contained } from '@fjell/lib';\nimport * as Library from '@fjell/lib';\nimport { createOperations } from '../Operations';\nimport { ModelStatic } from 'sequelize';\nimport { Registry } from '../Registry';\nimport { createOptions, Options } from '../Options';\nimport { Coordinate, createCoordinate } from '../Coordinate';\n\nexport interface SequelizeLibrary<\n V extends Item<S>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> extends AbstractSequelizeLibrary<V, S, L1, L2, L3, L4, L5> {\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>;\n registry: Registry;\n operations: Library.Operations<V, S, L1, L2, L3, L4, L5>;\n options: Options<V, S, L1, L2, L3, L4, L5>;\n models: ModelStatic<any>[];\n}\n\nexport function createSequelizeLibrary<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n keyTypes: ItemTypeArray<S, L1, L2, L3, L4, L5>,\n models: ModelStatic<any>[],\n libOptions: Partial<Options<V, S, L1, L2, L3, L4, L5>> = {},\n scopes: string[] = [],\n registry: Registry\n): SequelizeLibrary<V, S, L1, L2, L3, L4, L5> {\n\n // Create coordinate and options separately following new pattern\n const coordinate = createCoordinate(keyTypes, scopes);\n const options = createOptions(libOptions);\n\n // Create operations with the new signature\n const operations = createOperations<V, S, L1, L2, L3, L4, L5>(models, coordinate, registry, options);\n\n // Wrap operations for contained pattern\n const wrappedOperations = Contained.wrapOperations(operations, options as any, coordinate, registry);\n\n return {\n coordinate,\n registry,\n operations: wrappedOperations,\n options,\n models,\n } as unknown as SequelizeLibrary<V, S, L1, L2, L3, L4, L5>;\n}\n", "export * from './SequelizeLibrary';\n", "\nimport { SequelizeLibrary as AbstractSequelizeLibrary } from '../SequelizeLibrary';\nimport { Item } from '@fjell/core';\nimport { Primary } from '@fjell/lib';\nimport * as Library from '@fjell/lib';\nimport { createOperations } from '../Operations';\nimport { ModelStatic } from 'sequelize';\nimport { createOptions, Options } from '../Options';\nimport { Registry } from '../Registry';\nimport { Coordinate, createCoordinate } from '../Coordinate';\n\nimport LibLogger from '../logger';\n\nconst logger = LibLogger.get('lib-sequelize', 'primary', 'library');\n\nexport interface SequelizeLibrary<\n V extends Item<S>,\n S extends string\n> extends AbstractSequelizeLibrary<V, S> {\n coordinate: Coordinate<S>;\n registry: Registry;\n operations: Library.Operations<V, S>;\n options: Options<V, S>;\n models: ModelStatic<any>[];\n}\n\nexport function createSequelizeLibrary<\n V extends Item<S>,\n S extends string\n>(\n keyType: S,\n models: ModelStatic<any>[],\n libOptions: Partial<Options<V, S>> = {},\n scopes: string[] = [],\n registry: Registry\n): SequelizeLibrary<V, S> {\n logger.debug('createSequelizeLibrary', { keyType, models, libOptions, scopes });\n\n // Create coordinate and options separately following new pattern\n const coordinate = createCoordinate([keyType], scopes);\n const options = createOptions(libOptions);\n\n // Create operations with the new signature\n const operations = createOperations<V, S>(models, coordinate, registry, options);\n\n // Wrap operations for primary pattern\n const wrappedOperations = Primary.wrapOperations(operations, options as any, coordinate, registry);\n\n return {\n coordinate,\n registry,\n operations: wrappedOperations,\n options,\n models,\n } as unknown as SequelizeLibrary<V, S>;\n}\n"],
5
+ "mappings": ";;;;;;;AAAA,YAAY,aAAa;AAkFlB,IAAMA,iBAAgB,CAQ3B,qBAA4F;AAE5F,QAAM,EAAE,YAAY,gBAAgB,GAAG,qBAAqB,IAAI,oBAAoB,CAAC;AAGrF,QAAM,cAAsB,sBAAc,oBAAiE;AAG3G,SAAO;AAAA,IACL,GAAG;AAAA,IAC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C,QAAM,aAAa,iBAA2C,QAAQ,YAAY,UAAU,OAAO;AAGnG,QAAM,oBAAoB,UAAU,eAAe,YAAY,SAAgB,YAAY,QAAQ;AAEnG,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,EACF;AACF;;;AC5DA;AAAA;AAAA,gCAAAC;AAAA;;;ACGA,SAAS,eAAe;AAUxB,IAAMC,WAAS,eAAU,IAAI,iBAAiB,WAAW,SAAS;AAa3D,SAASC,wBAId,SACA,QACA,aAAqC,CAAC,GACtC,SAAmB,CAAC,GACpB,UACwB;AACxB,EAAAD,SAAO,MAAM,0BAA0B,EAAE,SAAS,QAAQ,YAAY,OAAO,CAAC;AAG9E,QAAM,aAAa,iBAAiB,CAAC,OAAO,GAAG,MAAM;AACrD,QAAM,UAAUE,eAAc,UAAU;AAGxC,QAAM,aAAa,iBAAuB,QAAQ,YAAY,UAAU,OAAO;AAG/E,QAAM,oBAAoB,QAAQ,eAAe,YAAY,SAAgB,YAAY,QAAQ;AAEjG,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,EACF;AACF;",
6
+ "names": ["createOptions", "logger", "createOptions", "Library", "Library", "logger", "attributeName", "sequelizeAssociationColumn", "conditionOp", "result", "logger", "foreignKeyField", "logger", "logger", "libLogger", "isComKey", "isPriKey", "isPriKey", "isComKey", "libLogger", "logger", "logger", "Op", "logger", "logger", "logger", "loc", "Op", "isComKey", "isPriKey", "validateKeys", "logger", "record", "isComKey", "isPriKey", "validateKeys", "validateKeys", "logger", "validateKeys", "processedResults", "isComKey", "isPriKey", "validateKeys", "logger", "isPriKey", "isComKey", "validateKeys", "logger", "isComKey", "isPriKey", "isValidItemKey", "NotFoundError", "logger", "processCompositeKey", "isValidItemKey", "isPriKey", "isComKey", "NotFoundError", "abbrevIK", "isComKey", "isPriKey", "validateKeys", "NotFoundError", "Op", "logger", "mergeIncludes", "isPriKey", "abbrevIK", "isComKey", "Op", "NotFoundError", "validateKeys", "isValidItemKey", "NotFoundError", "logger", "isValidItemKey", "NotFoundError", "createOptions", "logger", "logger", "createSequelizeLibrary", "createSequelizeLibrary", "createOptions", "createSequelizeLibrary", "logger", "createSequelizeLibrary", "createOptions"]
7
7
  }