@wildo-ai/saas-backend-lib 1.1.6 → 1.1.8

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.
@@ -1 +1 @@
1
- {"version":3,"file":"zod-to-mongoose-schema-convertor.backend.service.js","sourceRoot":"","sources":["../../../../../src/databases/services/zod-to-mongoose-schema-convertor.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,MAAM,EAA+B,KAAK,EAAE,MAAM,UAAU,CAAC;AACtE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,gCAAgC,EAAE,MAAM,8EAA8E,CAAC;AAChI,OAAO,EAKL,SAAS,EACT,2BAA2B,EAC3B,sCAAsC,GAGvC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,yCAAyC,EACzC,2BAA2B,EAC3B,2BAA2B,EAC3B,iCAAiC,GAElC,MAAM,wEAAwE,CAAC;AAGhF,OAAO,EACL,SAAS,EACT,kBAAkB,EAClB,WAAW,EACX,UAAU,EAGV,UAAU,EACV,aAAa,EACb,aAAa,EACb,YAAY,EACZ,uBAAuB,EACvB,sBAAsB,EACtB,uBAAuB,EACvB,yBAAyB,EACzB,iBAAiB,EACjB,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,WAAW,EACX,UAAU,EACV,oBAAoB,EACpB,UAAU,EACV,iBAAiB,EACjB,YAAY,EACZ,SAAS,EACT,YAAY,EACZ,WAAW,EAEX,WAAW,EACX,YAAY,EACZ,YAAY,EACZ,aAAa,EACb,QAAQ,EACR,eAAe,EAEf,YAAY,EACZ,MAAM,EACN,YAAY,EAEZ,uBAAuB,GACxB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EACL,sBAAsB,EACtB,0BAA0B,EAC1B,mBAAmB,EACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,E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nimport { Schema, Model, Document, Connection, Types } from 'mongoose';\nimport { z } from 'zod';\nimport { DATA_SEED_ROW_METADATA_FIELD_KEY } from '~wildo-backend-lib/data-seeding/models/data-seed-row-metadata.shared.schemas';\nimport {\n ResourceConfiguration,\n ResourceType,\n\n CoreResourceOperation,\n ErrorType,\n ErrorCustomMessageReference,\n resolveSharedPersistenceCollectionName,\n type ResourceRelationship,\n type RelationshipPersistenceForeignKeyContract,\n} from '@wildo-ai/saas-models';\nimport {\n buildRetentionVisibleRowsEqualityFragment,\n getVisibleRetentionStatuses,\n isRetentionGovernedResource,\n resolveSoleVisibleRetentionStatus,\n type RetentionGovernanceSignal,\n} from '~wildo-backend-lib/compliance/privacy/retention-hide-predicate.backend';\n\n\nimport {\n isZodPipe,\n getPipeInputSchema,\n isZodObject,\n getZodType,\n EnumLikeType,\n hasZodType,\n isZodArray,\n isZodOptional,\n isZodNullable,\n isZodDefault,\n getZodDefSchemaProperty,\n getZodDefArrayProperty,\n getZodDefStringProperty,\n getZodDefFunctionProperty,\n getZodDefProperty,\n getZodObjectShape,\n isVirtualField,\n isZodTransform,\n isZodCustom,\n isZodTuple,\n isDiscriminatedUnion,\n isZodUnion,\n isZodIntersection,\n isZodLiteral,\n isZodLazy,\n isZodTypeAny,\n isZodRecord,\n isZodSet,\n isDBIndexed,\n isForeignKey,\n unwrapSchema,\n getEnumValues,\n isUnique,\n getUniqueParams,\n UniqueFieldParams,\n isPrimaryKey,\n hasTtl,\n getTtlParams,\n TtlFieldParams,\n getBusinessKeySetParams,\n} from '@wildo-ai/zod-decorators';\n\nimport {\n SCHEMA_DEFAULT_OPTIONS,\n SCHEMA_SUBDOCUMENT_OPTIONS,\n initModelFromSchema\n} from './db-utils';\n\nimport { SAAS_SERVICE_TYPES } from '~wildo-backend-lib/inject/models/service-types';\nimport { LoggerService } from '~wildo-backend-lib/monitoring/logger/services/logger.service';\nimport { ErrorBuilderBackendService } from '~wildo-backend-lib/errors/services/error-builder.backend.service';\nimport { describeCaughtError } from '~wildo-backend-lib/errors/utils/error-log-level-classification.backend.utils';\nimport { REPOSITORY_ROW_IDENTITY_FIELD } from '~wildo-backend-lib/base-classes/services/repositories/repository-total-order.backend';\n\n\n/**\n * Interface for union inheritance schema information (not model instances)\n * Represents different inheritance options in a discriminated union\n */\nexport interface UnionInheritance_SchemaInfo {\n discriminatorKey: string;\n discriminatorValue: string;\n schema: Schema;\n zodSchema: z.ZodTypeAny;\n}\n\n/**\n * Options for schema conversion\n */\nexport interface SchemaConversionOptions {\n includeIndexes?: boolean;\n applyDefaults?: boolean;\n maxDepth?: number;\n connection?: Connection; // optional connection to bind model creation\n /**\n * The resource's TOP-LEVEL foreign-key fields whose relationship names a VIRTUAL (`HTTP_API`) resource (#1939) —\n * `resolveVirtualTargetForeignKeyFields`. Each is stored as a STRING, the target's synthesized key, instead of an\n * `ObjectId`. Absent or empty is the ordinary case, and then the conversion is byte-for-byte what it always was: every\n * `.isForeignKey()` field is an `ObjectId` path with the same index. Decided here, once, from the declaration; nothing\n * downstream converts a value.\n */\n virtualTargetForeignKeyFields?: ReadonlySet<string>;\n}\n\n/**\n * Info for unique index application\n */\nexport interface UniqueIndexInfo {\n path: string;\n params: UniqueFieldParams;\n}\n\n/**\n * Info for TTL (Time To Live) index application.\n * MongoDB will automatically delete documents when the TTL expires.\n */\nexport interface TtlIndexInfo {\n path: string;\n params: TtlFieldParams;\n}\n\n/**\n * Interface for generated model information (for debugging)\n */\nexport interface GeneratedModelInfo {\n resourceType: ResourceType;\n modelName: string;\n mainModel: Model<any & Document>;\n inheritanceSchemas: UnionInheritance_SchemaInfo[];\n inheritanceModels: Model<any & Document>[];\n schemaFieldCount: number;\n indexCount: number;\n conversionOptions: SchemaConversionOptions;\n createdAt: Date;\n}\n\n/**\n * Debug statistics for model generation\n */\nexport interface ModelGenerationStats {\n totalResources: number;\n totalMainModels: number;\n totalInheritanceModels: number;\n totalSchemaFields: number;\n totalIndexes: number;\n resourceTypes: ResourceType[];\n conversionTime: number;\n}\n\n/**\n * Service for converting Zod schemas to Mongoose schemas\n * Handles decorators for database indexing and resource references\n * Supports discriminated unions and complex nested objects\n *\n * IMPORTANT: This service is STATELESS and does NOT create inheritance models\n * to avoid global state mutations. Use the returned schemas to create models externally.\n *\n * Features unified error handling with ErrorBuilderBackendService for schema conversion errors.\n */\n@injectable()\nexport class ZodToMongooseSchemaConvertorBackendService {\n\n // =================================================================\n // CONSTRUCTOR AND CONFIGURATION\n // =================================================================\n\n private readonly DEFAULT_MAX_DEPTH = 25;\n protected logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n /**\n * The {@link SchemaConversionOptions.virtualTargetForeignKeyFields} of the conversion in progress, held for its duration\n * only (set and cleared around the synchronous conversion in `convertZodSchemaToMongooseSchemaWithCleanup`), so the\n * recursive field conversion does not carry it through a dozen signatures. Empty outside a conversion.\n */\n private virtualTargetForeignKeyFields: ReadonlySet<string> = new Set();\n\n /**\n * The Mongoose type of a foreign-key path (#1939): `ObjectId`, unless the field's relationship names a virtual resource,\n * whose ids are synthesized strings. Keyed on the field's path from the resource root, so only a top-level field — the\n * one a relationship declares — can take the exception; a nested field of the same name keeps its `ObjectId`.\n */\n private foreignKeyStorageType(currentPath: string): typeof Schema.Types.ObjectId | StringConstructor {\n return this.virtualTargetForeignKeyFields.size > 0 && this.virtualTargetForeignKeyFields.has(currentPath)\n ? String\n : Schema.Types.ObjectId;\n }\n\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger) private logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService) private errorBuilder: ErrorBuilderBackendService\n ) {\n this.logDebug = this.logger.debugByType('ZodToMongooseSchemaConvertorBackendService');\n this.logger.setDebugTypeLogging('ZodToMongooseSchemaConvertorBackendService', false);\n }\n\n // =================================================================\n // PUBLIC API METHODS\n // =================================================================\n\n /**\n * Converts a ResourceConfiguration to a Mongoose model\n * @param resourceConfiguration The resource configuration containing the schema\n * @param options Conversion options\n * @returns Object containing the main model and union inheritance schema information\n * @throws Error if schema conversion fails\n */\n /**\n * Build the Zod schema whose fields become Mongoose paths, widening a schema-family / discriminated-\n * union resource's BASE `mainSchema` with every variant-extension field as an OPTIONAL path (union\n * across all variants, recursing nested inheritance). See the block comment at the call site for why\n * this is required (variant fields would otherwise be silently dropped on write). Returns the base\n * unchanged when there is no inheritance definition or the base is not a plain object.\n */\n private buildPersistedSchemaWithVariantFields(baseSchema: z.ZodTypeAny, inheritenceSchemaDefinition: unknown): z.ZodTypeAny {\n if (!inheritenceSchemaDefinition || !isZodObject(baseSchema)) {\n return baseSchema;\n }\n const baseShape = getZodObjectShape(baseSchema);\n const extraOptionalFields: Record<string, z.ZodTypeAny> = {};\n\n type InheritanceNode = { discriminatorField?: string; inheritedSchemas?: Array<{ schema?: unknown; inheritenceSchemaDefinition?: unknown }> };\n const collect = (node: InheritanceNode | undefined): void => {\n if (!node?.inheritedSchemas) return;\n const discriminatorField = node.discriminatorField;\n for (const entry of node.inheritedSchemas) {\n const variantSchema = entry?.schema as z.ZodTypeAny | undefined;\n if (variantSchema && isZodObject(variantSchema)) {\n const variantShape = getZodObjectShape(variantSchema);\n for (const [key, fieldSchema] of Object.entries(variantShape)) {\n if (key === discriminatorField) continue; // discriminator is already carried on the base\n if (key in baseShape) continue; // a base field is already a model path\n if (key in extraOptionalFields) continue; // union across variants — first definition wins\n // Persist the variant field as OPTIONAL: per-variant \"required\" stays enforced by Zod at the\n // DTO layer; the flat model must accept rows of every variant.\n extraOptionalFields[key] = (fieldSchema as z.ZodTypeAny).optional();\n }\n }\n if (entry?.inheritenceSchemaDefinition) {\n collect(entry.inheritenceSchemaDefinition as InheritanceNode); // multi-level inheritance\n }\n }\n };\n collect(inheritenceSchemaDefinition as InheritanceNode);\n\n if (Object.keys(extraOptionalFields).length === 0) {\n return baseSchema;\n }\n return (baseSchema as z.ZodObject<z.ZodRawShape>).extend(extraOptionalFields);\n }\n\n /**\n * NOTE: TDatabaseSchema has been removed. Backend-only fields are now marked with\n * the `isBackendOnly` decorator on mainSchema and handled at the service layer.\n */\n convertResourceConfigurationToModel<\n TCustomOperationEnum extends EnumLikeType | undefined,\n TCoreOperationEnum extends Partial<CoreResourceOperation> | undefined,\n TMainSchema extends z.ZodTypeAny\n >(\n resourceConfiguration: ResourceConfiguration<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n options: SchemaConversionOptions = {}\n ): {\n mainModel: Model<any & Document>;\n inheritanceSchemas: UnionInheritance_SchemaInfo[];\n } {\n\n const startTime = Date.now();\n\n\n if (!resourceConfiguration) {\n const error = this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n { customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED }\n );\n throw error;\n }\n\n if (!resourceConfiguration.mainSchema) {\n const error = this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n { customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED, }\n );\n throw error;\n }\n\n // NOTE: databaseSchema was removed - mainSchema now contains all fields including backend-only (marked with isBackendOnly decorator)\n //\n // SCHEMA-FAMILY / DISCRIMINATED-UNION SUPERSET: for an inheritance resource, `mainSchema` is the\n // BASE schema only (a plain z.object). The variant-extension fields (e.g. a recurring todo's\n // `recurrence`/`startDate`/`endsDate`) live only in `inheritenceSchemaDefinition`, so if we convert\n // the bare base, Mongoose has no path for them and SILENTLY DROPS them on write — and the read-back\n // then fails the per-variant `transformOutput` (which requires them), surfacing as a 500\n // `service_resource_transformation_failed`. We therefore persist a SUPERSET model: the base plus\n // every variant-extension field as an OPTIONAL path (union across all variants, recursing nested\n // inheritance). This is the top-level analogue of the already-blessed\n // `flattenDiscriminatedUnionForSubdocument` strategy — ONE flat collection, NO Mongoose\n // discriminators, with per-variant \"required\" still enforced by Zod at the DTO layer. `mainSchema`\n // itself is left untouched (DTOs are built from it + the union elsewhere); this only widens the\n // persisted model. A resource with no inheritance (the common case) is entirely unchanged.\n const schemaToConvert = this.buildPersistedSchemaWithVariantFields(resourceConfiguration.mainSchema, (resourceConfiguration as { inheritenceSchemaDefinition?: unknown }).inheritenceSchemaDefinition);\n const modelLabel = resourceConfiguration.resourceIdentifier as string;\n\n\n\n // Get the collection name (may be different from model name for USER_SELF_* resources)\n const collectionName = this.getCollectionNameForResource(resourceConfiguration.resourceIdentifier);\n\n if (!modelLabel) {\n const error = this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n { customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED }\n );\n throw error;\n }\n\n try {\n // Convert Zod schema to Mongoose schema with clean state\n const conversionResult = this.convertZodSchemaToMongooseSchemaWithCleanup(\n schemaToConvert,\n options,\n resourceConfiguration\n );\n\n // Initialize main model with custom collection name if different from model name and optional connection\n const mainModel = initModelFromSchema(\n conversionResult.mongooseSchema,\n modelLabel,\n collectionName,\n options.connection\n );\n\n // Fail loud if a stale model registered under this name shadows the surrogate-PK reshape.\n this.assertSurrogatePrimaryKeyVirtualsBound(schemaToConvert, mainModel, modelLabel);\n\n // Log debug information if debug logging is enabled\n this.logDebug(`Converted schema for resource '${modelLabel}'`, {\n resourceType: resourceConfiguration.resourceIdentifier,\n modelName: modelLabel,\n schemaFieldCount: this.countSchemaFields(conversionResult.mongooseSchema),\n indexCount: conversionResult.mongooseSchema.indexes().length,\n inheritanceCount: conversionResult.inheritanceSchemas.length,\n conversionTime: Date.now() - startTime,\n conversionOptions: options\n });\n\n return {\n mainModel,\n inheritanceSchemas: conversionResult.inheritanceSchemas\n };\n } catch (error) {\n const conversionError = this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED,\n context: {\n resourceType: resourceConfiguration.resourceIdentifier,\n modelLabel,\n originalError: describeCaughtError(error)\n }\n }\n );\n throw conversionError;\n }\n }\n\n /**\n * Creates a Mongoose model directly from a Zod schema (utility method)\n * @param zodSchema The Zod schema\n * @param modelName The name for the model\n * @param options Conversion options\n * @returns Object containing the main model and union inheritance schemas\n * @throws Error if schema conversion fails\n */\n createModelFromZodSchema(\n zodSchema: z.ZodTypeAny,\n modelName: string,\n options: SchemaConversionOptions = {}\n ): {\n mainModel: Model<any & Document>;\n inheritanceSchemas: UnionInheritance_SchemaInfo[];\n } {\n\n if (!zodSchema) {\n const error = this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n { customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED }\n );\n throw error;\n }\n\n if (!modelName || typeof modelName !== 'string') {\n const error = this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n { customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED }\n );\n throw error;\n }\n\n try {\n const conversionResult = this.convertZodSchemaToMongooseSchemaWithCleanup(zodSchema, options, undefined);\n const mainModel = initModelFromSchema(conversionResult.mongooseSchema, modelName);\n this.assertSurrogatePrimaryKeyVirtualsBound(zodSchema, mainModel, modelName);\n\n this.logDebug(`Created model from Zod schema '${modelName}'`, {\n modelName,\n schemaFieldCount: this.countSchemaFields(conversionResult.mongooseSchema),\n indexCount: conversionResult.mongooseSchema.indexes().length,\n inheritanceCount: conversionResult.inheritanceSchemas.length,\n conversionOptions: options\n });\n\n return {\n mainModel,\n inheritanceSchemas: conversionResult.inheritanceSchemas\n };\n } catch (error) {\n const modelError = this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_MODEL_BUILD_FAILED,\n context: {\n modelName,\n originalError: describeCaughtError(error)\n }\n }\n );\n throw modelError;\n }\n }\n\n /**\n * Creates inheritance models from union inheritance schemas\n * This is a separate method to allow external control over model creation\n * @param unionRootModel The union root model (base for all inheritance options)\n * @param inheritanceSchemas The union inheritance schemas to create models from\n * @returns Array of created inheritance models\n */\n createInheritanceModels(\n unionRootModel: Model<any & Document>,\n inheritanceSchemas: UnionInheritance_SchemaInfo[]\n ): Model<any & Document>[] {\n\n const models: Model<any & Document>[] = [];\n\n for (const inheritanceSchema of inheritanceSchemas) {\n try {\n const inheritanceModelName = `${unionRootModel.modelName}_${inheritanceSchema.discriminatorValue}`;\n const inheritanceModel = unionRootModel.discriminator(inheritanceModelName, inheritanceSchema.schema);\n models.push(inheritanceModel);\n } catch (error) {\n this.logger.warn(`Failed to create inheritance model for value '${inheritanceSchema.discriminatorValue}': ${describeCaughtError(error)}`);\n }\n }\n\n this.logDebug(`Created inheritance models for union root model '${unionRootModel.modelName}'`, {\n unionRootModelName: unionRootModel.modelName,\n inheritanceModelsCount: models.length,\n inheritanceValues: inheritanceSchemas.map(s => s.discriminatorValue)\n });\n\n return models;\n }\n\n // =================================================================\n // MAIN CONVERSION METHODS\n // =================================================================\n\n /**\n * Find top-level fields marked `.isPrimaryKey()` whose name is not `_id` — i.e.\n * SURROGATE primary keys (the resource's external identity name for the\n * auto-generated Mongo `_id`, e.g. FILES `fileId`). Such fields are NOT stored\n * paths; they are registered as read-only virtual projections of `_id` by\n * {@link convertZodSchemaToMongooseSchemaWithCleanup}.\n *\n * Only the top-level object shape is inspected (a primary key is a top-level\n * concern). `_id` itself is excluded — it is the canonical key, handled natively.\n * Returns `[]` for every resource that has no custom primary key (i.e. all\n * resources except FILES today), so the rest of the conversion is unaffected.\n */\n private findSurrogatePrimaryKeyFields(zodSchema: z.ZodTypeAny): string[] {\n let objectSchema: z.ZodTypeAny = unwrapSchema(zodSchema);\n if (isZodPipe(objectSchema)) {\n objectSchema = getPipeInputSchema(objectSchema) ?? objectSchema;\n }\n if (!isZodObject(objectSchema)) {\n return [];\n }\n const shape = getZodObjectShape(objectSchema);\n const surrogateNames: string[] = [];\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n if (\n fieldName !== '_id' &&\n fieldSchema &&\n typeof fieldSchema === 'object' &&\n isPrimaryKey(fieldSchema as z.ZodTypeAny)\n ) {\n surrogateNames.push(fieldName);\n }\n }\n return surrogateNames;\n }\n\n /**\n * Defensive guard against a stale Mongoose model shadowing a surrogate-PK reshape.\n *\n * `initModelFromSchema` returns an EXISTING model registered under the same name and ignores\n * the passed schema. For a surrogate-PK resource (e.g. FILES `fileId`), a stale pre-reshape\n * model lacks the `= String(_id)` virtual — every read would then drop the surrogate from\n * responses, and `{ _id: doc.<name> }` filters (e.g. the files-cleanup batch) would become\n * `{ _id: undefined }`. The reshape's correctness silently depends on \"first-compile-wins\";\n * this makes that dependency loud. It fires only when a non-reshaped model is registered\n * first (double bootstrap / missing test isolation), never in correct single-build operation.\n */\n private assertSurrogatePrimaryKeyVirtualsBound(\n zodSchema: z.ZodTypeAny,\n mainModel: Model<any>,\n modelLabel: string,\n ): void {\n const surrogateFields = this.findSurrogatePrimaryKeyFields(zodSchema);\n for (const fieldName of surrogateFields) {\n if (!mainModel.schema?.virtuals?.[fieldName]) {\n throw new Error(\n `[ZodToMongoose] Model '${modelLabel}' is missing the surrogate primary-key virtual ` +\n `'${fieldName}' (= String(_id)). A stale Mongoose model registered under this name is ` +\n `shadowing the reshaped schema, so '${fieldName}' would be absent from every response ` +\n `and '{ _id: doc.${fieldName} }' filters would become '{ _id: undefined }'. Ensure the ` +\n `reshaped model is compiled first (model-registry caching — typically double-bootstrap ` +\n `or missing test isolation).`,\n );\n }\n }\n }\n\n /**\n * Converts a Zod schema to a Mongoose schema with proper cleanup\n * @param zodSchema The Zod schema to convert\n * @param options Conversion options\n * @returns Object containing mongoose schema and union inheritance information\n */\n private convertZodSchemaToMongooseSchemaWithCleanup(\n zodSchema: z.ZodTypeAny,\n options: SchemaConversionOptions = {},\n resourceConfiguration?: any\n ): {\n mongooseSchema: Schema;\n inheritanceSchemas: UnionInheritance_SchemaInfo[];\n } {\n\n if (!zodSchema) {\n const error = this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n { customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED }\n );\n throw error;\n }\n\n const maxDepth = options.maxDepth || this.DEFAULT_MAX_DEPTH;\n this.virtualTargetForeignKeyFields = options.virtualTargetForeignKeyFields ?? new Set();\n const processedSchemas = new WeakSet<z.ZodTypeAny>();\n const schemaCache = new WeakMap<z.ZodTypeAny, Schema>();\n const inheritanceSchemas: UnionInheritance_SchemaInfo[] = [];\n const indexesToApply: string[] = [];\n const uniqueIndexesToApply: UniqueIndexInfo[] = [];\n const ttlIndexesToApply: TtlIndexInfo[] = [];\n\n try {\n // Convert Zod schema to Mongoose schema definition\n const schemaDefinition = this.convertZodTypeToMongooseDefinition(\n zodSchema,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n '',\n 0,\n maxDepth\n );\n\n\n\n\n\n // Remove discriminatorKey from schema definition if present (it's not a valid Mongoose field type)\n // discriminatorKey is used for model-level discriminator configuration, not schema definition\n const { discriminatorKey, ...cleanSchemaDefinition } = schemaDefinition as any;\n\n // Surrogate primary keys: a top-level field marked `.isPrimaryKey()` whose name is\n // NOT `_id` is the resource's *external identity name* for the auto-generated Mongo\n // `_id` — e.g. FILES `fileId`. It must NOT be a separately-stored path (that produced\n // a second identity divergent from `_id`, and — being `excludeFromCreate` like every\n // primary key — was stripped from the create DTO yet required by Mongoose, which broke\n // every file create). Instead `_id` is the single stored identity and the surrogate\n // name is exposed as a read-only Mongoose VIRTUAL `= String(_id)`. For that virtual to\n // reach responses, virtuals MUST be enabled on this schema's `toObject`/`toJSON` — and\n // `SCHEMA_DEFAULT_OPTIONS` (db-utils) does NOT enable them (that flag lives in the\n // separate `SCHEMA_VIRTUALS_OPTIONS`). So the explicit `mongooseSchema.set('toObject' /\n // 'toJSON', { virtuals: true })` further below — gated on surrogate schemas — is\n // LOAD-BEARING: drop it and `<name>` silently disappears from every response/DTO (and\n // any `{ _id: doc.<name> }` filter, e.g. the cleanup batch, becomes `{ _id: undefined }`).\n // With it, the virtual flows into every response/DTO and `doc.<name>` reads resolve\n // through the getter — so the external `<name>` surface (DTOs, z_file references, URLs)\n // is unchanged while the resource has exactly one stored identity. (Today FILES.fileId is\n // the only such field; any future surrogate key gets the same treatment.)\n const surrogatePrimaryKeyFields = this.findSurrogatePrimaryKeyFields(zodSchema);\n for (const surrogateName of surrogatePrimaryKeyFields) {\n delete cleanSchemaDefinition[surrogateName];\n // Drop any collected index / unique index for the surrogate field. A primary key\n // contributes a UNIQUE index (see the \"already indexed via unique index\" note in\n // `convertZodFieldToMongooseField`), but the surrogate is now a non-stored virtual —\n // a unique index on the pathless field would make every document collide on `null`\n // (E11000). The identity is `_id`, which Mongo already uniquely indexes.\n for (let i = indexesToApply.length - 1; i >= 0; i--) {\n if (indexesToApply[i].replace(/\\[\\]/g, '').trim() === surrogateName) {\n indexesToApply.splice(i, 1);\n }\n }\n for (let i = uniqueIndexesToApply.length - 1; i >= 0; i--) {\n if ((uniqueIndexesToApply[i].path || '').replace(/\\[\\]/g, '').trim() === surrogateName) {\n uniqueIndexesToApply.splice(i, 1);\n }\n }\n }\n\n // CRDT field-level metadata — schemaless Mixed field for per-field LWW timestamps.\n // Only populated for resources that have isCRDT() fields.\n cleanSchemaDefinition._field_meta = { type: Schema.Types.Mixed };\n\n // Every resource can receive repository-owned seed metadata. Like the SQL planner's\n // framework-owned column, this belongs to storage, not the public resource DTO. Without\n // this path Mongoose silently drops the ownership/version stamp, defeating both unchanged\n // reconciliation and the seed-scoped orphan scan. Unseeded records have no value/default.\n cleanSchemaDefinition[DATA_SEED_ROW_METADATA_FIELD_KEY] = { type: Schema.Types.Mixed };\n\n // Create the Mongoose schema\n const mongooseSchema = new Schema(cleanSchemaDefinition, SCHEMA_DEFAULT_OPTIONS);\n\n // Register each surrogate primary key as a read-only virtual projection of `_id`.\n for (const surrogateName of surrogatePrimaryKeyFields) {\n mongooseSchema.virtual(surrogateName).get(function (this: { _id?: unknown }) {\n return this._id != null ? String(this._id) : undefined;\n });\n }\n\n this.relaxPluginOwnedTimestampRequiredValidators(mongooseSchema);\n\n // Apply standard transforms (convert ObjectId to string in toObject/toJSON)\n this.applyStandardTransforms(mongooseSchema);\n\n // A surrogate primary key is exposed only as a Mongoose VIRTUAL (= String(_id)), so it\n // must survive `toObject()` / `toJSON()`. `applyStandardTransforms` rewrites those\n // options without `virtuals: true` (it drops the `SCHEMA_DEFAULT_OPTIONS` virtuals\n // flag), which would silently strip the surrogate name from every response/DTO. Re-\n // enable virtuals — but ONLY for resources that actually have a surrogate PK — so the\n // serialized shape of every other resource is unchanged.\n //\n // Side effect: enabling virtuals also exposes Mongoose's built-in `id` virtual\n // (= String(_id)) on this resource's `toObject`/`toJSON`. That is harmless — the\n // response DTO is a non-`.strict()` Zod object, which strips unknown keys, so `id`\n // never reaches an API/DTO consumer (only the declared surrogate `<name>` does).\n // (A surrogate field that participates in a `.businessKeySet([...])` is handled by\n // `applyBusinessKeyCompoundUniqueIndex` — the deleted path reads as \"missing\", so the\n // compound index is skipped with a warning rather than emitted against a virtual.)\n if (surrogatePrimaryKeyFields.length > 0) {\n const currentToObject = (mongooseSchema as any).options?.toObject || {};\n const currentToJSON = (mongooseSchema as any).options?.toJSON || {};\n mongooseSchema.set('toObject', { ...currentToObject, virtuals: true });\n mongooseSchema.set('toJSON', { ...currentToJSON, virtuals: true });\n }\n\n this.applyRelationshipForeignKeyPersistence(\n mongooseSchema,\n resourceConfiguration,\n options.includeIndexes !== false,\n );\n\n // Apply indexes if enabled\n if (options.includeIndexes !== false) {\n this.applyIndexesToSchema(mongooseSchema, indexesToApply, uniqueIndexesToApply, ttlIndexesToApply, resourceConfiguration?.resourceIdentifier as string | undefined, resourceConfiguration);\n // Phase 3.2 fix (review Finding #4 / R2-4): materialise the\n // top-level `.businessKeySet([...])` decorator as a Mongo\n // compound `{ unique: true }` index. Without this, the Zod\n // metadata is enforced at the **type** layer (filter builders,\n // `findByBusinessKey` callers) but NOT at the DB layer, leaving\n // race-prone find-then-create paths (e.g. data-seed\n // `DataSeedDispatcher.startRun`) free to insert duplicate\n // business-key rows under concurrency. Single-field business\n // keys are already covered by the field-level\n // `isBusinessKey() ⇒ isUnique` translation, so this only\n // applies to length ≥ 2 composite keys (centralised here so\n // every business-keyed resource benefits, not just\n // `DataSeedRun`).\n this.applyBusinessKeyCompoundUniqueIndex(mongooseSchema, zodSchema, resourceConfiguration);\n }\n\n return {\n mongooseSchema,\n inheritanceSchemas\n };\n } catch (error) {\n // Cleanup\n inheritanceSchemas.length = 0;\n indexesToApply.length = 0;\n ttlIndexesToApply.length = 0;\n uniqueIndexesToApply.length = 0;\n\n const conversionError = this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED,\n context: {\n originalError: describeCaughtError(error),\n maxDepth: options.maxDepth\n }\n }\n );\n throw conversionError;\n } finally {\n // The set belongs to THIS conversion; the next one (another resource) starts from its own.\n this.virtualTargetForeignKeyFields = new Set();\n }\n }\n\n /**\n * Converts a Zod type to a Mongoose schema definition\n * @param zodType The Zod type to convert\n * @param processedSchemas Set to track circular references\n * @param inheritanceSchemas Array to collect union inheritance schemas\n * @param indexesToApply Array to collect index paths\n * @param uniqueIndexesToApply Array to collect unique index paths with params\n * @param ttlIndexesToApply Array to collect TTL index paths with params\n * @param currentPath Current object path for indexing\n * @param currentDepth Current recursion depth\n * @param maxDepth Maximum allowed recursion depth\n * @returns The Mongoose schema definition\n */\n private convertZodTypeToMongooseDefinition(\n zodType: z.ZodTypeAny,\n processedSchemas: WeakSet<z.ZodTypeAny>,\n schemaCache: WeakMap<z.ZodTypeAny, Schema>,\n inheritanceSchemas: UnionInheritance_SchemaInfo[],\n indexesToApply: string[],\n uniqueIndexesToApply: UniqueIndexInfo[],\n ttlIndexesToApply: TtlIndexInfo[],\n currentPath: string = '',\n currentDepth: number = 0,\n maxDepth: number = 10\n ): any {\n\n\n\n // Depth check\n if (currentDepth >= maxDepth) {\n return { type: Schema.Types.Mixed };\n }\n\n try {\n // Handle pipe types (from .transform(), .pipe(), etc.) - unwrap to input schema\n // In Zod v4, transforms create pipe types with 'in' and 'out' schemas\n if (isZodPipe(zodType)) {\n const inputSchema = getPipeInputSchema(zodType);\n if (inputSchema) {\n // For pipe types, recursively process the input schema\n return this.convertZodTypeToMongooseDefinition(\n inputSchema,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n }\n }\n\n // Handle ZodObject (main case for resource schemas)\n // In Zod v4, object schemas have type: \"object\"\n if (isZodObject(zodType)) {\n\n // Check cache for existing schema to handle recursion\n if (schemaCache.has(zodType)) {\n return schemaCache.get(zodType);\n }\n\n // Create a new Schema instance immediately to allow self-reference\n // We use a temporary empty definition, then add paths to it\n const newSchema = new Schema({}, SCHEMA_SUBDOCUMENT_OPTIONS);\n schemaCache.set(zodType, newSchema);\n\n // Use public .shape property (Zod v4 API)\n const shape = getZodObjectShape(zodType);\n\n\n\n const mongooseDefinition: any = {};\n\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n if (fieldName.startsWith('$') || typeof fieldSchema !== 'object' || fieldSchema === null) {\n if (fieldName.startsWith('$')) {\n this.logger.warn(`[ZodToMongoose] Skipping '$'-prefixed key '${fieldName}' (value type: ${typeof fieldSchema}) at path='${currentPath}'. Assumed Zod internal — if this is a user field, the filter is incorrect.`);\n }\n continue;\n }\n\n // Virtual fields (isVirtual) are computed at read time by\n // VirtualFieldsBackendService and never persisted — they must NOT produce\n // a Mongoose path. Their declared `dependencies` are ordinary stored\n // fields and are emitted normally, so the computation still has its\n // inputs. Skipping here keeps computed fields out of the database schema.\n if (isVirtualField(fieldSchema as z.ZodTypeAny)) {\n continue;\n }\n\n const fieldPath = currentPath ? `${currentPath}.${fieldName}` : fieldName;\n\n const fieldDefinition = this.convertZodFieldToMongooseField(\n fieldSchema as z.ZodTypeAny,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n fieldPath,\n currentDepth + 1,\n maxDepth\n );\n\n // Safety check: ensure field definition is valid\n if (!fieldDefinition || typeof fieldDefinition !== 'object' ||\n (!fieldDefinition.type && !Array.isArray(fieldDefinition) && typeof fieldDefinition !== 'object')) {\n this.logger.warn(`[ZodToMongoose] Invalid field definition for ${fieldPath}`, { fieldDefinition });\n this.logger.warn(`[ZodToMongoose] Zod field type was: ${typeof fieldSchema}`);\n mongooseDefinition[fieldName] = { type: Schema.Types.Mixed };\n } else {\n // CRITICAL: If fieldDefinition is a Schema instance (from nested object),\n // wrap it in { type: ... } to prevent Mongoose from iterating over its properties\n if (this.isSchemaLike(fieldDefinition)) {\n mongooseDefinition[fieldName] = {\n type: fieldDefinition,\n _id: false\n };\n } else {\n mongooseDefinition[fieldName] = fieldDefinition;\n }\n }\n }\n\n // Final validation: ensure all fields have proper type properties\n // Only validate at depth 0 (top-level). Nested objects will be validated by Mongoose\n // when they're added to their parent schema\n if (currentDepth === 0) {\n this.validateAndFixFieldTypes(mongooseDefinition, 'unknown');\n }\n\n // If this is the top-level call (depth 0), we return the definition object\n // so the caller can create the main Schema.\n // If this is a nested object (depth > 0), we return the Schema instance we created.\n if (currentDepth === 0) {\n return mongooseDefinition;\n } else {\n newSchema.add(mongooseDefinition);\n this.applyStandardTransforms(newSchema);\n return newSchema;\n }\n }\n\n // For non-object types, convert as field\n return this.convertZodFieldToMongooseField(\n zodType,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n } catch (error) {\n processedSchemas.delete(zodType);\n this.logger.error(`[ZodToMongoose] convertZodTypeToMongooseDefinition FAILED at path='${currentPath}', depth=${currentDepth}: ${describeCaughtError(error)}`);\n throw error;\n }\n }\n\n // =================================================================\n // FIELD CONVERSION METHODS\n // =================================================================\n\n /**\n * Converts a single Zod field to a Mongoose field definition\n * @param zodField The Zod field schema\n * @param processedSchemas Set to track circular references\n * @param inheritanceSchemas Array to collect union inheritance schemas\n * @param indexesToApply Array to collect index paths\n * @param ttlIndexesToApply Array to collect TTL index paths\n * @param currentPath Current field path\n * @param currentDepth Current recursion depth\n * @param maxDepth Maximum allowed recursion depth\n * @returns The Mongoose field definition\n */\n private convertZodFieldToMongooseField(\n zodField: z.ZodTypeAny,\n processedSchemas: WeakSet<z.ZodTypeAny>,\n schemaCache: WeakMap<z.ZodTypeAny, Schema>,\n inheritanceSchemas: UnionInheritance_SchemaInfo[],\n indexesToApply: string[],\n uniqueIndexesToApply: UniqueIndexInfo[],\n ttlIndexesToApply: TtlIndexInfo[],\n currentPath: string,\n currentDepth: number,\n maxDepth: number\n ): any {\n\n // Special handling for the TOP-LEVEL `_id` — the document's canonical Mongo\n // key — which is always an auto-generatable ObjectId. A NESTED/embedded `_id`\n // (currentPath like `standaloneTasks[]._id`) is a different thing: an authored\n // identity field declared in the Zod schema (e.g. the tasks embedded in an\n // ActorSystem execution's `standaloneTasks` array, whose `_id` is the task\n // row's id). Forcing THAT to ObjectId + disabling `_id` on the subdoc wrapper\n // (see the nested-object branch below) silently DROPPED it on the Mongo\n // round-trip (first-live bug, 2026-07-08: read-back embedded tasks had no\n // `_id`, so the execution-snapshot re-sync appended a duplicate and failed\n // validation). For a nested `_id`, fall through to the standard declared-type\n // conversion so its Zod type (typically `z.string()`) is honored and persists.\n const fieldName = currentPath.split('.').pop() || '';\n if (fieldName === '_id' && currentPath === '_id') {\n const definition: any = {\n type: Schema.Types.ObjectId,\n // Ensure Mongoose can auto-generate _id when not provided\n default: () => new Types.ObjectId(),\n required: false\n };\n\n return definition;\n }\n\n // Unwrap optional fields\n // In Zod v4, optional schemas have type: \"optional\"\n if (isZodOptional(zodField)) {\n const innerType = getZodDefSchemaProperty(zodField, 'innerType');\n if (!innerType) {\n return { type: Schema.Types.Mixed, required: false };\n }\n const innerField = this.convertZodFieldToMongooseField(\n innerType,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n // For optional fields, explicitly ensure they are NOT required\n if (!innerField || typeof innerField !== 'object') {\n return { type: Schema.Types.Mixed, required: false };\n }\n\n // Handle arrays specially (arrays don't have required property)\n if (Array.isArray(innerField)) {\n return innerField; // Arrays don't have required property\n }\n\n // CRITICAL: If innerField is a Schema instance (from nested object), wrap it properly\n // Do NOT destructure Schema instances as this spreads their internal properties\n if (this.isSchemaLike(innerField)) {\n return {\n type: innerField,\n required: false,\n _id: false\n };\n }\n\n // Remove any required: true and explicitly set required: false for optional fields\n const { required, ...optionalField } = innerField;\n\n // Explicitly set required: false to ensure Mongoose recognizes this as optional\n const result = Object.keys(optionalField).length === 0 && innerField.type\n ? { type: innerField.type, required: false }\n : { ...optionalField, required: false };\n\n return result;\n }\n\n // Unwrap nullable fields\n // In Zod v4, nullable schemas have type: \"nullable\"\n if (isZodNullable(zodField)) {\n const innerType = getZodDefSchemaProperty(zodField, 'innerType');\n if (!innerType) {\n return { type: Schema.Types.Mixed };\n }\n const innerField = this.convertZodFieldToMongooseField(\n innerType,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n // Ensure we always have at least the type information\n if (!innerField || typeof innerField !== 'object') {\n return { type: Schema.Types.Mixed };\n }\n\n // An array definition (`[String]`) passes through untouched, as the optional and default branches\n // already do (#1776). Destructuring it below turned `[String]` into `{ \"0\": String }`, and an outer\n // `.optional()` then added `required: false` to that plain object, which Mongoose reads as a nested\n // PATH named `required` defined as `false` — so `z.array(…).nullish()` refused the whole model.\n if (Array.isArray(innerField)) {\n return innerField;\n }\n\n // CRITICAL: If innerField is a Schema instance (from nested object), wrap it properly\n // Do NOT destructure Schema instances as this spreads their internal properties\n if (this.isSchemaLike(innerField)) {\n return {\n type: innerField,\n _id: false\n };\n }\n\n // For nullable fields, we typically don't want required=true\n const { required, ...nullableField } = innerField;\n if (Object.keys(nullableField).length === 0 && innerField.type) {\n return { type: innerField.type };\n }\n return nullableField;\n }\n\n // Unwrap default fields\n // In Zod v4, default schemas have type: \"default\"\n if (isZodDefault(zodField)) {\n /**\n * ⚠️ In Zod 4 `def.defaultValue` is a GETTER, not a stored value.\n *\n * Reading it EVALUATES the default: `z.date().default(() => new Date())`\n * yields a fresh `Date` on every read (verified — two reads are not the same\n * reference), and a literal default yields its value. There is therefore no\n * \"thunk\" to detect and forward — `typeof … === 'function'` is never true for\n * a dynamic default, only for a default whose VALUE happens to be a function.\n *\n * So a single read here is a materialization, and this method runs ONCE per\n * model at model-build time (process start). Handing Mongoose that value\n * freezes it for the life of the process: every document inserted by that\n * process is stamped with the same instant. Mongoose does not rescue it — a\n * `default` is applied at document construction, and the `timestamps` plugin\n * explicitly DEFERS to an already-set path, so a frozen `createdAt` shadows\n * the plugin silently.\n *\n * Measured before this fix (Wonder Todos, 2026-08-10): `auditLogs` held three\n * distinct `createdAt` values across its newest 200 rows — one per backend\n * boot — and `createdAt` is that resource's only event timestamp, so ordering\n * within a boot was unrecoverable. The same freeze reached\n * `jobExecutions.createdAt`, which then carried a 30-day TTL index (rows expired\n * relative to boot, not to creation; current cleanup uses `expiresAt`), the pending-invitation and\n * anonymous-session sweeps (which DELETE by a `createdAt` cutoff), and\n * business fields such as `files.uploadedAt` / `userIdentityLinks.linkedAt`.\n * The error equals process uptime and always points into the past, so every\n * one of those consumers acts too early — invisible on a dev machine that\n * restarts constantly, progressively worse on a long-lived pod.\n */\n const defaultValueProp = getZodDefProperty(zodField, 'defaultValue');\n\n /**\n * The MATERIALIZED default — used ONLY for structural decisions below (is\n * this a nested object? which nested paths carry their own default?). Reading\n * it once is correct for inspection and wrong for persistence.\n */\n const defaultValue = typeof defaultValueProp === 'function'\n ? (defaultValueProp as () => unknown)()\n : defaultValueProp;\n\n /**\n * What Mongoose actually receives: a function that RE-READS the Zod getter,\n * so the default is evaluated per document instead of per model.\n *\n * Applied uniformly rather than only to dynamic defaults — a literal simply\n * returns its value on each read, and routing object/array literals through\n * the getter additionally retires a latent second defect, where a single\n * materialized instance was shared as the default of every document of the\n * model.\n */\n const mongooseDefault = (): unknown => getZodDefProperty(zodField, 'defaultValue');\n\n const innerType = getZodDefSchemaProperty(zodField, 'innerType');\n if (!innerType) {\n return { type: Schema.Types.Mixed, default: mongooseDefault };\n }\n\n const innerField = this.convertZodFieldToMongooseField(\n innerType,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n\n // Remove required property for fields with defaults (Mongoose treats absence as optional)\n // Ensure we always have at least the type information\n if (!innerField || typeof innerField !== 'object') {\n return { type: Schema.Types.Mixed, default: mongooseDefault };\n }\n\n // Handle arrays BEFORE destructuring (arrays don't have required property)\n if (Array.isArray(innerField)) {\n return {\n type: innerField,\n default: mongooseDefault\n };\n }\n\n // CRITICAL: If innerField is a Schema instance (from nested object), wrap it properly\n // Do NOT destructure Schema instances as this spreads their internal properties\n if (this.isSchemaLike(innerField)) {\n return {\n type: innerField,\n default: mongooseDefault,\n _id: false\n };\n }\n\n const { required, ...fieldWithoutRequired } = innerField;\n\n // Check if this is a nested object schema (has 'type' property with nested fields)\n // CRITICAL: Do NOT spread if type is a Schema instance!\n const isNestedObjectSchema = fieldWithoutRequired.type &&\n typeof fieldWithoutRequired.type === 'object' &&\n !Array.isArray(fieldWithoutRequired.type) &&\n !this.isSchemaLike(fieldWithoutRequired.type) &&\n Object.keys(fieldWithoutRequired.type).length > 0;\n\n if (isNestedObjectSchema && defaultValue && typeof defaultValue === 'object') {\n // For nested objects with defaults, preserve field type definitions\n // and merge defaults into the appropriate fields\n const nestedFields = { ...fieldWithoutRequired.type };\n\n for (const [fieldName, defaultFieldValue] of Object.entries(defaultValue)) {\n if (nestedFields[fieldName] && typeof nestedFields[fieldName] === 'object') {\n // Preserve the existing field definition and add the default\n nestedFields[fieldName] = {\n ...nestedFields[fieldName],\n default: defaultFieldValue\n };\n }\n }\n\n return {\n type: nestedFields,\n // The per-path defaults merged above come from the materialized value\n // (they are structural); the OBJECT default stays the thunk so each\n // document builds its own instance instead of sharing one.\n default: mongooseDefault,\n _id: false\n };\n }\n\n // This check is no longer needed since arrays are handled before destructuring\n\n // Ensure we have at least the type property for primitive fields\n const result = Object.keys(fieldWithoutRequired).length === 0 && innerField.type\n ? { type: innerField.type }\n : fieldWithoutRequired;\n\n return {\n ...result,\n default: mongooseDefault\n };\n }\n\n // Handle pipe types (from .transform(), .pipe(), etc.) - extract the input schema\n // In Zod v4, transforms create pipe types with 'in' and 'out' schemas\n if (isZodPipe(zodField)) {\n const inputSchema = getPipeInputSchema(zodField);\n if (inputSchema) {\n return this.convertZodFieldToMongooseField(\n inputSchema,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n }\n }\n\n // Handle transform types (standalone transform, no underlying schema)\n // In Zod v4, transform types are standalone\n if (isZodTransform(zodField)) {\n // Transform types don't have an underlying schema, return Mixed\n return { type: Schema.Types.Mixed };\n }\n\n // Handle custom types (from .refine(), .superRefine(), etc.)\n // In Zod v4, custom types don't wrap schemas - refinements are stored as checks\n // For custom types, we need to check if there's an underlying schema\n // This is complex - for now, return Mixed\n if (isZodCustom(zodField)) {\n return { type: Schema.Types.Mixed };\n }\n\n // Handle arrays\n // In Zod v4, array schemas have type: \"array\"\n if (isZodArray(zodField)) {\n const element = getZodDefSchemaProperty(zodField, 'element');\n if (!element) {\n return [{ type: Schema.Types.Mixed }];\n }\n\n const elementType = this.convertZodFieldToMongooseField(\n element,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n `${currentPath}[]`,\n currentDepth + 1,\n maxDepth\n );\n\n // Check for array-level decorators before returning\n let arrayDefinition: any = [elementType];\n\n // Handle array-level resource reference (convert array elements to ObjectId — or, for an array of keys of a\n // VIRTUAL resource, to its synthesized string keys: #1939)\n if (isForeignKey(zodField)) {\n arrayDefinition = [{\n type: this.foreignKeyStorageType(currentPath)\n }];\n }\n\n // Collect index information for decorated array fields\n // Skip primary keys - they're already indexed via unique index or field-level index\n if (isDBIndexed(zodField) && !isPrimaryKey(zodField) && currentPath) {\n indexesToApply.push(currentPath);\n }\n\n // Collect unique index information for array fields\n if (isUnique(zodField) && currentPath) {\n const uniqueParams = getUniqueParams(zodField);\n uniqueIndexesToApply.push({ path: currentPath, params: uniqueParams || {} });\n }\n\n // Collect TTL index information for array fields (rare, but possible for array of dates)\n if (hasTtl(zodField) && currentPath) {\n const ttlParams = getTtlParams(zodField);\n if (ttlParams) {\n ttlIndexesToApply.push({ path: currentPath, params: ttlParams });\n }\n }\n\n return arrayDefinition;\n }\n\n // Handle tuples\n // In Zod v4, tuple schemas have type: \"tuple\"\n if (isZodTuple(zodField)) {\n return [{ type: Schema.Types.Mixed }];\n }\n\n // Handle nested objects\n // In Zod v4, object schemas have type: \"object\"\n if (isZodObject(zodField)) {\n const nestedDefinition = this.convertZodTypeToMongooseDefinition(\n zodField,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n\n // Honor an EXPLICITLY-declared `_id` on the embedded object (the\n // \"unless explicitly defined\" the legacy comment promised but did not\n // deliver). A subdocument whose Zod shape declares `_id` carries an\n // authored identity that MUST persist; `_id: false` on the wrapper strips\n // the subschema's own `_id` path, silently losing it on the round-trip\n // (first-live bug, 2026-07-08). Anonymous nested objects (no declared\n // `_id`) keep `_id: false` so Mongoose does not inject a spurious ObjectId.\n const declaresOwnId = Object.prototype.hasOwnProperty.call(getZodObjectShape(zodField), '_id');\n\n // If nestedDefinition is a Schema instance (from cache or new), return it directly as type\n if (nestedDefinition instanceof Schema) {\n return declaresOwnId ? { type: nestedDefinition } : { type: nestedDefinition, _id: false };\n }\n\n // Otherwise wrap the definition\n return declaresOwnId ? { type: nestedDefinition } : { type: nestedDefinition, _id: false };\n }\n\n // Handle discriminated unions\n // At depth 0: collect schema info for Mongoose discriminator model creation (root-level).\n // At depth > 0: flatten into a superset schema. This is intentional — Mongoose embedded\n // discriminators are unstable at depth 3-6 and MongoDB enforces nothing on sub-documents.\n // Zod validates per-variant constraints in the resource pipeline before Mongoose writes.\n if (isDiscriminatedUnion(zodField)) {\n if (currentDepth === 0) {\n return this.handleDiscriminatedUnionField(\n zodField,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n }\n return this.flattenDiscriminatedUnionForSubdocument(\n zodField,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n }\n\n // Handle regular unions - analyze for smart type detection\n // In Zod v4, union schemas have type: \"union\"\n if (isZodUnion(zodField)) {\n return this.handleZodUnion(zodField);\n }\n\n // Handle intersections - merge the types\n // In Zod v4, intersection schemas have type: \"intersection\"\n if (isZodIntersection(zodField)) {\n const left = getZodDefSchemaProperty(zodField, 'left');\n const right = getZodDefSchemaProperty(zodField, 'right');\n\n if (!left || !right) {\n return { type: Schema.Types.Mixed };\n }\n\n const leftDef = this.convertZodFieldToMongooseField(\n left,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n const rightDef = this.convertZodFieldToMongooseField(\n right,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n\n // Merge object definitions\n if (this.isObjectDefinition(leftDef) && this.isObjectDefinition(rightDef)) {\n return { ...leftDef, ...rightDef };\n }\n return { type: Schema.Types.Mixed };\n }\n\n // Handle literals\n // In Zod v4, literal schemas have type: \"literal\" and store their value(s)\n // in def.values — an ARRAY, because z.literal(['a', 'b']) is legal in v4.\n // Reading the legacy Zod 3 def.value returned undefined and silently\n // degraded EVERY literal field to Mixed with enum: [null] — which is how\n // flattened discriminated-union tags escaped enum validation entirely.\n if (isZodLiteral(zodField)) {\n const literalValues = (getZodDefArrayProperty(zodField, 'values') ?? [getZodDefProperty(zodField, 'value')])\n .filter((value) => value !== undefined && value !== null);\n if (literalValues.length === 0) {\n // z.literal(null) / z.literal(undefined): Mixed accepts the nullish value.\n return { type: Schema.Types.Mixed };\n }\n const firstValue = literalValues[0];\n return {\n type: typeof firstValue === 'string' ? String :\n typeof firstValue === 'number' ? Number :\n typeof firstValue === 'boolean' ? Boolean : Schema.Types.Mixed,\n enum: literalValues\n };\n }\n\n // Handle lazy types (recursive schemas)\n // In Zod v4, lazy schemas have type: \"lazy\"\n if (isZodLazy(zodField)) {\n const getter = getZodDefFunctionProperty(zodField, 'getter');\n if (!getter) {\n return { type: Schema.Types.Mixed };\n }\n const innerSchema = getter();\n return this.convertZodFieldToMongooseField(\n innerSchema,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n }\n\n // Handle basic types with decorators - unwrap to get the core type\n const coreType = this.unwrapDecoratedType(zodField);\n const baseDefinition = this.getBaseMongooseType(coreType, schemaCache);\n\n // Apply resource reference (ObjectId — or the synthesized string key of a VIRTUAL target: #1939)\n if (isForeignKey(zodField)) {\n const definition: any = {\n type: this.foreignKeyStorageType(currentPath)\n };\n\n // Only add required property if the field is actually required\n if (this.isFieldRequired(zodField)) {\n definition.required = true;\n }\n\n // Collect index information instead of applying immediately\n // Skip primary keys - they're already indexed via unique index or field-level index\n if (isDBIndexed(zodField) && !isPrimaryKey(zodField) && currentPath) {\n indexesToApply.push(currentPath);\n }\n\n // Collect unique index information\n if (isUnique(zodField) && currentPath) {\n const uniqueParams = getUniqueParams(zodField);\n uniqueIndexesToApply.push({ path: currentPath, params: uniqueParams || {} });\n }\n\n return definition;\n }\n\n // Collect TTL index information for Date fields\n // TTL indexes enable automatic document expiration in MongoDB\n if (hasTtl(zodField) && currentPath) {\n const ttlParams = getTtlParams(zodField);\n if (ttlParams) {\n ttlIndexesToApply.push({ path: currentPath, params: ttlParams });\n }\n }\n\n // Collect index information for decorated fields\n // Skip primary keys - they're already indexed via unique index or field-level index\n if (isDBIndexed(zodField) && !isPrimaryKey(zodField) && currentPath) {\n indexesToApply.push(currentPath);\n }\n\n // Collect unique index information for decorated fields\n if (isUnique(zodField) && currentPath) {\n const uniqueParams = getUniqueParams(zodField);\n uniqueIndexesToApply.push({ path: currentPath, params: uniqueParams || {} });\n }\n\n // Only add required property if the field is actually required\n if (this.isFieldRequired(zodField)) {\n const definition = baseDefinition || { type: Schema.Types.Mixed };\n return {\n ...definition,\n required: true\n };\n }\n\n return baseDefinition || { type: Schema.Types.Mixed };\n }\n\n // =================================================================\n // TYPE HANDLING METHODS\n // =================================================================\n\n /**\n * Flattens a discriminated union into a superset schema for embedded sub-documents.\n *\n * This is the **intended persistence strategy** for discriminated unions nested inside\n * sub-documents. Mongoose embedded discriminators (both array and single-nested) exist\n * but have known instability at depth 3-6 (field stripping, validation inconsistencies,\n * query hydration bugs — see Mongoose issues #10702, #12318, #15075). MongoDB itself\n * enforces nothing about sub-document schemas regardless of Mongoose configuration.\n *\n * The architecture relies on **Zod as the authoritative validation layer**: all writes\n * pass through `requestDto.parse()` in the resource operation pipeline before reaching\n * Mongoose. The superset schema preserves field types and indexes while Zod enforces\n * per-variant required constraints.\n *\n * WHAT THIS METHOD DOES:\n * - Merges all fields from ALL union variants into one flat sub-document schema.\n * - The discriminator key merges the enum values of EVERY variant's tag —\n * the tag is a different literal per variant by construction, so keeping\n * only the first variant's enum would reject every other variant at the\n * Mongoose layer (recovered 2026-07-03: `type: 'structured'` artifacts\n * failed against `enum: ['text']`).\n * - All non-discriminator fields become optional at the Mongoose layer\n * (each variant persists only its own subset).\n * - A field declared by SEVERAL variants with DIFFERENT object shapes (the\n * `content`-per-kind pattern, e.g. `ArtifactInstanceSchema`) merges into a\n * deep all-optional superset of those shapes — NOT first-variant-wins,\n * which let the first variant's required inner paths reject every other\n * variant's payload (\"content.text: Path `text` is required.\" for a\n * Zod-valid structured artifact).\n * - Same-named fields that share a primitive base type union their enum\n * constraints; structurally incompatible fields (object vs primitive,\n * string vs number, differing arrays) degrade to `Schema.Types.Mixed`.\n * - Field types, indexes, and enum values ARE preserved wherever the\n * variants agree (unlike a blanket Schema.Types.Mixed).\n */\n private flattenDiscriminatedUnionForSubdocument(\n zodField: z.ZodTypeAny,\n processedSchemas: WeakSet<z.ZodTypeAny>,\n schemaCache: WeakMap<z.ZodTypeAny, Schema>,\n inheritanceSchemas: UnionInheritance_SchemaInfo[],\n indexesToApply: string[],\n uniqueIndexesToApply: UniqueIndexInfo[],\n ttlIndexesToApply: TtlIndexInfo[],\n currentPath: string,\n currentDepth: number,\n maxDepth: number\n ): any {\n const discriminatorKey = getZodDefStringProperty(zodField, 'discriminator');\n const optionsArray = getZodDefArrayProperty(zodField, 'options');\n\n if (!discriminatorKey || !optionsArray || optionsArray.length === 0) {\n return { type: Schema.Types.Mixed };\n }\n\n const options = optionsArray.filter(isZodTypeAny);\n if (options.length === 0) {\n return { type: Schema.Types.Mixed };\n }\n\n this.logDebug(\n `[ZodToMongoose] Discriminated union at path='${currentPath}' (depth=${currentDepth}): ` +\n `flattening ${options.length} variants into superset schema (discriminator='${discriminatorKey}'). ` +\n `Per-variant required constraints enforced by Zod validation in the resource operation pipeline.`\n );\n\n // Pass 1 — collect the DISTINCT Zod field schemas per field name across\n // all variants. Dedupe by reference: variants built from a common base via\n // `.extend()` share the base field instances, so shared fields collapse to\n // a single schema and only genuinely re-declared fields need merging.\n const variantFieldSchemas = new Map<string, z.ZodTypeAny[]>();\n for (const option of options) {\n if (!isZodObject(option)) continue;\n\n const optionShape = getZodObjectShape(option);\n for (const [fieldName, fieldSchema] of Object.entries(optionShape)) {\n if (typeof fieldSchema !== 'object' || fieldSchema === null) continue;\n let schemas = variantFieldSchemas.get(fieldName);\n if (!schemas) {\n schemas = [];\n variantFieldSchemas.set(fieldName, schemas);\n }\n if (!schemas.includes(fieldSchema as z.ZodTypeAny)) {\n schemas.push(fieldSchema as z.ZodTypeAny);\n }\n }\n }\n\n // Pass 2 — build the merged Mongoose definition.\n const mergedDefinition: Record<string, any> = {};\n for (const [fieldName, schemas] of variantFieldSchemas) {\n const fieldPath = currentPath ? `${currentPath}.${fieldName}` : fieldName;\n const convert = (schema: z.ZodTypeAny): any => this.convertZodFieldToMongooseField(\n schema,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n fieldPath,\n currentDepth + 1,\n maxDepth\n );\n\n if (fieldName === discriminatorKey) {\n // Union the tag values of every variant so each variant's document\n // passes the Mongoose enum validator.\n const discriminatorDef = convert(schemas[0]);\n for (const variantSchema of schemas.slice(1)) {\n const variantDef = convert(variantSchema);\n if (\n discriminatorDef && Array.isArray(discriminatorDef.enum) &&\n variantDef && Array.isArray(variantDef.enum)\n ) {\n discriminatorDef.enum = [...new Set([...discriminatorDef.enum, ...variantDef.enum])];\n }\n }\n mergedDefinition[fieldName] = discriminatorDef ?? { type: Schema.Types.Mixed };\n continue;\n }\n\n const fieldDef = schemas.length === 1\n ? convert(schemas[0])\n : this.convertConflictingVariantField(schemas, convert);\n\n // Non-discriminator fields are optional at the Mongoose layer — each\n // variant persists only its own subset; Zod owns per-variant required.\n if (typeof fieldDef === 'object' && fieldDef !== null && !Array.isArray(fieldDef) && !(fieldDef instanceof Schema)) {\n mergedDefinition[fieldName] = { ...fieldDef, required: false };\n } else {\n mergedDefinition[fieldName] = fieldDef;\n }\n }\n\n const nestedSchema = new Schema(mergedDefinition, SCHEMA_SUBDOCUMENT_OPTIONS);\n this.applyStandardTransforms(nestedSchema);\n return nestedSchema;\n }\n\n /**\n * Converts a field that is declared with DIFFERENT Zod schemas across the\n * variants of a flattened discriminated union (see\n * {@link flattenDiscriminatedUnionForSubdocument}).\n *\n * Resolution order:\n * 1. Every variant declares an object payload (the `content`-per-kind\n * pattern) → convert a deep all-optional superset of those shapes so\n * paths stay typed and no variant's required inner field leaks onto the\n * others.\n * 2. Every variant converts to the same primitive Mongoose type → keep the\n * shared type; union enum constraints when ALL variants are\n * enum-constrained, drop the enum when any variant is unconstrained\n * (a constrained enum would reject the unconstrained variant's values).\n * 3. Structurally incompatible (object vs primitive, string vs number,\n * differing array elements, …) → `Schema.Types.Mixed`. First-variant-wins\n * is NOT an option: it validates every other variant against a shape it\n * never declared.\n */\n private convertConflictingVariantField(\n schemas: z.ZodTypeAny[],\n convert: (schema: z.ZodTypeAny) => any\n ): any {\n const supersetObject = this.buildVariantObjectSupersetSchema(schemas);\n if (supersetObject) {\n return convert(supersetObject);\n }\n\n const isPlainDefinition = (definition: any): boolean =>\n typeof definition === 'object' && definition !== null &&\n !Array.isArray(definition) && !(definition instanceof Schema);\n\n const variantDefs = schemas.map(convert);\n const firstDef = variantDefs[0];\n if (isPlainDefinition(firstDef) && variantDefs.every((definition) => isPlainDefinition(definition) && definition.type === firstDef.type)) {\n if (variantDefs.every((definition) => Array.isArray(definition.enum))) {\n return { ...firstDef, enum: [...new Set(variantDefs.flatMap((definition) => definition.enum))] };\n }\n const { enum: _unconstrainedAcrossVariants, ...withoutEnum } = firstDef;\n return withoutEnum;\n }\n\n return { type: Schema.Types.Mixed };\n }\n\n /**\n * Builds an all-optional superset Zod object for a field whose variants each\n * declare a (different) object payload under the same name.\n *\n * The superset is built at the ZOD level — not by merging converted Mongoose\n * definitions — so the regular conversion pipeline (decorators, nested\n * unions, arrays, defaults) applies unchanged to the merged shape. Every\n * superset field is wrapped `.optional()`: a field required by one variant\n * is absent from the others by construction, and per-variant requiredness is\n * enforced by Zod in the resource operation pipeline before Mongoose writes.\n *\n * Inner same-named fields that are themselves objects in every variant merge\n * recursively; anything else that conflicts degrades to `z.any()` (persisted\n * as `Schema.Types.Mixed`).\n *\n * @returns the superset object schema, or null when any variant's core type\n * is not a plain Zod object (the caller falls back to primitive\n * enum merging or Mixed).\n */\n private buildVariantObjectSupersetSchema(schemas: z.ZodTypeAny[]): z.ZodTypeAny | null {\n const coreSchemas = schemas.map((schema) => this.unwrapDecoratedType(schema));\n if (coreSchemas.length === 0 || !coreSchemas.every((core) => isZodObject(core))) {\n return null;\n }\n\n const fieldSchemasByName = new Map<string, z.ZodTypeAny[]>();\n for (const core of coreSchemas) {\n const shape = getZodObjectShape(core);\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n if (typeof fieldSchema !== 'object' || fieldSchema === null) continue;\n let list = fieldSchemasByName.get(fieldName);\n if (!list) {\n list = [];\n fieldSchemasByName.set(fieldName, list);\n }\n if (!list.includes(fieldSchema as z.ZodTypeAny)) {\n list.push(fieldSchema as z.ZodTypeAny);\n }\n }\n }\n\n const supersetShape: Record<string, z.ZodTypeAny> = {};\n for (const [fieldName, fieldSchemas] of fieldSchemasByName) {\n const merged: z.ZodTypeAny = fieldSchemas.length === 1\n ? fieldSchemas[0]\n : (this.buildVariantObjectSupersetSchema(fieldSchemas) ?? z.any());\n supersetShape[fieldName] = isZodOptional(merged) ? merged : merged.optional();\n }\n\n return z.object(supersetShape);\n }\n\n /**\n * Handles discriminated union fields by collecting schema information\n * @param zodField The discriminated union field\n * @param processedSchemas Set to track circular references\n * @param inheritanceSchemas Array to collect union inheritance schemas\n * @param indexesToApply Array to collect index paths\n * @param currentPath Current field path\n * @param currentDepth Current recursion depth\n * @param maxDepth Maximum allowed recursion depth\n * @returns Base schema definition for the discriminated union\n */\n private handleDiscriminatedUnionField(\n zodField: z.ZodTypeAny,\n processedSchemas: WeakSet<z.ZodTypeAny>,\n schemaCache: WeakMap<z.ZodTypeAny, Schema>,\n inheritanceSchemas: UnionInheritance_SchemaInfo[],\n indexesToApply: string[],\n uniqueIndexesToApply: UniqueIndexInfo[],\n ttlIndexesToApply: TtlIndexInfo[],\n currentPath: string,\n currentDepth: number,\n maxDepth: number\n ): any {\n\n const discriminatorKey = getZodDefStringProperty(zodField, 'discriminator');\n const optionsArray = getZodDefArrayProperty(zodField, 'options');\n\n if (!discriminatorKey || !optionsArray || optionsArray.length === 0) {\n return { type: Schema.Types.Mixed };\n }\n\n // Filter and validate options are ZodTypeAny\n const options = optionsArray.filter(isZodTypeAny);\n if (options.length === 0) {\n return { type: Schema.Types.Mixed };\n }\n\n // Use the first option as the union root schema structure\n const rootOption = options[0];\n const rootDefinition = this.convertZodTypeToMongooseDefinition(\n rootOption,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n\n // Collect union inheritance schemas for later model creation (but don't create models here)\n for (let optionIndex = 0; optionIndex < options.length; optionIndex++) {\n const option = options[optionIndex];\n try {\n const optionDefinition = this.convertZodTypeToMongooseDefinition(\n option,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n\n // Create Mongoose schema for this union inheritance option\n const inheritanceOptionSchema = new Schema(optionDefinition, SCHEMA_SUBDOCUMENT_OPTIONS);\n this.applyStandardTransforms(inheritanceOptionSchema);\n\n // Extract discriminator value from the option's shape.\n // Unwrap the discriminator field to handle optional/nullable/default wrappers.\n //\n // `getEnumValues` is the Zod-4-correct reader: it reads a literal's\n // value from `def.values` (an ARRAY in Zod 4) and also handles\n // z.enum / native-enum / union discriminators. The prior code read the\n // legacy Zod-3 `def.value` (always undefined in Zod 4), so EVERY\n // literal-tagged variant fell through to the `option_${index}` fallback\n // below — root-union resources then registered their Mongoose\n // discriminators as `<Model>_option_0` instead of `<Model>_<tag>`.\n // getEnumValues only surfaces STRING literals; the direct `def.values`\n // read covers number/boolean literal discriminators it skips.\n let discriminatorValue: string | null = null;\n if (discriminatorKey && isZodObject(option)) {\n const optionShape = getZodObjectShape(option);\n const discriminatorField = optionShape[discriminatorKey];\n if (discriminatorField) {\n const unwrappedField = unwrapSchema(discriminatorField);\n const enumValues = getEnumValues(unwrappedField);\n if (enumValues.length > 0) {\n discriminatorValue = String(enumValues[0]);\n } else if (isZodLiteral(unwrappedField)) {\n const literalValues = getZodDefArrayProperty(unwrappedField, 'values')\n ?? [getZodDefProperty(unwrappedField, 'value')];\n const firstLiteral = literalValues.find((value) => value !== undefined && value !== null);\n if (firstLiteral !== undefined) {\n discriminatorValue = String(firstLiteral);\n }\n }\n }\n }\n\n // If we couldn't extract a discriminator value, use index-based fallback to ensure uniqueness\n // This prevents \"Discriminator with name 'unknown' already exists\" errors\n if (!discriminatorValue || discriminatorValue === 'unknown') {\n discriminatorValue = `option_${optionIndex}`;\n this.logDebug(`Could not extract discriminator value for union option ${optionIndex}, using fallback: ${discriminatorValue}`, {\n discriminatorKey,\n optionIndex\n });\n }\n\n // Store schema information for later inheritance model creation\n inheritanceSchemas.push({\n discriminatorKey,\n discriminatorValue: String(discriminatorValue),\n schema: inheritanceOptionSchema,\n zodSchema: option\n });\n } catch (error) {\n this.logger.warn(`Failed to process union inheritance option: ${describeCaughtError(error)}`);\n }\n }\n\n // Return the union root definition with discriminator key\n return {\n ...rootDefinition,\n discriminatorKey\n };\n }\n\n /**\n * Unwraps decorated Zod types to get the core type for instanceof checks\n * @param zodField The potentially decorated Zod field\n * @returns The core Zod type without decoration wrappers\n */\n private unwrapDecoratedType(zodField: z.ZodTypeAny): z.ZodTypeAny {\n // Use the centralized unwrapSchema function from zod-decorators\n return unwrapSchema(zodField);\n }\n\n /**\n * Handles ZodUnion types intelligently\n * @param zodUnion The Zod union to analyze\n * @returns Appropriate Mongoose type definition\n */\n private handleZodUnion(zodUnion: z.ZodTypeAny): any {\n const options = getZodDefArrayProperty(zodUnion, 'options');\n if (!options) {\n return { type: Schema.Types.Mixed };\n }\n\n // Collect all enum values and check if all options are string-like\n const enumValues: string[] = [];\n let allStringLike = true;\n\n for (const option of options) {\n if (!isZodTypeAny(option)) continue;\n\n const optionType = getZodType(option);\n\n // Handle enum (check for entries in Zod v4, or enum property for native enums)\n if (optionType === 'enum') {\n // Use centralized getEnumValues function\n const optionEnumValues = getEnumValues(option);\n enumValues.push(...optionEnumValues);\n continue;\n }\n\n // Handle ZodString (allows any string)\n if (optionType === 'string') {\n // String type allows any string value, so we just continue\n continue;\n }\n\n // If we encounter a non-string type, fall back to Mixed\n allStringLike = false;\n break;\n }\n\n // If all options are string-like (enum + string), return String with enum validation\n if (allStringLike) {\n if (enumValues.length > 0) {\n return {\n type: String,\n enum: [...new Set(enumValues)] // Remove duplicates\n };\n } else {\n return { type: String };\n }\n }\n\n // Fall back to Mixed for complex unions\n return { type: Schema.Types.Mixed };\n }\n\n /**\n * Gets the base Mongoose type for a Zod field\n * @param zodField The Zod field to get the type for\n * @param schemaCache Cache of created schemas for recursive types\n * @returns The base Mongoose type definition\n */\n private getBaseMongooseType(zodField: z.ZodTypeAny, schemaCache?: WeakMap<z.ZodTypeAny, Schema>): any {\n const zodType = getZodType(zodField);\n\n // Handle string types\n // In Zod v4, string schemas have type: \"string\"\n if (zodType === 'string') {\n const definition: any = { type: String };\n\n // Add string-specific validations\n // In Zod v4, checks are stored in def.checks array\n const checks = getZodDefArrayProperty(zodField, 'checks');\n if (checks) {\n\n for (const check of checks) {\n if (typeof check === 'object' && check !== null) {\n const checkKind = (check as Record<string, unknown>).kind;\n const checkValue = (check as Record<string, unknown>).value;\n\n if (checkKind === 'min' && typeof checkValue === 'number') {\n definition.minlength = checkValue;\n } else if (checkKind === 'max' && typeof checkValue === 'number') {\n definition.maxlength = checkValue;\n } else if (checkKind === 'regex' && checkValue instanceof RegExp) {\n definition.match = checkValue;\n }\n }\n }\n }\n\n return definition;\n }\n\n // Handle number types\n // In Zod v4, number schemas have type: \"number\" or \"int\"\n if (zodType === 'number' || zodType === 'int') {\n const definition: any = { type: Number };\n\n const checks = getZodDefArrayProperty(zodField, 'checks');\n if (checks) {\n\n for (const check of checks) {\n if (typeof check === 'object' && check !== null) {\n const checkKind = (check as Record<string, unknown>).kind;\n const checkValue = (check as Record<string, unknown>).value;\n\n if (checkKind === 'min' && typeof checkValue === 'number') {\n definition.min = checkValue;\n } else if (checkKind === 'max' && typeof checkValue === 'number') {\n definition.max = checkValue;\n }\n }\n }\n }\n\n return definition;\n }\n\n // Handle bigint types\n // In Zod v4, bigint schemas have type: \"bigint\"\n // Mongoose 6+ supports BigInt natively, which stores as BSON Long (64-bit)\n // For arbitrarily large bigints, we store as String for maximum precision\n if (zodType === 'bigint') {\n // Use String type for storage to preserve full precision of arbitrarily large bigints\n // The application layer handles conversion to/from BigInt\n return {\n type: String,\n get: (v: string | null | undefined) => v ? BigInt(v) : v,\n set: (v: bigint | string | null | undefined) => v !== null && v !== undefined ? String(v) : v\n };\n }\n\n // Handle boolean types\n // In Zod v4, boolean schemas have type: \"boolean\"\n if (zodType === 'boolean') {\n return { type: Boolean };\n }\n\n // Handle date types\n // In Zod v4, date schemas have type: \"date\"\n if (zodType === 'date') {\n return { type: Date };\n }\n\n // Handle enum types\n // In Zod v4, enum schemas have type: \"enum\" and values are in def.entries\n if (zodType === 'enum') {\n // Use centralized getEnumValues function\n const enumValues = getEnumValues(zodField);\n\n return {\n type: String,\n enum: enumValues\n };\n }\n\n // NOTE: In Zod v4, .brand() no longer creates a wrapper type.\n // Branded schemas report their underlying type (e.g., 'string') directly.\n // The branding is purely a TypeScript compile-time feature.\n // No special handling is needed for branded types in Zod v4.\n\n // Handle record types - z.record() represents plain objects with dynamic keys\n // In Zod v4, record schemas have type: \"record\"\n if (isZodRecord(zodField)) {\n // Default to Mixed for non-recursive records\n // Only use Map if we detect a recursive schema that requires it\n const valueType = getZodDefSchemaProperty(zodField, 'valueType');\n let mapValueType: any = null;\n\n if (valueType && isZodLazy(valueType)) {\n // For recursive records (like properties: z.record(z.lazy(...))), we MUST use Map with the schema\n // otherwise we lose the recursive structure.\n\n // Try to resolve lazy type from cache if available\n if (schemaCache) {\n const getter = getZodDefFunctionProperty(valueType, 'getter');\n if (getter) {\n const inner = getter();\n if (schemaCache.has(inner)) {\n mapValueType = schemaCache.get(inner);\n }\n }\n }\n }\n\n // If we found a recursive schema, return Map\n if (mapValueType) {\n return { type: Map, of: mapValueType };\n }\n\n // Default to Mixed for non-recursive records\n return { type: Schema.Types.Mixed };\n }\n\n // Handle Set types\n // In Zod v4, set schemas have type: \"set\"\n // Sets are stored as arrays in MongoDB with getter/setter for conversion\n if (zodType === 'set') {\n const valueType = getZodDefSchemaProperty(zodField, 'valueType');\n\n // Try to determine the value type for the Set\n let setValueType: any = Schema.Types.Mixed;\n if (valueType) {\n const valueTypeDefinition = this.getBaseMongooseType(valueType, schemaCache);\n if (valueTypeDefinition?.type) {\n setValueType = valueTypeDefinition.type;\n }\n }\n\n return {\n type: [setValueType],\n get: (v: any[] | null | undefined) => v ? new Set(v) : v,\n set: (v: Set<any> | any[] | null | undefined) => {\n if (v === null || v === undefined) return v;\n return v instanceof Set ? Array.from(v) : v;\n }\n };\n }\n\n // Handle Map types\n // In Zod v4, map schemas have type: \"map\"\n if (zodType === 'map') {\n const valueType = getZodDefSchemaProperty(zodField, 'valueType');\n\n // Try to determine the value type for the Map\n let mapValueType: any = Schema.Types.Mixed;\n if (valueType) {\n const valueTypeDefinition = this.getBaseMongooseType(valueType, schemaCache);\n if (valueTypeDefinition?.type) {\n mapValueType = valueTypeDefinition.type;\n }\n }\n\n return { type: Map, of: mapValueType };\n }\n\n // Handle any/unknown types\n // In Zod v4, any/unknown schemas have type: \"any\" or \"unknown\"\n if (zodType === 'any' || zodType === 'unknown') {\n return { type: Schema.Types.Mixed };\n }\n\n // Handle void/undefined types\n // In Zod v4, void/undefined schemas have type: \"void\" or \"undefined\"\n if (zodType === 'void' || zodType === 'undefined') {\n return { type: Schema.Types.Mixed };\n }\n\n // Handle never type\n // In Zod v4, never schemas have type: \"never\"\n if (zodType === 'never') {\n return { type: Schema.Types.Mixed };\n }\n\n // Fallback for unknown types\n this.logger.warn(`[ZodToMongoose] Unknown Zod type, using Mixed. Type: ${typeof zodField}`);\n return { type: Schema.Types.Mixed };\n }\n\n // =================================================================\n // VALIDATION AND HELPER METHODS\n // =================================================================\n\n /**\n * Validates and fixes field types to ensure Mongoose compatibility\n * @param mongooseDefinition The mongoose schema definition to validate\n * @param resourceType The resource type for debugging\n */\n private validateAndFixFieldTypes(mongooseDefinition: any, resourceType: string): void {\n this.validateFieldsRecursively(mongooseDefinition, resourceType, '');\n }\n\n /**\n * Recursively validates and fixes field types\n * @param obj The object to validate\n * @param resourceType The resource type for debugging\n * @param path The current field path for debugging\n */\n /**\n * Checks if a value is a Mongoose Schema instance or looks like one\n * More robust than instanceof to handle different Schema versions/instances\n */\n private isSchemaLike(value: any): boolean {\n if (!value || typeof value !== 'object') return false;\n // Check instanceof first (most reliable)\n if (value instanceof Schema) {\n return true;\n }\n // Check for Schema constructor\n if (value.constructor && value.constructor.name === 'Schema') {\n return true;\n }\n // Check for Schema-specific properties as fallback\n // A real Schema instance has: paths, methods, statics, virtuals, options\n // Even newly created empty schemas have these\n return (\n typeof value.paths === 'object' &&\n typeof value.methods === 'object' &&\n typeof value.statics === 'object' &&\n typeof value.virtuals === 'object' &&\n typeof value.options === 'object'\n );\n }\n\n\n private validateFieldsRecursively(obj: any, resourceType: string, path: string): void {\n if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {\n return;\n }\n\n\n // CRITICAL: If obj itself is a Schema instance, do not iterate over it\n // Schema instances have internal properties that should not be validated as fields\n if (this.isSchemaLike(obj)) {\n return;\n }\n\n for (const [fieldName, fieldValue] of Object.entries(obj)) {\n const fieldPath = path ? `${path}.${fieldName}` : fieldName;\n\n // CRITICAL: If fieldValue is a Schema instance, skip it entirely\n // Schema instances are already valid and should not be validated\n if (this.isSchemaLike(fieldValue)) {\n continue;\n }\n\n if (fieldValue && typeof fieldValue === 'object' && !Array.isArray(fieldValue)) {\n // CRITICAL: If fieldValue has a 'type' property that is a Schema instance,\n // skip validation entirely - it's already properly wrapped\n if ('type' in fieldValue && this.isSchemaLike(fieldValue.type)) {\n continue;\n }\n\n // Check if this is a field definition (should have a type property or be a nested object)\n const hasTypeProperty = 'type' in fieldValue;\n const hasNestedFields = Object.keys(fieldValue).some(key =>\n key !== 'default' && key !== 'required' && key !== '_id' && key !== 'type' &&\n typeof fieldValue[key] === 'object'\n );\n\n // Valid Mongoose schema properties that don't require a 'type' property\n const validMongooseProperties = [\n 'match', 'min', 'max', 'minlength', 'maxlength',\n 'enum', 'required', 'default', 'validate', 'get', 'set',\n 'transform', 'alias', 'immutable', 'sparse', 'unique',\n 'index', 'select', 'populate', 'discriminator', '_id'\n ];\n\n const hasOnlyValidMongooseProperties = Object.keys(fieldValue).every(key =>\n validMongooseProperties.includes(key)\n );\n\n if (!hasTypeProperty && !hasNestedFields && !hasOnlyValidMongooseProperties) {\n // This field is missing a type property - fix it\n this.logger.warn(`[ZodToMongoose] FIXING field '${fieldPath}' in resource '${resourceType}': Missing type property`);\n this.logger.warn(`[ZodToMongoose] Field value keys: ${Object.keys(fieldValue as Record<string, unknown>).join(', ')}`);\n\n let mongooseType: any = Schema.Types.Mixed; // Default fallback\n\n // Try to infer type from default value if available\n if ('default' in fieldValue) {\n const defaultValue = fieldValue.default;\n if (typeof defaultValue === 'boolean') {\n mongooseType = Schema.Types.Boolean;\n } else if (typeof defaultValue === 'string') {\n mongooseType = Schema.Types.String;\n } else if (typeof defaultValue === 'number') {\n mongooseType = Schema.Types.Number;\n } else if (defaultValue instanceof Date) {\n mongooseType = Schema.Types.Date;\n }\n }\n // For fields with only 'required: true', assume String as a safe default\n else if ('required' in fieldValue && Object.keys(fieldValue).length === 1) {\n mongooseType = String;\n }\n\n // Fix the field definition\n obj[fieldName] = {\n type: mongooseType,\n ...fieldValue\n };\n\n this.logger.warn(`[ZodToMongoose] Fixed to: ${JSON.stringify(obj[fieldName])}`);\n } else if (hasNestedFields) {\n // Recursively validate nested objects, but exclude valid Mongoose properties AND type\n const validMongooseKeys = ['match', 'min', 'max', 'minlength', 'maxlength', 'enum', 'required', 'default', 'validate', 'get', 'set', 'transform', 'alias', 'immutable', 'sparse', 'unique', 'index', 'select', 'populate', 'discriminator', '_id', 'type'];\n const nestedFields = Object.fromEntries(\n Object.entries(fieldValue).filter(([key]) => !validMongooseKeys.includes(key))\n );\n this.validateFieldsRecursively(nestedFields, resourceType, fieldPath);\n } else if (hasTypeProperty && fieldValue.type && typeof fieldValue.type === 'object') {\n // CRITICAL: If fieldValue.type is a Schema instance, DO NOT validate it\n // Schema instances have internal properties (methods, options, etc.) that should not be treated as fields\n if (!this.isSchemaLike(fieldValue.type)) {\n // This is a nested object type (plain object definition) - validate its contents\n this.validateFieldsRecursively(fieldValue.type, resourceType, fieldPath);\n }\n // If it's a Schema instance, we skip validation - it's already a valid Mongoose schema\n }\n }\n }\n }\n\n\n // =================================================================\n // UTILITY AND HELPER METHODS\n // =================================================================\n\n /**\n * The MongoDB collection this resource's model is built over.\n *\n * `USER_SELF*` resources deliberately share their non-SELF counterpart's\n * collection — separate models, one set of rows — so the self door and the\n * admin door address the same records.\n *\n * Delegates to the shared authority\n * (`RESOURCE_SHARED_PERSISTENCE_COLLECTION_ALIASES` in `@wildo-ai/saas-models`)\n * rather than declaring the mapping here. This method is what actually creates\n * and reads the collection, so a local copy makes this the de-facto truth while\n * other consumers — the aggregation collection resolver, and the boot-time\n * retention-coherence guard — quietly disagree with it. That has already\n * happened once: the aggregation resolver returned the FK field identifier\n * instead of the collection, and every aggregation silently read a\n * non-existent collection.\n */\n private getCollectionNameForResource(resourceType: ResourceType): string {\n return resolveSharedPersistenceCollectionName(resourceType);\n }\n\n /**\n * Make the schema paths owned by the Mongoose `timestamps` option\n * (`SCHEMA_DEFAULT_OPTIONS.timestamps` → createdAt/updatedAt) genuinely\n * plugin-owned: drop their `required` validators AND their `default`.\n *\n * Resource zod schemas declare `createdAt`/`updatedAt` as non-optional —\n * truthful for every PERSISTED document — so the zod→mongoose field\n * conversion marks those paths `required: true`. Population, however, is\n * infrastructure-owned: the Mongoose timestamps plugin sets both fields in\n * a pre('save') hook, and since Mongoose 9 document validation runs BEFORE\n * pre('save') middleware (ordering change vs ≤8). A `required` validator on\n * a plugin-populated timestamp therefore rejects EVERY insert with\n * \"Path `createdAt` is required\" — reproduced standalone against\n * mongoose@9.3.3 and recovered 2026-06-12 on the Wonder Todos todoLists\n * create flow (first dogfooded resource CREATE on Mongoose 9).\n *\n * Dropping `required` at the DB layer loses nothing: the plugin\n * deterministically populates both fields on every insert/update, and the\n * zod layer keeps the non-optional read contract. Rejected alternatives:\n * stamping the dates in the repository enrichment (two writers for the\n * same fields, contradicts the repository's \"timestamps are handled by\n * Mongoose\" contract) and making the zod fields optional (weakens the read\n * DTO truth for all consumers).\n *\n * ## Why the `default` goes too (2026-08-11)\n *\n * \"Timestamps are handled by Mongoose\" is the stated contract, and a `default`\n * on those paths quietly breaks it — Mongoose applies a default at DOCUMENT\n * CONSTRUCTION and the timestamps plugin then defers to the already-set path,\n * so the default WINS and the plugin never writes. That made the zod-declared\n * `.default(() => new Date())` the real writer of every `createdAt`, which is\n * how the model-build freeze (see `mongooseDefault` in the default-unwrap\n * branch) reached persistence at all.\n *\n * Passing the thunk through already fixes the freeze. This removal fixes the\n * OWNERSHIP: with the default gone there is exactly ONE writer for these two\n * paths, the one the contract names, instead of two that happen to agree.\n * Note that it is the create path being stripped — `.excludeFromCreate()` —\n * that lets the DB-layer default apply in the first place, so this is not a\n * theoretical tidy-up; it is the seam where the two writers met.\n *\n * Scope is deliberately narrow: ONLY the paths the plugin owns. Every other\n * defaulted field keeps its (now per-document) default.\n */\n private relaxPluginOwnedTimestampRequiredValidators(mongooseSchema: Schema): void {\n const timestampsOption = (mongooseSchema as any).options?.timestamps as\n | boolean\n | { createdAt?: string | boolean; updatedAt?: string | boolean }\n | undefined;\n if (!timestampsOption) {\n return;\n }\n\n const resolvePathName = (value: string | boolean | undefined, fallback: string): string | null => {\n if (value === false) return null;\n return typeof value === 'string' ? value : fallback;\n };\n const timestampPathNames = typeof timestampsOption === 'object'\n ? [resolvePathName(timestampsOption.createdAt, 'createdAt'), resolvePathName(timestampsOption.updatedAt, 'updatedAt')]\n : ['createdAt', 'updatedAt'];\n\n for (const pathName of timestampPathNames) {\n if (!pathName) continue;\n const schemaType = mongooseSchema.path(pathName);\n if (schemaType) {\n schemaType.required(false);\n // Hand the path back to the plugin. `SchemaType#default(undefined)` is\n // Mongoose's documented way to REMOVE a default (as opposed to setting\n // one to `undefined`), and it clears `defaultValue` so nothing is applied\n // at document construction.\n schemaType.default(undefined);\n }\n }\n }\n\n /**\n * Standardizes toObject/toJSON to serialize ObjectId fields as strings.\n * Keeps internal schema types as ObjectId for queries, but outputs strings for DTO parsing.\n */\n private applyStandardTransforms(mongooseSchema: Schema): void {\n const hasToObject = (mongooseSchema as any).options?.toObject;\n const hasToJSON = (mongooseSchema as any).options?.toJSON;\n\n mongooseSchema.set('toObject', {\n ...(hasToObject || {}),\n transform: (doc: any, ret: any) => {\n this.serializeObjectIds(ret);\n if (typeof (hasToObject as any)?.transform === 'function') {\n (hasToObject as any).transform(doc, ret);\n }\n return ret;\n }\n });\n\n mongooseSchema.set('toJSON', {\n ...(hasToJSON || {}),\n transform: (doc: any, ret: any) => {\n this.serializeObjectIds(ret);\n if (typeof (hasToJSON as any)?.transform === 'function') {\n (hasToJSON as any).transform(doc, ret);\n }\n return ret;\n }\n });\n }\n\n private serializeObjectIds(obj: any): void {\n if (!obj || typeof obj !== 'object') return;\n const stack: any[] = [obj];\n while (stack.length) {\n const current = stack.pop();\n for (const key of Object.keys(current)) {\n const value = current[key];\n if (value && typeof value === 'object') {\n // ObjectId array\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const v = value[i] as any;\n if (v && typeof v === 'object' && (v as any)?._bsontype === 'ObjectId') {\n value[i] = String(v);\n } else if (v && typeof v === 'object') {\n stack.push(v);\n }\n }\n } else if ((value as any)?._bsontype === 'ObjectId' || value instanceof (Types as any).ObjectId) {\n current[key] = String(value);\n } else {\n stack.push(value);\n }\n }\n }\n }\n }\n\n /**\n * Determines if a Zod field is required\n * @param zodField The Zod field to check\n * @returns True if the field is required\n */\n private isFieldRequired(zodField: z.ZodTypeAny): boolean {\n // Check if it's wrapped in ZodOptional or ZodNullable\n // In Zod v4, optional/nullable schemas have type: \"optional\" or \"nullable\"\n if (isZodOptional(zodField) || isZodNullable(zodField)) {\n return false;\n }\n\n // Check if it has a default value\n // In Zod v4, default schemas have type: \"default\"\n if (isZodDefault(zodField)) {\n return false;\n }\n\n // Otherwise, it's required\n return true;\n }\n\n /**\n * Applies indexes to a Mongoose schema\n * @param mongooseSchema The schema to apply indexes to\n * @param indexesToApply Array of field paths to index\n * @param uniqueIndexesToApply Array of unique index info with paths and params\n * @param ttlIndexesToApply Array of TTL index info with paths and params\n * @param resourceType Optional resource type for diagnostic logging\n */\n private applyIndexesToSchema(\n mongooseSchema: Schema,\n indexesToApply: string[],\n uniqueIndexesToApply: UniqueIndexInfo[] = [],\n ttlIndexesToApply: TtlIndexInfo[] = [],\n resourceType?: string,\n resourceConfiguration?: RetentionGovernanceSignal,\n ): void {\n const appliedPaths = new Set<string>();\n\n // First, collect all paths that will have unique indexes to avoid duplicates\n const uniqueIndexPaths = new Set<string>();\n for (const uniqueInfo of uniqueIndexesToApply) {\n const normalizedPath = (uniqueInfo.path || '').replace(/\\[\\]/g, '').trim();\n if (normalizedPath) {\n uniqueIndexPaths.add(normalizedPath);\n }\n }\n\n // Collect paths that already have a schema-level index registered by\n // applyRelationshipForeignKeyPersistence (which runs before this method).\n // Those are relationship-derived unique indexes for 1:1 FK fields. Adding\n // a plain index on the same path would trigger Mongoose's \"Duplicate schema\n // index\" warning because Mongoose sees two index definitions for the same\n // single-field key — the unique one from the relationship and the non-unique\n // one from the Zod decorator.\n const alreadyIndexedPaths = new Set<string>();\n for (const [indexSpec] of mongooseSchema.indexes()) {\n const keys = Object.keys(indexSpec as Record<string, unknown>);\n // Only pre-filter single-field indexes — compound indexes are composed of\n // multiple fields and we should not block plain indexing of the individual\n // participating fields.\n if (keys.length === 1) {\n alreadyIndexedPaths.add(keys[0]);\n }\n }\n\n // Apply regular indexes\n for (const rawPath of indexesToApply) {\n try {\n // Normalize array notation and trim whitespace\n const normalizedPath = (rawPath || '').replace(/\\[\\]/g, '').trim();\n\n // Skip invalid or empty paths\n if (!normalizedPath) continue;\n\n // Never attempt to index _id (MongoDB manages it). Also skip nested '.*._id'\n if (normalizedPath === '_id' || normalizedPath.endsWith('._id')) {\n continue;\n }\n\n // Skip paths that will have unique indexes (unique indexes already create an index)\n if (uniqueIndexPaths.has(normalizedPath)) {\n continue;\n }\n\n // Skip paths that already have a schema-level index from\n // applyRelationshipForeignKeyPersistence (relationship-derived unique\n // indexes for 1:1 FK fields). The unique index supersedes a plain one;\n // registering both causes a \"Duplicate schema index\" warning.\n if (alreadyIndexedPaths.has(normalizedPath)) {\n continue;\n }\n\n // De-duplicate\n if (appliedPaths.has(normalizedPath)) continue;\n appliedPaths.add(normalizedPath);\n\n // A plain index on the field, ENDED ON `_id` (#1915).\n //\n // Every paged read now orders by `<key>, _id` (`completeToTotalOrder`), so that rows tied on the key are\n // served exactly once across pages. A single-field `{ <key>: 1 }` index cannot serve that sort: measured on\n // MongoDB 8.2 over 50,000 rows, `sort({ createdAt: -1 })` walked the index and examined 20 documents for a\n // page, while `sort({ createdAt: -1, _id: -1 })` fell back to COLLSCAN + an in-memory SORT examining all\n // 50,000. `{ <key>: 1, _id: 1 }` restores the index walk in both directions and still serves every query the\n // single-field index did, since `<key>` is its prefix. It costs one ObjectId per index entry.\n //\n // PostgreSQL owes nothing equivalent: the planner turns a `<key>` btree into an Incremental Sort over the\n // tied groups (measured on the live Wonder Todos database), so no migration follows from this.\n //\n // Rejected: extending only `createdAt`. The default ordering is `createdAt`, but a declared `sortFields[0]`\n // (a status, an attempt count) is ordered the same way, and which fields an operation sorts by is not known\n // here. Every plain index is a potential sort index, so every one ends on `_id`.\n const indexSpec: Record<string, 1> = { [normalizedPath]: 1, [REPOSITORY_ROW_IDENTITY_FIELD]: 1 };\n this.logDebug(`[ZodToMongoose] Applying plain index on '${normalizedPath}' (ended on _id)`, { resourceType });\n mongooseSchema.index(indexSpec);\n } catch (error) {\n this.logger.warn(`[ZodToMongoose] Failed to apply index on path '${rawPath}': ${describeCaughtError(error)}`);\n }\n }\n\n // Apply unique indexes\n const appliedUniquePaths = new Set<string>();\n for (const uniqueInfo of uniqueIndexesToApply) {\n try {\n // Normalize array notation and trim whitespace\n const normalizedPath = (uniqueInfo.path || '').replace(/\\[\\]/g, '').trim();\n\n // Skip invalid or empty paths\n if (!normalizedPath) continue;\n\n // Never attempt to index _id (MongoDB manages it). Also skip nested '.*._id'\n if (normalizedPath === '_id' || normalizedPath.endsWith('._id')) {\n continue;\n }\n\n // De-duplicate within this invocation\n if (appliedUniquePaths.has(normalizedPath)) continue;\n\n // Skip paths that already have a schema-level index from\n // applyRelationshipForeignKeyPersistence. For single-field unique indexes,\n // re-registering the same key pattern triggers Mongoose's \"Duplicate schema\n // index\" warning. The relationship-derived index supersedes the Zod-derived one\n // because it may carry a partialFilterExpression for sparse semantics.\n if (alreadyIndexedPaths.has(normalizedPath)) {\n this.logDebug(`[ZodToMongoose] Skipped duplicate unique index on '${normalizedPath}' (already registered by relationship FK persistence)`, { resourceType });\n continue;\n }\n\n appliedUniquePaths.add(normalizedPath);\n\n const params = uniqueInfo.params || {};\n const scope = params.scope || 'global';\n const sparse = params.sparse !== false; // Default to true\n\n // Create index spec based on scope or compoundWith\n const indexSpec: Record<string, 1> = {};\n\n if (params.compoundWith) {\n // Resolve compoundWith field — handles polymorphic renames automatically\n let compoundField = params.compoundWith;\n if (!(mongooseSchema as any).paths?.[compoundField]) {\n const suffix = compoundField.charAt(0).toUpperCase() + compoundField.slice(1);\n const schemaFields = Object.keys((mongooseSchema as any).paths || {});\n const match = schemaFields.find(p => p.endsWith(suffix) && p !== normalizedPath);\n if (match) {\n compoundField = match;\n } else {\n this.logger.warn(`[ZodToMongoose] compoundWith field '${params.compoundWith}' not found in schema paths (suffix '${suffix}'). Available: ${schemaFields.join(', ')}`);\n }\n }\n indexSpec[compoundField] = 1;\n indexSpec[normalizedPath] = 1;\n } else if (scope === 'organization') {\n // Compound unique index: organizationId + field\n indexSpec['organizationId'] = 1;\n indexSpec[normalizedPath] = 1;\n } else if (scope === 'user') {\n // Compound unique index: createdByUserId + field\n indexSpec['createdByUserId'] = 1;\n indexSpec[normalizedPath] = 1;\n } else {\n // Global unique index\n indexSpec[normalizedPath] = 1;\n }\n\n // Apply unique index with options.\n //\n // G-BKEY: on a retention-governed resource, uniqueness covers only non-retained rows, so a\n // hidden retained row can neither block re-creation of its key nor reject the scrub's repeated\n // mask/null values (see buildRetentionPartialFilterExpression).\n //\n // ⚠️ `sparse` and `partialFilterExpression` are MUTUALLY EXCLUSIVE in MongoDB — the server\n // rejects the combination with `CannotCreateIndex`. Worse, the framework relies on Mongoose's\n // background `autoIndex` and never awaits `Model.init()`, so that rejection surfaces only as a\n // console error and the index is NEVER CREATED: uniqueness would be silently LOST rather than\n // scoped. So when the retention filter applies we express the sparse intent INSIDE the partial\n // filter (`$exists: true`), which is the MongoDB-legal equivalent and matches the shape already\n // used by the relationship-FK unique indexes below.\n // A COMPOUND index (scope organization/user, or `compoundWith`) cannot express \"skip when the\n // optional field is absent\" via `sparse: true`: MongoDB only sparse-EXCLUDES a document when it\n // is missing EVERY indexed key, and the scope key (`organizationId`/`createdByUserId`) or the\n // compound partner is always present — so every document missing the optional field indexes as\n // `(scope, null)` and the unique constraint collides on the FIRST such pair. The MongoDB-legal\n // equivalent is a partial filter requiring the field to exist. This is the same `$exists: true`\n // shape used on the retention path above and by the relationship-FK unique indexes below; a\n // SINGLE-key sparse index behaves correctly, so it keeps plain `sparse: true`.\n const isCompoundIndex = Object.keys(indexSpec).length > 1;\n const indexOptions: { unique: true; sparse?: boolean; partialFilterExpression?: Record<string, unknown> } = { unique: true };\n const retentionPartialFilter = this.buildRetentionPartialFilterExpression(resourceConfiguration);\n if (retentionPartialFilter) {\n indexOptions.partialFilterExpression = sparse\n ? { ...retentionPartialFilter, [normalizedPath]: { $exists: true } }\n : retentionPartialFilter;\n } else if (sparse && isCompoundIndex) {\n // Compound + sparse: express the sparse intent as a partial filter so absent-field rows are\n // genuinely excluded (a plain compound `sparse: true` would silently collide on `(scope, null)`).\n indexOptions.partialFilterExpression = { [normalizedPath]: { $exists: true } };\n } else if (sparse) {\n indexOptions.sparse = true;\n }\n\n mongooseSchema.index(indexSpec, indexOptions);\n } catch (error) {\n this.logger.warn(`[ZodToMongoose] Failed to apply unique index on path '${uniqueInfo.path}': ${describeCaughtError(error)}`);\n }\n }\n\n // Apply TTL indexes\n // MongoDB TTL indexes automatically delete documents after a specified time\n // TTL indexes can only be applied to Date fields\n const appliedTtlPaths = new Set<string>();\n for (const ttlInfo of ttlIndexesToApply) {\n try {\n // Normalize array notation and trim whitespace\n const normalizedPath = (ttlInfo.path || '').replace(/\\[\\]/g, '').trim();\n\n // Skip invalid or empty paths\n if (!normalizedPath) continue;\n\n // De-duplicate\n if (appliedTtlPaths.has(normalizedPath)) continue;\n appliedTtlPaths.add(normalizedPath);\n\n const params = ttlInfo.params;\n const expireAfterSeconds = params.expireAfterSeconds;\n\n // Create TTL index on the field\n const indexSpec: Record<string, 1> = {};\n indexSpec[normalizedPath] = 1;\n\n // Apply TTL index with expireAfterSeconds option\n mongooseSchema.index(indexSpec, { expireAfterSeconds });\n\n this.logDebug(`Applied TTL index on path '${normalizedPath}' with expireAfterSeconds: ${expireAfterSeconds}`);\n } catch (error) {\n this.logger.warn(`[ZodToMongoose] Failed to apply TTL index on path '${ttlInfo.path}': ${describeCaughtError(error)}`);\n }\n }\n }\n\n /**\n * Materialise a top-level `.businessKeySet([...])` decorator as a\n * Mongo compound `{ unique: true }` index on the resulting schema.\n *\n * **Why this exists** (Phase 3.2 review fix R2-4): the framework's\n * Zod-decorator surface declares two business-key shapes —\n * field-level `.isBusinessKey()` (single-field identity) and\n * object-level `.businessKeySet([...])` (composite identity, e.g.\n * `(seedKey, scopeKind, relatedResourceType, relatedId, seedVersion)`\n * for `DataSeedRun`). The single-field shape was already enforced\n * at the DB layer because `isBusinessKey` flows through the existing\n * `isUnique` path inside `convertZodTypeToMongooseDefinition`. The\n * composite shape was NOT — `.businessKeySet([...])` lived as Zod\n * metadata only, consumed by `business-key-resolver.shared.utils.ts`\n * (filter builder) and `findByBusinessKey` callers, but invisible\n * to MongoDB. That left every consumer doing find-then-create\n * race-prone (e.g. `DataSeedDispatcher.startRun` could insert two\n * ledger rows under concurrent boots).\n *\n * **Cardinality contract**:\n * - length === 0 / undefined → no-op (no decorator declared)\n * - length === 1 → no-op (the single field necessarily also carries\n * `.isBusinessKey()` per the decorator's validation pass, which\n * flows into `isUnique` and gets a single-field unique index\n * elsewhere — adding a \"compound\" index over one field would be\n * redundant)\n * - length ≥ 2 → compound `{ field1: 1, field2: 1, …, unique: true }`\n *\n * **Sparse handling is OFF BY DEFAULT**: a partial business key\n * (some fields null, others set) MUST collide with another partial\n * key bearing the same shape. For `DataSeedRun.CUSTOM` scope rows\n * with `relatedId === null`, sparse: true would let two rows with\n * `{seedKey: 'x', scopeKind: CUSTOM, relatedResourceType: null,\n * relatedId: null, seedVersion: 1}` co-exist — exactly the\n * collision F-4 widened the key to prevent. Mongo treats `null` as\n * a real value in non-sparse compound indexes, which is what the\n * business-key contract requires.\n *\n * A key whose member is optional IN THE DOMAIN opts out per member\n * with `skipRowsMissing`. `ORGANIZATION_UNITS`' \"code unique among\n * siblings\" is the motivating case: any number of siblings may carry\n * NO code, so rows without one must sit outside the constraint\n * entirely, while rows WITH one still collide. Only the listed\n * members are scoped — an unlisted optional member keeps the\n * null-collides default, which is what makes \"two roots may not\n * share a code\" work (an absent `parentUnitId` indexes as null, so\n * roots collide with each other, exactly as intended).\n *\n * The opt-out is expressed as `$exists: true` inside\n * `partialFilterExpression` rather than as `sparse: true` because\n * the two are MUTUALLY EXCLUSIVE in MongoDB and a retention-governed\n * resource already needs the partial filter. Combining them is\n * rejected by the server with `CannotCreateIndex`, and since the\n * framework never awaits `Model.init()`, that rejection would\n * surface only as a console error — the index would simply never be\n * created and uniqueness would be silently LOST.\n *\n * **Path validation**: every declared field name must exist in the\n * resolved Mongoose schema. The Zod-decorator validator already\n * enforces this at decoration time (`businessKeySet([...]) references\n * field(s) not present in the schema shape: …`), so a runtime\n * mismatch here would indicate a regression in the decorator\n * validation. We log a warning + skip rather than throw to avoid\n * blocking application boot on a non-critical index issue.\n */\n /**\n * Partial-index predicate that stops a UNIQUE index from permanently blocking re-creation of a\n * business key held by an impersonalized-and-retained row (gate **G-BKEY**).\n *\n * A RETAINED row is hidden from every normal read, so a find-then-create / upsert path does not see\n * it — but a plain unique index still does. The INSERT branch then collides with `E11000` on a row\n * the caller cannot see: a permanent re-creation lockout AND an existence oracle. Scoping the\n * uniqueness to non-retained rows resolves it at the DB layer while PRESERVING the retained row's\n * own business key (severing it instead would destroy the audit identity — an invoice must keep its\n * invoice number).\n *\n * Uniqueness among retained rows is deliberately dropped: they are immutable historical records, and\n * the scrub intentionally writes identical values (a shared mask constant, or null) across a batch —\n * which is exactly what a still-covering unique index would reject.\n *\n * Uses PLAIN EQUALITY, which every MongoDB version supporting partial indexes accepts. Expressing\n * \"any of several non-retained states\" would need `$in`, whose partial-index support is\n * version-dependent — so a future third `RetentionStatus` member fails LOUD here rather than\n * silently narrowing every unique index on every retention-governed resource.\n *\n * This is the INVERTED expression of the hide rule — it selects the rows the hide KEEPS — which is\n * the most dangerous kind of duplicate, because it drifts in the opposite direction and fails\n * silently (a lost uniqueness constraint, or an erasure that aborts on E11000). Both the status it\n * names and the field it names therefore come from the single retention authority, derived from the\n * same hidden-status constant the hide predicate negates; this method owns only the Mongo-specific\n * \"must be a plain equality\" constraint and the error it raises.\n */\n private buildRetentionPartialFilterExpression(\n resourceConfiguration?: RetentionGovernanceSignal,\n ): Record<string, unknown> | undefined {\n if (!isRetentionGovernedResource(resourceConfiguration)) {\n return undefined;\n }\n const visibleStatus = resolveSoleVisibleRetentionStatus();\n if (visibleStatus === undefined) {\n const visibleStatuses = getVisibleRetentionStatuses();\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED,\n context: {\n message:\n `RetentionStatus now has ${visibleStatuses.length} non-retained members, so the unique-index ` +\n `partial filter can no longer be a plain equality. Update buildRetentionPartialFilterExpression ` +\n `(and verify the target MongoDB supports the operator you choose) before adding the member.`,\n nonRetainedStatuses: visibleStatuses,\n },\n });\n }\n return buildRetentionVisibleRowsEqualityFragment(visibleStatus);\n }\n\n private applyBusinessKeyCompoundUniqueIndex(\n mongooseSchema: Schema,\n zodSchema: z.ZodTypeAny,\n resourceConfiguration?: RetentionGovernanceSignal,\n ): void {\n const businessKeyParams = getBusinessKeySetParams(zodSchema);\n const businessKeyFields = businessKeyParams?.fields;\n if (!businessKeyFields || businessKeyFields.length < 2) {\n return;\n }\n\n const schemaPaths = Object.keys((mongooseSchema as any).paths ?? {});\n const missing = businessKeyFields.filter((f) => !schemaPaths.includes(f));\n if (missing.length > 0) {\n this.logger.warn(\n `[ZodToMongoose] businessKeySet declared field(s) not present in resolved Mongoose schema — skipping compound unique index: ${missing.join(', ')}. Available paths: ${schemaPaths.join(', ')}`,\n );\n return;\n }\n\n const indexSpec: Record<string, 1> = {};\n for (const field of businessKeyFields) {\n indexSpec[field] = 1;\n }\n\n try {\n // Two independent reasons to narrow the index, which is why they are MERGED rather than\n // chosen between:\n // - G-BKEY: scope the uniqueness to non-retained rows so a retained row's business key\n // cannot permanently lock out re-creation (see buildRetentionPartialFilterExpression).\n // - `skipRowsMissing`: take rows that omit a domain-optional member out of the constraint.\n // A retention-governed resource declaring `skipRowsMissing` needs BOTH predicates; keeping\n // only one would either lose the re-creation escape hatch or re-collide the key-less rows.\n const retentionPartialFilter = this.buildRetentionPartialFilterExpression(resourceConfiguration);\n const presencePartialFilter = (businessKeyParams?.skipRowsMissing ?? []).reduce<Record<string, unknown>>(\n (accumulator, field) => {\n accumulator[field] = { $exists: true };\n return accumulator;\n },\n {},\n );\n const partialFilterExpression: Record<string, unknown> = { ...retentionPartialFilter, ...presencePartialFilter };\n const hasPartialFilter = Object.keys(partialFilterExpression).length > 0;\n\n mongooseSchema.index(indexSpec, {\n unique: true,\n ...(hasPartialFilter ? { partialFilterExpression } : {}),\n });\n this.logDebug(\n `Applied businessKeySet compound unique index: { ${businessKeyFields.join(', ')} }`,\n {\n retentionScoped: !!retentionPartialFilter,\n presenceScopedFields: businessKeyParams?.skipRowsMissing ?? [],\n },\n );\n } catch (error) {\n this.logger.warn(\n `[ZodToMongoose] Failed to apply businessKeySet compound unique index on { ${businessKeyFields.join(', ')} }: ${describeCaughtError(error)}`,\n );\n }\n }\n\n /**\n * Materialise relationship-derived FK persistence behavior.\n *\n * The shared relationship factory compiles authored topology into\n * `resolvedSemantics.persistence`. Storage adapters consume that runtime\n * contract instead of re-deriving from raw cardinality/nature. This keeps the\n * developer-facing declaration small while making FK materialization and\n * uniqueness a first-class framework consequence of relationship meaning.\n *\n * The contract's `holderResourceType` is the ONLY resource this FK may be\n * materialized/validated on. Positional `resourceType1`/`resourceType2`\n * checks are not a holder signal: declaration order is author-dependent\n * (parent-first vs child-first), and gating on `resourceType2` synthesizes\n * required FK columns onto the referenced TARGET of every child-first\n * relationship — e.g. the `users` model growing required\n * `postedByUserId`/`createdByUserId` paths from inbound\n * `(<holder>, USERS, MANY, ONE)` references, which fails validated saves of\n * every user (self-registration).\n *\n * Scope note: this method iterates the parent + self relationship buckets of\n * the resource under build. A child-first relationship lives in its HOLDER's\n * child bucket, so its authored FK column is governed by the Zod schema\n * conversion alone — relationship-level required/unique enforcement for the\n * child bucket is intentionally not active here (activating it is a separate\n * coherence decision across existing authored schemas).\n */\n private applyRelationshipForeignKeyPersistence(\n mongooseSchema: Schema,\n resourceConfiguration?: Partial<ResourceConfiguration<any, any, any>> & {\n resourceRelationships?: {\n parentRelationships?: ResourceRelationship[];\n selfRelationships?: ResourceRelationship[];\n } | ResourceRelationship[];\n },\n applyUniqueIndexes = true,\n ): void {\n if (!resourceConfiguration?.resourceIdentifier || !resourceConfiguration.resourceRelationships) {\n return;\n }\n\n const relationships = Array.isArray(resourceConfiguration.resourceRelationships)\n ? resourceConfiguration.resourceRelationships\n : [\n ...(resourceConfiguration.resourceRelationships.parentRelationships ?? []),\n ...(resourceConfiguration.resourceRelationships.selfRelationships ?? []),\n ];\n const indexedFields = new Set<string>();\n\n for (const relationship of relationships) {\n const foreignKeyPersistence = (relationship.resolvedSemantics as {\n persistence?: {\n foreignKey?: RelationshipPersistenceForeignKeyContract;\n };\n } | undefined)?.persistence?.foreignKey;\n if (\n !foreignKeyPersistence?.materializeField ||\n foreignKeyPersistence.holderResourceType !== resourceConfiguration.resourceIdentifier\n ) {\n continue;\n }\n\n const existingPath = mongooseSchema.path(foreignKeyPersistence.fieldIdentifier) as\n | { instance?: string; isRequired?: boolean; caster?: { instance?: string } }\n | undefined;\n // `wasMaterializedByFramework` distinguishes \"schema author explicitly\n // authored this field\" from \"framework synthesized this field from\n // relationship metadata.\" It matters for unique-index strategy below:\n // a materialized field's `required` constraint is enforceable ONLY by\n // Mongoose validators, which **raw MongoDB driver writes bypass**\n // (e.g. INIT-mode writers use `db.collection().insertOne()` directly).\n // For those fields we MUST use `partialFilterExpression` on the\n // unique index, otherwise an absent value materializes as `null` in\n // Mongo and the second insert collides with the first on the\n // unique index — exact bug pattern seen with the\n // `platformApplications.applicationId` synthesis (see Subsystem E in\n // `.claude/plans/platform-bootstrap-regression-fix.md`).\n const wasMaterializedByFramework = !existingPath;\n const expectedInstances = foreignKeyPersistence.isArray\n ? ['Array']\n : ['String', 'ObjectId'];\n if (existingPath) {\n if (!expectedInstances.includes(existingPath.instance ?? '')) {\n throw new Error(\n `[ZodToMongoose] Relationship FK '${foreignKeyPersistence.fieldIdentifier}' on resource '${String(resourceConfiguration.resourceIdentifier)}' resolves to ${expectedInstances.join(' or ')}, but the existing schema path is ${existingPath.instance ?? 'unknown'}. Align the authored relationship FK with the resource schema.`,\n );\n }\n if (\n foreignKeyPersistence.isArray &&\n !['String', 'ObjectId'].includes(existingPath.caster?.instance ?? '')\n ) {\n throw new Error(\n `[ZodToMongoose] Relationship FK '${foreignKeyPersistence.fieldIdentifier}' on resource '${String(resourceConfiguration.resourceIdentifier)}' resolves to an array FK, but the existing schema path has array element type ${existingPath.caster?.instance ?? 'unknown'}. Align the authored relationship FK with the resource schema.`,\n );\n }\n if (\n !foreignKeyPersistence.isArray &&\n Boolean(existingPath.isRequired) !== foreignKeyPersistence.required &&\n // M:N junction parent relationships use parentResourceRequirement=OPTIONAL for\n // URL-routing semantics (either parent path is valid). The Zod schema is the\n // authoritative source for junction FK requiredness; accessScopeStrategy=\n // OPTIONAL_CONTEXT already captures the routing concern independently.\n !relationship.jointResourceType\n ) {\n throw new Error(\n `[ZodToMongoose] Relationship FK '${foreignKeyPersistence.fieldIdentifier}' on resource '${String(resourceConfiguration.resourceIdentifier)}' resolves required=${foreignKeyPersistence.required}, but the existing schema path has required=${Boolean(existingPath.isRequired)}. Align parentResourceRequirement with the resource schema.`,\n );\n }\n this.logDebug('Relationship FK persistence path already present', {\n resourceType: resourceConfiguration.resourceIdentifier,\n parentResourceType: relationship.resourceType1,\n fieldIdentifier: foreignKeyPersistence.fieldIdentifier,\n instance: existingPath.instance,\n casterInstance: existingPath.caster?.instance,\n required: Boolean(existingPath.isRequired),\n unique: foreignKeyPersistence.unique,\n });\n } else {\n mongooseSchema.add({\n [foreignKeyPersistence.fieldIdentifier]: foreignKeyPersistence.isArray\n ? [{\n type: String,\n required: foreignKeyPersistence.required,\n }]\n : {\n type: String,\n required: foreignKeyPersistence.required,\n },\n });\n this.logDebug('Materialized relationship FK persistence path', {\n resourceType: resourceConfiguration.resourceIdentifier,\n parentResourceType: relationship.resourceType1,\n fieldIdentifier: foreignKeyPersistence.fieldIdentifier,\n isArray: foreignKeyPersistence.isArray,\n required: foreignKeyPersistence.required,\n unique: foreignKeyPersistence.unique,\n });\n }\n\n const persistedPath = mongooseSchema.path(foreignKeyPersistence.fieldIdentifier) as\n | { instance?: string; isRequired?: boolean; caster?: { instance?: string } }\n | undefined;\n const partialFilterBsonType = persistedPath?.instance === 'ObjectId'\n ? 'objectId'\n : 'string';\n\n if (\n !applyUniqueIndexes ||\n !foreignKeyPersistence.unique ||\n indexedFields.has(foreignKeyPersistence.fieldIdentifier)\n ) {\n this.logDebug('Skipped relationship FK unique index', {\n resourceType: resourceConfiguration.resourceIdentifier,\n parentResourceType: relationship.resourceType1,\n fieldIdentifier: foreignKeyPersistence.fieldIdentifier,\n applyUniqueIndexes,\n unique: foreignKeyPersistence.unique,\n duplicateIndexField: indexedFields.has(foreignKeyPersistence.fieldIdentifier),\n });\n continue;\n }\n indexedFields.add(foreignKeyPersistence.fieldIdentifier);\n\n const indexSpec: Record<string, 1> = { [foreignKeyPersistence.fieldIdentifier]: 1 };\n // Use a plain `unique` index ONLY when the field was explicitly\n // authored in the Zod schema with required: true. In that case the\n // schema author has guaranteed every persisted doc populates the\n // field (Mongoose validators enforce it for `.save()` / `Model.create()`).\n //\n // For ALL other cases — field materialized by framework, or\n // explicitly optional — use `partialFilterExpression` so absent\n // values don't collide as `null`. This is defensive even for\n // declared-required materialized fields, because raw-driver writes\n // (`db.collection().insertOne()`) bypass Mongoose validation.\n // G-BKEY: this is the THIRD unique-index emission path, and it is the one that MATTERS MOST for\n // retention — it also SUPPRESSES the Zod-derived unique index for the same path (see the\n // duplicate-path skip above), so if the retention predicate were only applied there, a\n // retention-governed resource whose unique key is a relationship FK (including the polymorphic\n // singleton scope FK) would keep a retention-BLIND unique index: the retained row stays in it,\n // permanently locking out re-creation and aborting the scrub batch with E11000.\n const retentionPartialFilter = this.buildRetentionPartialFilterExpression(resourceConfiguration);\n const usePlainUniqueIndex =\n foreignKeyPersistence.required && !wasMaterializedByFramework;\n const fkExistencePredicate = {\n [foreignKeyPersistence.fieldIdentifier]: { $exists: true, $type: partialFilterBsonType },\n };\n const indexOptions = usePlainUniqueIndex\n ? (retentionPartialFilter\n ? { unique: true, partialFilterExpression: retentionPartialFilter }\n : { unique: true })\n : {\n unique: true,\n partialFilterExpression: retentionPartialFilter\n ? { ...retentionPartialFilter, ...fkExistencePredicate }\n : fkExistencePredicate,\n };\n try {\n mongooseSchema.index(indexSpec, indexOptions);\n this.logDebug(\n `Applied relationship FK unique index: { ${foreignKeyPersistence.fieldIdentifier}: 1 }`,\n {\n resourceType: resourceConfiguration.resourceIdentifier,\n parentResourceType: relationship.resourceType1,\n required: foreignKeyPersistence.required,\n partialFilterBsonType: foreignKeyPersistence.required ? undefined : partialFilterBsonType,\n },\n );\n } catch (error) {\n this.logger.warn(\n `[ZodToMongoose] Failed to apply relationship FK unique index on path '${foreignKeyPersistence.fieldIdentifier}': ${describeCaughtError(error)}`,\n );\n }\n }\n }\n\n /**\n * Checks if a definition is an object definition (not a primitive type)\n * @param definition The definition to check\n * @returns True if it's an object definition\n */\n private isObjectDefinition(definition: any): boolean {\n return definition &&\n typeof definition === 'object' &&\n !Array.isArray(definition) &&\n !definition.type &&\n Object.keys(definition).length > 0;\n }\n\n /**\n * Generates a hash for a schema for caching purposes\n * @param schema The schema to hash\n * @returns A hash string\n */\n private getSchemaHash(schema: any): string {\n try {\n const schemaString = JSON.stringify(schema, (key, value) => {\n if (typeof value === 'function') return '[Function]';\n if (value instanceof RegExp) return value.toString();\n return value;\n });\n return schemaString.length.toString(36) + schemaString.slice(0, 10);\n } catch {\n return Math.random().toString(36).substr(2, 9);\n }\n }\n\n // =================================================================\n // DEBUG AND UTILITY METHODS\n // =================================================================\n\n /**\n * Debug display method to show schema structure for a specific model\n * @param model The Mongoose model to analyze\n * @param showDetails Whether to show detailed field information\n */\n debugDisplayModelSchema(model: Model<any>, showDetails: boolean = true): void {\n\n this.logDebug(`\\n🔍 === MODEL SCHEMA DEBUG: ${model.modelName} ===`);\n this.logDebug(`Collection: ${model.collection.name}`);\n this.logDebug(`Schema Fields: ${this.countSchemaFields(model.schema)}`);\n this.logDebug(`Indexes: ${model.schema.indexes().length}`);\n\n if (showDetails) {\n this.displaySchemaStructure(model.schema, model.modelName);\n\n const indexes = model.schema.indexes();\n if (indexes.length > 0) {\n this.logDebug('\\n🗂️ Indexes:');\n indexes.forEach((index, i) => {\n const [fields, options] = index;\n const fieldsStr = Object.entries(fields)\n .map(([field, direction]) => `${field}:${direction}`)\n .join(', ');\n const optionsStr = options && Object.keys(options).length > 0\n ? ` (${Object.entries(options).map(([k, v]) => `${k}:${v}`).join(', ')})`\n : '';\n this.logDebug(` ${i + 1}. {${fieldsStr}}${optionsStr}`);\n });\n }\n }\n this.logDebug('=================================\\n');\n }\n\n /**\n * Debug method to show simplified schema summary\n * @param models Array of models to analyze\n */\n debugShowModelsSummary(models: Model<any>[]): void {\n\n this.logDebug('\\n📋 === MODELS SUMMARY ===');\n\n if (models.length === 0) {\n this.logDebug('No models provided.');\n return;\n }\n\n for (const model of models) {\n const fieldCount = this.countSchemaFields(model.schema);\n const indexCount = model.schema.indexes().length;\n this.logDebug(`${model.modelName}: ${fieldCount} fields, ${indexCount} indexes`);\n }\n this.logDebug('========================\\n');\n }\n\n /**\n * Counts schema fields recursively\n * @param schema The Mongoose schema\n * @returns Total field count\n */\n private countSchemaFields(schema: Schema): number {\n if (!schema || !schema.paths) return 0;\n\n const paths = schema.paths;\n const pathNames = Object.keys(paths)\n .filter(path => !['__v', '_version_db_doc'].includes(path))\n .sort();\n\n return pathNames.length;\n }\n\n /**\n * Displays the structure of a Mongoose schema for debugging\n * @param schema The schema to display\n * @param schemaName Optional name for the schema\n * @param options Display options\n */\n private displaySchemaStructure(\n schema: Schema,\n schemaName: string = 'Schema',\n options: {\n showIndexes?: boolean;\n showValidators?: boolean;\n maxDepth?: number;\n } = {}\n ): void {\n const { showIndexes = true, showValidators = false, maxDepth = 3 } = options;\n\n this.logDebug(`\\n=== ${schemaName} Structure ===`);\n\n if (!schema || !schema.paths) {\n this.logDebug('No schema paths found');\n return;\n }\n\n const paths = schema.paths;\n const pathNames = Object.keys(paths)\n .filter(path => !['__v', '_version_db_doc'].includes(path))\n .sort();\n\n for (const pathName of pathNames) {\n const pathInfo = this.getPathTypeInfo(paths[pathName]);\n\n // Start with base type\n let pathDisplay = `${pathName}: `;\n\n if (pathInfo.isArray) {\n // For arrays, show [ElementType] format\n const elementType = pathInfo.arrayElementType || 'Mixed';\n pathDisplay += `[${elementType}]`;\n } else {\n pathDisplay += pathInfo.type;\n }\n\n // Collect all additional info in parentheses\n const additionalInfo: string[] = [];\n\n // Required vs Optional\n if (pathInfo.isRequired) {\n additionalInfo.push('required');\n } else {\n additionalInfo.push('optional');\n }\n\n // Enum values\n if (pathInfo.enumValues.length > 0) {\n const enumList = pathInfo.enumValues.join(', ');\n additionalInfo.push(`enum: [${enumList}]`);\n }\n\n // Default value\n if (pathInfo.hasDefault) {\n let defaultStr = '';\n if (Array.isArray(pathInfo.defaultValue)) {\n defaultStr = `[${pathInfo.defaultValue.join(', ')}]`;\n } else if (typeof pathInfo.defaultValue === 'object' && pathInfo.defaultValue !== null) {\n defaultStr = JSON.stringify(pathInfo.defaultValue);\n } else if (typeof pathInfo.defaultValue === 'string') {\n defaultStr = `\"${pathInfo.defaultValue}\"`;\n } else {\n defaultStr = String(pathInfo.defaultValue);\n }\n additionalInfo.push(`default: ${defaultStr}`);\n }\n\n // Validators\n if (showValidators && pathInfo.validators.length > 0) {\n additionalInfo.push(`validators: [${pathInfo.validators.join(', ')}]`);\n }\n\n // Add all additional info in parentheses\n if (additionalInfo.length > 0) {\n pathDisplay += ` (${additionalInfo.join(', ')})`;\n }\n\n this.logDebug(` ${pathDisplay}`);\n\n // Show nested structure for objects\n if (pathInfo.isNested && maxDepth > 0) {\n this.displayNestedPathStructure(paths[pathName], 2, maxDepth - 1, showValidators);\n }\n }\n\n if (showIndexes) {\n const indexes = schema.indexes();\n if (indexes.length > 0) {\n this.logDebug('\\n Indexes:');\n indexes.forEach((index, i) => {\n this.logDebug(` ${i + 1}. ${JSON.stringify(index[0])} ${JSON.stringify(index[1] || {})}`);\n });\n }\n }\n\n this.logDebug(`\\nTotal paths: ${pathNames.length}`);\n }\n\n /**\n * Displays nested path structure recursively with comprehensive details\n * @param path The path to display\n * @param indent Current indentation level\n * @param maxDepth Maximum depth to display\n * @param showValidators Whether to show validator information\n */\n private displayNestedPathStructure(path: any, indent: number = 0, maxDepth: number = 2, showValidators: boolean = false): void {\n if (maxDepth <= 0) return;\n\n const spaces = ' '.repeat(indent);\n\n if (path.schema && path.schema.paths) {\n const nestedPaths = Object.keys(path.schema.paths)\n .filter(nestedPath => !['__v', '_version_db_doc'].includes(nestedPath))\n .sort();\n\n for (const nestedPath of nestedPaths) {\n const nestedPathInfo = this.getPathTypeInfo(path.schema.paths[nestedPath]);\n\n // Build display string for nested field\n let nestedDisplay = `${nestedPath}: `;\n\n if (nestedPathInfo.isArray) {\n const elementType = nestedPathInfo.arrayElementType || 'Mixed';\n nestedDisplay += `[${elementType}]`;\n } else {\n nestedDisplay += nestedPathInfo.type;\n }\n\n // Collect additional info for nested fields\n const nestedAdditionalInfo: string[] = [];\n\n // Required vs Optional\n if (nestedPathInfo.isRequired) {\n nestedAdditionalInfo.push('required');\n } else {\n nestedAdditionalInfo.push('optional');\n }\n\n // Enum values\n if (nestedPathInfo.enumValues.length > 0) {\n const enumList = nestedPathInfo.enumValues.join(', ');\n nestedAdditionalInfo.push(`enum: [${enumList}]`);\n }\n\n // Default value\n if (nestedPathInfo.hasDefault) {\n let defaultStr = '';\n if (Array.isArray(nestedPathInfo.defaultValue)) {\n defaultStr = `[${nestedPathInfo.defaultValue.join(', ')}]`;\n } else if (typeof nestedPathInfo.defaultValue === 'object' && nestedPathInfo.defaultValue !== null) {\n defaultStr = JSON.stringify(nestedPathInfo.defaultValue);\n } else if (typeof nestedPathInfo.defaultValue === 'string') {\n defaultStr = `\"${nestedPathInfo.defaultValue}\"`;\n } else {\n defaultStr = String(nestedPathInfo.defaultValue);\n }\n nestedAdditionalInfo.push(`default: ${defaultStr}`);\n }\n\n // Validators\n if (showValidators && nestedPathInfo.validators.length > 0) {\n nestedAdditionalInfo.push(`validators: [${nestedPathInfo.validators.join(', ')}]`);\n }\n\n // Add additional info in parentheses\n if (nestedAdditionalInfo.length > 0) {\n nestedDisplay += ` (${nestedAdditionalInfo.join(', ')})`;\n }\n\n this.logDebug(`${spaces}${nestedDisplay}`);\n\n if (nestedPathInfo.isNested) {\n this.displayNestedPathStructure(path.schema.paths[nestedPath], indent + 1, maxDepth - 1, showValidators);\n }\n }\n }\n }\n\n /**\n * Gets comprehensive type information for a schema path\n * @param schemaType The schema type to analyze\n * @returns Object containing detailed type information\n */\n private getPathTypeInfo(schemaType: any): {\n type: string;\n isRequired: boolean;\n hasDefault: boolean;\n defaultValue: any;\n isArray: boolean;\n arrayElementType: string;\n isNested: boolean;\n validators: string[];\n enumValues: string[];\n isOptional: boolean;\n } {\n let type = 'Mixed';\n let isRequired = false;\n let hasDefault = false;\n let defaultValue: any = undefined;\n let isArray = false;\n let arrayElementType = '';\n let isNested = false;\n const validators: string[] = [];\n const enumValues: string[] = [];\n\n if (schemaType) {\n // Get type name\n if (schemaType.instance) {\n type = schemaType.instance;\n } else if (schemaType.constructor && schemaType.constructor.name) {\n type = schemaType.constructor.name;\n }\n\n // Check if required\n if (schemaType.isRequired) {\n isRequired = true;\n }\n\n // Check if has default and get the actual value\n if (schemaType.defaultValue !== undefined) {\n hasDefault = true;\n defaultValue = schemaType.defaultValue;\n\n // Handle function defaults\n if (typeof defaultValue === 'function') {\n try {\n const result = defaultValue();\n defaultValue = result;\n } catch (e) {\n defaultValue = '[Function]';\n }\n }\n }\n\n // Check if array and get element type\n if (schemaType.constructor && schemaType.constructor.name === 'Array') {\n isArray = true;\n\n // Try to get array element type\n if (schemaType.caster) {\n if (schemaType.caster.instance) {\n arrayElementType = schemaType.caster.instance;\n } else if (schemaType.caster.constructor && schemaType.caster.constructor.name) {\n arrayElementType = schemaType.caster.constructor.name;\n }\n\n // Check for enum values in array elements\n if (schemaType.caster.enumValues && Array.isArray(schemaType.caster.enumValues)) {\n enumValues.push(...schemaType.caster.enumValues);\n }\n }\n }\n\n // Check if nested (has embedded schema)\n if (schemaType.schema) {\n isNested = true;\n type = 'Object';\n }\n\n // Check for enum values\n if (schemaType.enumValues && Array.isArray(schemaType.enumValues)) {\n enumValues.push(...schemaType.enumValues);\n }\n\n // Collect validators\n if (schemaType.validators && Array.isArray(schemaType.validators)) {\n validators.push(...schemaType.validators.map((v: any) => v.type || 'custom'));\n }\n }\n\n const isOptional = !isRequired;\n\n return {\n type,\n isRequired,\n hasDefault,\n defaultValue,\n isArray,\n arrayElementType,\n isNested,\n validators,\n enumValues,\n isOptional\n };\n }\n}\n"]}
1
+ {"version":3,"file":"zod-to-mongoose-schema-convertor.backend.service.js","sourceRoot":"","sources":["../../../../../src/databases/services/zod-to-mongoose-schema-convertor.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,MAAM,EAA+B,KAAK,EAAE,MAAM,UAAU,CAAC;AACtE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,gCAAgC,EAAE,MAAM,8EAA8E,CAAC;AAChI,OAAO,EAKL,S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CAAC,UAAU,CAAC,CAAC;YAC5C,CAAC;YAED,qBAAqB;YACrB,IAAI,UAAU,CAAC,UAAU,IAAI,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;gBAClE,UAAU,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,QAAQ,CAAC,CAAC,CAAC;YAChF,CAAC;QACH,CAAC;QAED,MAAM,UAAU,GAAG,CAAC,UAAU,CAAC;QAE/B,OAAO;YACL,IAAI;YACJ,UAAU;YACV,UAAU;YACV,YAAY;YACZ,OAAO;YACP,gBAAgB;YAChB,QAAQ;YACR,UAAU;YACV,UAAU;YACV,UAAU;SACX,CAAC;IACJ,CAAC;CACF,CAAA;AAjyGY,0CAA0C;IADtD,UAAU,EAAE;IA8BR,WAAA,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAA;IACjC,WAAA,MAAM,CAAC,kBAAkB,CAAC,mBAAmB,CAAC,CAAA;qCADI,aAAa;QACM,0BAA0B;GA9BvF,0CAA0C,CAiyGtD","sourcesContent":["import { injectable, inject } from 'inversify';\nimport { Schema, Model, Document, Connection, Types } from 'mongoose';\nimport { z } from 'zod';\nimport { DATA_SEED_ROW_METADATA_FIELD_KEY } from '~wildo-backend-lib/data-seeding/models/data-seed-row-metadata.shared.schemas';\nimport {\n ResourceConfiguration,\n ResourceType,\n\n CoreResourceOperation,\n ErrorType,\n ErrorCustomMessageReference,\n resolveSharedPersistenceCollectionName,\n type ResourceRelationship,\n type RelationshipPersistenceForeignKeyContract,\n} from '@wildo-ai/saas-models';\nimport {\n buildRetentionVisibleRowsEqualityFragment,\n getVisibleRetentionStatuses,\n isRetentionGovernedResource,\n resolveSoleVisibleRetentionStatus,\n type RetentionGovernanceSignal,\n} from '~wildo-backend-lib/compliance/privacy/retention-hide-predicate.backend';\n\n\nimport {\n isZodPipe,\n getPipeInputSchema,\n isZodObject,\n getZodType,\n EnumLikeType,\n hasZodType,\n isZodArray,\n isZodOptional,\n isZodNullable,\n isZodDefault,\n getZodDefSchemaProperty,\n getZodDefArrayProperty,\n getZodDefStringProperty,\n getZodDefFunctionProperty,\n getZodDefProperty,\n getZodObjectShape,\n isVirtualField,\n isZodTransform,\n isZodCustom,\n isZodTuple,\n isDiscriminatedUnion,\n isZodUnion,\n isZodIntersection,\n isZodLiteral,\n isZodLazy,\n isZodTypeAny,\n isZodRecord,\n isZodSet,\n isDBIndexed,\n isForeignKey,\n unwrapSchema,\n getEnumValues,\n isUnique,\n getUniqueParams,\n UniqueFieldParams,\n isPrimaryKey,\n hasTtl,\n getTtlParams,\n TtlFieldParams,\n getBusinessKeySetParams,\n} from '@wildo-ai/zod-decorators';\n\nimport {\n SCHEMA_DEFAULT_OPTIONS,\n SCHEMA_SUBDOCUMENT_OPTIONS,\n initModelFromSchema\n} from './db-utils';\n\nimport { SAAS_SERVICE_TYPES } from '~wildo-backend-lib/inject/models/service-types';\nimport { LoggerService } from '~wildo-backend-lib/monitoring/logger/services/logger.service';\nimport { ErrorBuilderBackendService } from '~wildo-backend-lib/errors/services/error-builder.backend.service';\nimport { describeCaughtError } from '~wildo-backend-lib/errors/utils/error-log-level-classification.backend.utils';\nimport { REPOSITORY_ROW_IDENTITY_FIELD } from '~wildo-backend-lib/base-classes/services/repositories/repository-total-order.backend';\n\n\n/**\n * Interface for union inheritance schema information (not model instances)\n * Represents different inheritance options in a discriminated union\n */\nexport interface UnionInheritance_SchemaInfo {\n discriminatorKey: string;\n discriminatorValue: string;\n schema: Schema;\n zodSchema: z.ZodTypeAny;\n}\n\n/**\n * Options for schema conversion\n */\nexport interface SchemaConversionOptions {\n includeIndexes?: boolean;\n applyDefaults?: boolean;\n maxDepth?: number;\n connection?: Connection; // optional connection to bind model creation\n /**\n * The resource's TOP-LEVEL foreign-key fields whose relationship names a VIRTUAL (`HTTP_API`) resource (#1939) —\n * `resolveVirtualTargetForeignKeyFields`. Each is stored as a STRING, the target's synthesized key, instead of an\n * `ObjectId`. Absent or empty is the ordinary case, and then the conversion is byte-for-byte what it always was: every\n * `.isForeignKey()` field is an `ObjectId` path with the same index. Decided here, once, from the declaration; nothing\n * downstream converts a value.\n */\n virtualTargetForeignKeyFields?: ReadonlySet<string>;\n}\n\n/**\n * Info for unique index application\n */\nexport interface UniqueIndexInfo {\n path: string;\n params: UniqueFieldParams;\n}\n\n/**\n * Info for TTL (Time To Live) index application.\n * MongoDB will automatically delete documents when the TTL expires.\n */\nexport interface TtlIndexInfo {\n path: string;\n params: TtlFieldParams;\n}\n\n/**\n * Interface for generated model information (for debugging)\n */\nexport interface GeneratedModelInfo {\n resourceType: ResourceType;\n modelName: string;\n mainModel: Model<any & Document>;\n inheritanceSchemas: UnionInheritance_SchemaInfo[];\n inheritanceModels: Model<any & Document>[];\n schemaFieldCount: number;\n indexCount: number;\n conversionOptions: SchemaConversionOptions;\n createdAt: Date;\n}\n\n/**\n * Debug statistics for model generation\n */\nexport interface ModelGenerationStats {\n totalResources: number;\n totalMainModels: number;\n totalInheritanceModels: number;\n totalSchemaFields: number;\n totalIndexes: number;\n resourceTypes: ResourceType[];\n conversionTime: number;\n}\n\n/**\n * Service for converting Zod schemas to Mongoose schemas\n * Handles decorators for database indexing and resource references\n * Supports discriminated unions and complex nested objects\n *\n * IMPORTANT: This service is STATELESS and does NOT create inheritance models\n * to avoid global state mutations. Use the returned schemas to create models externally.\n *\n * Features unified error handling with ErrorBuilderBackendService for schema conversion errors.\n */\n@injectable()\nexport class ZodToMongooseSchemaConvertorBackendService {\n\n // =================================================================\n // CONSTRUCTOR AND CONFIGURATION\n // =================================================================\n\n private readonly DEFAULT_MAX_DEPTH = 25;\n protected logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n /**\n * The {@link SchemaConversionOptions.virtualTargetForeignKeyFields} of the conversion in progress, held for its duration\n * only (set and cleared around the synchronous conversion in `convertZodSchemaToMongooseSchemaWithCleanup`), so the\n * recursive field conversion does not carry it through a dozen signatures. Empty outside a conversion.\n */\n private virtualTargetForeignKeyFields: ReadonlySet<string> = new Set();\n\n /**\n * The Mongoose type of a foreign-key path (#1939): `ObjectId`, unless the field's relationship names a virtual resource,\n * whose ids are synthesized strings. Keyed on the field's path from the resource root, so only a top-level field — the\n * one a relationship declares — can take the exception; a nested field of the same name keeps its `ObjectId`.\n */\n private foreignKeyStorageType(currentPath: string): typeof Schema.Types.ObjectId | StringConstructor {\n return this.virtualTargetForeignKeyFields.size > 0 && this.virtualTargetForeignKeyFields.has(currentPath)\n ? String\n : Schema.Types.ObjectId;\n }\n\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger) private logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService) private errorBuilder: ErrorBuilderBackendService\n ) {\n this.logDebug = this.logger.debugByType('ZodToMongooseSchemaConvertorBackendService');\n this.logger.setDebugTypeLogging('ZodToMongooseSchemaConvertorBackendService', false);\n }\n\n // =================================================================\n // PUBLIC API METHODS\n // =================================================================\n\n /**\n * Converts a ResourceConfiguration to a Mongoose model\n * @param resourceConfiguration The resource configuration containing the schema\n * @param options Conversion options\n * @returns Object containing the main model and union inheritance schema information\n * @throws Error if schema conversion fails\n */\n /**\n * Build the Zod schema whose fields become Mongoose paths, widening a schema-family / discriminated-\n * union resource's BASE `mainSchema` with every variant-extension field as an OPTIONAL path (union\n * across all variants, recursing nested inheritance). See the block comment at the call site for why\n * this is required (variant fields would otherwise be silently dropped on write). Returns the base\n * unchanged when there is no inheritance definition or the base is not a plain object.\n */\n private buildPersistedSchemaWithVariantFields(baseSchema: z.ZodTypeAny, inheritenceSchemaDefinition: unknown): z.ZodTypeAny {\n if (!inheritenceSchemaDefinition || !isZodObject(baseSchema)) {\n return baseSchema;\n }\n const baseShape = getZodObjectShape(baseSchema);\n const extraOptionalFields: Record<string, z.ZodTypeAny> = {};\n\n type InheritanceNode = { discriminatorField?: string; inheritedSchemas?: Array<{ schema?: unknown; inheritenceSchemaDefinition?: unknown }> };\n const collect = (node: InheritanceNode | undefined): void => {\n if (!node?.inheritedSchemas) return;\n const discriminatorField = node.discriminatorField;\n for (const entry of node.inheritedSchemas) {\n const variantSchema = entry?.schema as z.ZodTypeAny | undefined;\n if (variantSchema && isZodObject(variantSchema)) {\n const variantShape = getZodObjectShape(variantSchema);\n for (const [key, fieldSchema] of Object.entries(variantShape)) {\n if (key === discriminatorField) continue; // discriminator is already carried on the base\n if (key in baseShape) continue; // a base field is already a model path\n if (key in extraOptionalFields) continue; // union across variants — first definition wins\n // Persist the variant field as OPTIONAL: per-variant \"required\" stays enforced by Zod at the\n // DTO layer; the flat model must accept rows of every variant.\n extraOptionalFields[key] = (fieldSchema as z.ZodTypeAny).optional();\n }\n }\n if (entry?.inheritenceSchemaDefinition) {\n collect(entry.inheritenceSchemaDefinition as InheritanceNode); // multi-level inheritance\n }\n }\n };\n collect(inheritenceSchemaDefinition as InheritanceNode);\n\n if (Object.keys(extraOptionalFields).length === 0) {\n return baseSchema;\n }\n return (baseSchema as z.ZodObject<z.ZodRawShape>).extend(extraOptionalFields);\n }\n\n /**\n * NOTE: TDatabaseSchema has been removed. Backend-only fields are now marked with\n * the `isBackendOnly` decorator on mainSchema and handled at the service layer.\n */\n convertResourceConfigurationToModel<\n TCustomOperationEnum extends EnumLikeType | undefined,\n TCoreOperationEnum extends Partial<CoreResourceOperation> | undefined,\n TMainSchema extends z.ZodTypeAny\n >(\n resourceConfiguration: ResourceConfiguration<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n options: SchemaConversionOptions = {}\n ): {\n mainModel: Model<any & Document>;\n inheritanceSchemas: UnionInheritance_SchemaInfo[];\n } {\n\n const startTime = Date.now();\n\n\n if (!resourceConfiguration) {\n const error = this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n { customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED }\n );\n throw error;\n }\n\n if (!resourceConfiguration.mainSchema) {\n const error = this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n { customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED, }\n );\n throw error;\n }\n\n // NOTE: databaseSchema was removed - mainSchema now contains all fields including backend-only (marked with isBackendOnly decorator)\n //\n // SCHEMA-FAMILY / DISCRIMINATED-UNION SUPERSET: for an inheritance resource, `mainSchema` is the\n // BASE schema only (a plain z.object). The variant-extension fields (e.g. a recurring todo's\n // `recurrence`/`startDate`/`endsDate`) live only in `inheritenceSchemaDefinition`, so if we convert\n // the bare base, Mongoose has no path for them and SILENTLY DROPS them on write — and the read-back\n // then fails the per-variant `transformOutput` (which requires them), surfacing as a 500\n // `service_resource_transformation_failed`. We therefore persist a SUPERSET model: the base plus\n // every variant-extension field as an OPTIONAL path (union across all variants, recursing nested\n // inheritance). This is the top-level analogue of the already-blessed\n // `flattenDiscriminatedUnionForSubdocument` strategy — ONE flat collection, NO Mongoose\n // discriminators, with per-variant \"required\" still enforced by Zod at the DTO layer. `mainSchema`\n // itself is left untouched (DTOs are built from it + the union elsewhere); this only widens the\n // persisted model. A resource with no inheritance (the common case) is entirely unchanged.\n const schemaToConvert = this.buildPersistedSchemaWithVariantFields(resourceConfiguration.mainSchema, (resourceConfiguration as { inheritenceSchemaDefinition?: unknown }).inheritenceSchemaDefinition);\n const modelLabel = resourceConfiguration.resourceIdentifier as string;\n\n\n\n // Get the collection name (may be different from model name for USER_SELF_* resources)\n const collectionName = this.getCollectionNameForResource(resourceConfiguration.resourceIdentifier);\n\n if (!modelLabel) {\n const error = this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n { customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED }\n );\n throw error;\n }\n\n try {\n // Convert Zod schema to Mongoose schema with clean state\n const conversionResult = this.convertZodSchemaToMongooseSchemaWithCleanup(\n schemaToConvert,\n options,\n resourceConfiguration\n );\n\n // Initialize main model with custom collection name if different from model name and optional connection\n const mainModel = initModelFromSchema(\n conversionResult.mongooseSchema,\n modelLabel,\n collectionName,\n options.connection\n );\n\n // Fail loud if a stale model registered under this name shadows the surrogate-PK reshape.\n this.assertSurrogatePrimaryKeyVirtualsBound(schemaToConvert, mainModel, modelLabel);\n\n // Log debug information if debug logging is enabled\n this.logDebug(`Converted schema for resource '${modelLabel}'`, {\n resourceType: resourceConfiguration.resourceIdentifier,\n modelName: modelLabel,\n schemaFieldCount: this.countSchemaFields(conversionResult.mongooseSchema),\n indexCount: conversionResult.mongooseSchema.indexes().length,\n inheritanceCount: conversionResult.inheritanceSchemas.length,\n conversionTime: Date.now() - startTime,\n conversionOptions: options\n });\n\n return {\n mainModel,\n inheritanceSchemas: conversionResult.inheritanceSchemas\n };\n } catch (error) {\n const conversionError = this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED,\n context: {\n resourceType: resourceConfiguration.resourceIdentifier,\n modelLabel,\n originalError: describeCaughtError(error)\n }\n }\n );\n throw conversionError;\n }\n }\n\n /**\n * Creates a Mongoose model directly from a Zod schema (utility method)\n * @param zodSchema The Zod schema\n * @param modelName The name for the model\n * @param options Conversion options\n * @returns Object containing the main model and union inheritance schemas\n * @throws Error if schema conversion fails\n */\n createModelFromZodSchema(\n zodSchema: z.ZodTypeAny,\n modelName: string,\n options: SchemaConversionOptions = {}\n ): {\n mainModel: Model<any & Document>;\n inheritanceSchemas: UnionInheritance_SchemaInfo[];\n } {\n\n if (!zodSchema) {\n const error = this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n { customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED }\n );\n throw error;\n }\n\n if (!modelName || typeof modelName !== 'string') {\n const error = this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n { customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED }\n );\n throw error;\n }\n\n try {\n const conversionResult = this.convertZodSchemaToMongooseSchemaWithCleanup(zodSchema, options, undefined);\n const mainModel = initModelFromSchema(conversionResult.mongooseSchema, modelName);\n this.assertSurrogatePrimaryKeyVirtualsBound(zodSchema, mainModel, modelName);\n\n this.logDebug(`Created model from Zod schema '${modelName}'`, {\n modelName,\n schemaFieldCount: this.countSchemaFields(conversionResult.mongooseSchema),\n indexCount: conversionResult.mongooseSchema.indexes().length,\n inheritanceCount: conversionResult.inheritanceSchemas.length,\n conversionOptions: options\n });\n\n return {\n mainModel,\n inheritanceSchemas: conversionResult.inheritanceSchemas\n };\n } catch (error) {\n const modelError = this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_MODEL_BUILD_FAILED,\n context: {\n modelName,\n originalError: describeCaughtError(error)\n }\n }\n );\n throw modelError;\n }\n }\n\n /**\n * Creates inheritance models from union inheritance schemas\n * This is a separate method to allow external control over model creation\n * @param unionRootModel The union root model (base for all inheritance options)\n * @param inheritanceSchemas The union inheritance schemas to create models from\n * @returns Array of created inheritance models\n */\n createInheritanceModels(\n unionRootModel: Model<any & Document>,\n inheritanceSchemas: UnionInheritance_SchemaInfo[]\n ): Model<any & Document>[] {\n\n const models: Model<any & Document>[] = [];\n\n for (const inheritanceSchema of inheritanceSchemas) {\n try {\n const inheritanceModelName = `${unionRootModel.modelName}_${inheritanceSchema.discriminatorValue}`;\n const inheritanceModel = unionRootModel.discriminator(inheritanceModelName, inheritanceSchema.schema);\n models.push(inheritanceModel);\n } catch (error) {\n this.logger.warn(`Failed to create inheritance model for value '${inheritanceSchema.discriminatorValue}': ${describeCaughtError(error)}`);\n }\n }\n\n this.logDebug(`Created inheritance models for union root model '${unionRootModel.modelName}'`, {\n unionRootModelName: unionRootModel.modelName,\n inheritanceModelsCount: models.length,\n inheritanceValues: inheritanceSchemas.map(s => s.discriminatorValue)\n });\n\n return models;\n }\n\n // =================================================================\n // MAIN CONVERSION METHODS\n // =================================================================\n\n /**\n * Find top-level fields marked `.isPrimaryKey()` whose name is not `_id` — i.e.\n * SURROGATE primary keys (the resource's external identity name for the\n * auto-generated Mongo `_id`, e.g. FILES `fileId`). Such fields are NOT stored\n * paths; they are registered as read-only virtual projections of `_id` by\n * {@link convertZodSchemaToMongooseSchemaWithCleanup}.\n *\n * Only the top-level object shape is inspected (a primary key is a top-level\n * concern). `_id` itself is excluded — it is the canonical key, handled natively.\n * Returns `[]` for every resource that has no custom primary key (i.e. all\n * resources except FILES today), so the rest of the conversion is unaffected.\n */\n private findSurrogatePrimaryKeyFields(zodSchema: z.ZodTypeAny): string[] {\n let objectSchema: z.ZodTypeAny = unwrapSchema(zodSchema);\n if (isZodPipe(objectSchema)) {\n objectSchema = getPipeInputSchema(objectSchema) ?? objectSchema;\n }\n if (!isZodObject(objectSchema)) {\n return [];\n }\n const shape = getZodObjectShape(objectSchema);\n const surrogateNames: string[] = [];\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n if (\n fieldName !== '_id' &&\n fieldSchema &&\n typeof fieldSchema === 'object' &&\n isPrimaryKey(fieldSchema as z.ZodTypeAny)\n ) {\n surrogateNames.push(fieldName);\n }\n }\n return surrogateNames;\n }\n\n /**\n * Defensive guard against a stale Mongoose model shadowing a surrogate-PK reshape.\n *\n * `initModelFromSchema` returns an EXISTING model registered under the same name and ignores\n * the passed schema. For a surrogate-PK resource (e.g. FILES `fileId`), a stale pre-reshape\n * model lacks the `= String(_id)` virtual — every read would then drop the surrogate from\n * responses, and `{ _id: doc.<name> }` filters (e.g. the files-cleanup batch) would become\n * `{ _id: undefined }`. The reshape's correctness silently depends on \"first-compile-wins\";\n * this makes that dependency loud. It fires only when a non-reshaped model is registered\n * first (double bootstrap / missing test isolation), never in correct single-build operation.\n */\n private assertSurrogatePrimaryKeyVirtualsBound(\n zodSchema: z.ZodTypeAny,\n mainModel: Model<any>,\n modelLabel: string,\n ): void {\n const surrogateFields = this.findSurrogatePrimaryKeyFields(zodSchema);\n for (const fieldName of surrogateFields) {\n if (!mainModel.schema?.virtuals?.[fieldName]) {\n throw new Error(\n `[ZodToMongoose] Model '${modelLabel}' is missing the surrogate primary-key virtual ` +\n `'${fieldName}' (= String(_id)). A stale Mongoose model registered under this name is ` +\n `shadowing the reshaped schema, so '${fieldName}' would be absent from every response ` +\n `and '{ _id: doc.${fieldName} }' filters would become '{ _id: undefined }'. Ensure the ` +\n `reshaped model is compiled first (model-registry caching — typically double-bootstrap ` +\n `or missing test isolation).`,\n );\n }\n }\n }\n\n /**\n * Converts a Zod schema to a Mongoose schema with proper cleanup\n * @param zodSchema The Zod schema to convert\n * @param options Conversion options\n * @returns Object containing mongoose schema and union inheritance information\n */\n private convertZodSchemaToMongooseSchemaWithCleanup(\n zodSchema: z.ZodTypeAny,\n options: SchemaConversionOptions = {},\n resourceConfiguration?: any\n ): {\n mongooseSchema: Schema;\n inheritanceSchemas: UnionInheritance_SchemaInfo[];\n } {\n\n if (!zodSchema) {\n const error = this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n { customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED }\n );\n throw error;\n }\n\n const maxDepth = options.maxDepth || this.DEFAULT_MAX_DEPTH;\n this.virtualTargetForeignKeyFields = options.virtualTargetForeignKeyFields ?? new Set();\n const processedSchemas = new WeakSet<z.ZodTypeAny>();\n const schemaCache = new WeakMap<z.ZodTypeAny, Schema>();\n const inheritanceSchemas: UnionInheritance_SchemaInfo[] = [];\n const indexesToApply: string[] = [];\n const uniqueIndexesToApply: UniqueIndexInfo[] = [];\n const ttlIndexesToApply: TtlIndexInfo[] = [];\n\n try {\n // Convert Zod schema to Mongoose schema definition\n const schemaDefinition = this.convertZodTypeToMongooseDefinition(\n zodSchema,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n '',\n 0,\n maxDepth\n );\n\n\n\n\n\n // Remove discriminatorKey from schema definition if present (it's not a valid Mongoose field type)\n // discriminatorKey is used for model-level discriminator configuration, not schema definition\n const { discriminatorKey, ...cleanSchemaDefinition } = schemaDefinition as any;\n\n // Surrogate primary keys: a top-level field marked `.isPrimaryKey()` whose name is\n // NOT `_id` is the resource's *external identity name* for the auto-generated Mongo\n // `_id` — e.g. FILES `fileId`. It must NOT be a separately-stored path (that produced\n // a second identity divergent from `_id`, and — being `excludeFromCreate` like every\n // primary key — was stripped from the create DTO yet required by Mongoose, which broke\n // every file create). Instead `_id` is the single stored identity and the surrogate\n // name is exposed as a read-only Mongoose VIRTUAL `= String(_id)`. For that virtual to\n // reach responses, virtuals MUST be enabled on this schema's `toObject`/`toJSON` — and\n // `SCHEMA_DEFAULT_OPTIONS` (db-utils) does NOT enable them (that flag lives in the\n // separate `SCHEMA_VIRTUALS_OPTIONS`). So the explicit `mongooseSchema.set('toObject' /\n // 'toJSON', { virtuals: true })` further below — gated on surrogate schemas — is\n // LOAD-BEARING: drop it and `<name>` silently disappears from every response/DTO (and\n // any `{ _id: doc.<name> }` filter, e.g. the cleanup batch, becomes `{ _id: undefined }`).\n // With it, the virtual flows into every response/DTO and `doc.<name>` reads resolve\n // through the getter — so the external `<name>` surface (DTOs, z_file references, URLs)\n // is unchanged while the resource has exactly one stored identity. (Today FILES.fileId is\n // the only such field; any future surrogate key gets the same treatment.)\n const surrogatePrimaryKeyFields = this.findSurrogatePrimaryKeyFields(zodSchema);\n for (const surrogateName of surrogatePrimaryKeyFields) {\n delete cleanSchemaDefinition[surrogateName];\n // Drop any collected index / unique index for the surrogate field. A primary key\n // contributes a UNIQUE index (see the \"already indexed via unique index\" note in\n // `convertZodFieldToMongooseField`), but the surrogate is now a non-stored virtual —\n // a unique index on the pathless field would make every document collide on `null`\n // (E11000). The identity is `_id`, which Mongo already uniquely indexes.\n for (let i = indexesToApply.length - 1; i >= 0; i--) {\n if (indexesToApply[i].replace(/\\[\\]/g, '').trim() === surrogateName) {\n indexesToApply.splice(i, 1);\n }\n }\n for (let i = uniqueIndexesToApply.length - 1; i >= 0; i--) {\n if ((uniqueIndexesToApply[i].path || '').replace(/\\[\\]/g, '').trim() === surrogateName) {\n uniqueIndexesToApply.splice(i, 1);\n }\n }\n }\n\n // CRDT field-level metadata — schemaless Mixed field for per-field LWW timestamps.\n // Only populated for resources that have isCRDT() fields.\n cleanSchemaDefinition._field_meta = { type: Schema.Types.Mixed };\n\n // Every resource can receive repository-owned seed metadata. Like the SQL planner's\n // framework-owned column, this belongs to storage, not the public resource DTO. Without\n // this path Mongoose silently drops the ownership/version stamp, defeating both unchanged\n // reconciliation and the seed-scoped orphan scan. Unseeded records have no value/default.\n cleanSchemaDefinition[DATA_SEED_ROW_METADATA_FIELD_KEY] = { type: Schema.Types.Mixed };\n\n // Create the Mongoose schema\n const mongooseSchema = new Schema(cleanSchemaDefinition, SCHEMA_DEFAULT_OPTIONS);\n\n // Register each surrogate primary key as a read-only virtual projection of `_id`.\n for (const surrogateName of surrogatePrimaryKeyFields) {\n mongooseSchema.virtual(surrogateName).get(function (this: { _id?: unknown }) {\n return this._id != null ? String(this._id) : undefined;\n });\n }\n\n this.relaxPluginOwnedTimestampRequiredValidators(mongooseSchema);\n\n // Apply standard transforms (convert ObjectId to string in toObject/toJSON)\n this.applyStandardTransforms(mongooseSchema);\n\n // A surrogate primary key is exposed only as a Mongoose VIRTUAL (= String(_id)), so it\n // must survive `toObject()` / `toJSON()`. `applyStandardTransforms` rewrites those\n // options without `virtuals: true` (it drops the `SCHEMA_DEFAULT_OPTIONS` virtuals\n // flag), which would silently strip the surrogate name from every response/DTO. Re-\n // enable virtuals — but ONLY for resources that actually have a surrogate PK — so the\n // serialized shape of every other resource is unchanged.\n //\n // Side effect: enabling virtuals also exposes Mongoose's built-in `id` virtual\n // (= String(_id)) on this resource's `toObject`/`toJSON`. That is harmless — the\n // response DTO is a non-`.strict()` Zod object, which strips unknown keys, so `id`\n // never reaches an API/DTO consumer (only the declared surrogate `<name>` does).\n // (A surrogate field that participates in a `.businessKeySet([...])` is handled by\n // `applyBusinessKeyCompoundUniqueIndex` — the deleted path reads as \"missing\", so the\n // compound index is skipped with a warning rather than emitted against a virtual.)\n if (surrogatePrimaryKeyFields.length > 0) {\n const currentToObject = (mongooseSchema as any).options?.toObject || {};\n const currentToJSON = (mongooseSchema as any).options?.toJSON || {};\n mongooseSchema.set('toObject', { ...currentToObject, virtuals: true });\n mongooseSchema.set('toJSON', { ...currentToJSON, virtuals: true });\n }\n\n this.applyRelationshipForeignKeyPersistence(\n mongooseSchema,\n resourceConfiguration,\n options.includeIndexes !== false,\n );\n\n // Apply indexes if enabled\n if (options.includeIndexes !== false) {\n this.applyIndexesToSchema(mongooseSchema, indexesToApply, uniqueIndexesToApply, ttlIndexesToApply, resourceConfiguration?.resourceIdentifier as string | undefined, resourceConfiguration);\n // Phase 3.2 fix (review Finding #4 / R2-4): materialise the\n // top-level `.businessKeySet([...])` decorator as a Mongo\n // compound `{ unique: true }` index. Without this, the Zod\n // metadata is enforced at the **type** layer (filter builders,\n // `findByBusinessKey` callers) but NOT at the DB layer, leaving\n // race-prone find-then-create paths (e.g. data-seed\n // `DataSeedDispatcher.startRun`) free to insert duplicate\n // business-key rows under concurrency. Single-field business\n // keys are already covered by the field-level\n // `isBusinessKey() ⇒ isUnique` translation, so this only\n // applies to length ≥ 2 composite keys (centralised here so\n // every business-keyed resource benefits, not just\n // `DataSeedRun`).\n this.applyBusinessKeyCompoundUniqueIndex(mongooseSchema, zodSchema, resourceConfiguration);\n }\n\n return {\n mongooseSchema,\n inheritanceSchemas\n };\n } catch (error) {\n // Cleanup\n inheritanceSchemas.length = 0;\n indexesToApply.length = 0;\n ttlIndexesToApply.length = 0;\n uniqueIndexesToApply.length = 0;\n\n const conversionError = this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED,\n context: {\n originalError: describeCaughtError(error),\n maxDepth: options.maxDepth\n }\n }\n );\n throw conversionError;\n } finally {\n // The set belongs to THIS conversion; the next one (another resource) starts from its own.\n this.virtualTargetForeignKeyFields = new Set();\n }\n }\n\n /**\n * Converts a Zod type to a Mongoose schema definition\n * @param zodType The Zod type to convert\n * @param processedSchemas Set to track circular references\n * @param inheritanceSchemas Array to collect union inheritance schemas\n * @param indexesToApply Array to collect index paths\n * @param uniqueIndexesToApply Array to collect unique index paths with params\n * @param ttlIndexesToApply Array to collect TTL index paths with params\n * @param currentPath Current object path for indexing\n * @param currentDepth Current recursion depth\n * @param maxDepth Maximum allowed recursion depth\n * @returns The Mongoose schema definition\n */\n private convertZodTypeToMongooseDefinition(\n zodType: z.ZodTypeAny,\n processedSchemas: WeakSet<z.ZodTypeAny>,\n schemaCache: WeakMap<z.ZodTypeAny, Schema>,\n inheritanceSchemas: UnionInheritance_SchemaInfo[],\n indexesToApply: string[],\n uniqueIndexesToApply: UniqueIndexInfo[],\n ttlIndexesToApply: TtlIndexInfo[],\n currentPath: string = '',\n currentDepth: number = 0,\n maxDepth: number = 10\n ): any {\n\n\n\n // Depth check\n if (currentDepth >= maxDepth) {\n return { type: Schema.Types.Mixed };\n }\n\n try {\n // Handle pipe types (from .transform(), .pipe(), etc.) - unwrap to input schema\n // In Zod v4, transforms create pipe types with 'in' and 'out' schemas\n if (isZodPipe(zodType)) {\n const inputSchema = getPipeInputSchema(zodType);\n if (inputSchema) {\n // For pipe types, recursively process the input schema\n return this.convertZodTypeToMongooseDefinition(\n inputSchema,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n }\n }\n\n // Handle ZodObject (main case for resource schemas)\n // In Zod v4, object schemas have type: \"object\"\n if (isZodObject(zodType)) {\n\n // Check cache for existing schema to handle recursion\n if (schemaCache.has(zodType)) {\n return schemaCache.get(zodType);\n }\n\n // Create a new Schema instance immediately to allow self-reference\n // We use a temporary empty definition, then add paths to it\n const newSchema = new Schema({}, SCHEMA_SUBDOCUMENT_OPTIONS);\n schemaCache.set(zodType, newSchema);\n\n // Use public .shape property (Zod v4 API)\n const shape = getZodObjectShape(zodType);\n\n\n\n const mongooseDefinition: any = {};\n\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n if (fieldName.startsWith('$') || typeof fieldSchema !== 'object' || fieldSchema === null) {\n if (fieldName.startsWith('$')) {\n this.logger.warn(`[ZodToMongoose] Skipping '$'-prefixed key '${fieldName}' (value type: ${typeof fieldSchema}) at path='${currentPath}'. Assumed Zod internal — if this is a user field, the filter is incorrect.`);\n }\n continue;\n }\n\n // Virtual fields (isVirtual) are computed at read time by\n // VirtualFieldsBackendService and never persisted — they must NOT produce\n // a Mongoose path. Their declared `dependencies` are ordinary stored\n // fields and are emitted normally, so the computation still has its\n // inputs. Skipping here keeps computed fields out of the database schema.\n if (isVirtualField(fieldSchema as z.ZodTypeAny)) {\n continue;\n }\n\n const fieldPath = currentPath ? `${currentPath}.${fieldName}` : fieldName;\n\n const fieldDefinition = this.convertZodFieldToMongooseField(\n fieldSchema as z.ZodTypeAny,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n fieldPath,\n currentDepth + 1,\n maxDepth\n );\n\n // Safety check: ensure field definition is valid\n if (!fieldDefinition || typeof fieldDefinition !== 'object' ||\n (!fieldDefinition.type && !Array.isArray(fieldDefinition) && typeof fieldDefinition !== 'object')) {\n this.logger.warn(`[ZodToMongoose] Invalid field definition for ${fieldPath}`, { fieldDefinition });\n this.logger.warn(`[ZodToMongoose] Zod field type was: ${typeof fieldSchema}`);\n mongooseDefinition[fieldName] = { type: Schema.Types.Mixed };\n } else {\n // CRITICAL: If fieldDefinition is a Schema instance (from nested object),\n // wrap it in { type: ... } to prevent Mongoose from iterating over its properties\n if (this.isSchemaLike(fieldDefinition)) {\n mongooseDefinition[fieldName] = {\n type: fieldDefinition,\n _id: false\n };\n } else {\n mongooseDefinition[fieldName] = fieldDefinition;\n }\n }\n }\n\n // Final validation: ensure all fields have proper type properties\n // Only validate at depth 0 (top-level). Nested objects will be validated by Mongoose\n // when they're added to their parent schema\n if (currentDepth === 0) {\n this.validateAndFixFieldTypes(mongooseDefinition, 'unknown');\n }\n\n // If this is the top-level call (depth 0), we return the definition object\n // so the caller can create the main Schema.\n // If this is a nested object (depth > 0), we return the Schema instance we created.\n if (currentDepth === 0) {\n return mongooseDefinition;\n } else {\n newSchema.add(mongooseDefinition);\n this.applyStandardTransforms(newSchema);\n return newSchema;\n }\n }\n\n // For non-object types, convert as field\n return this.convertZodFieldToMongooseField(\n zodType,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n } catch (error) {\n processedSchemas.delete(zodType);\n this.logger.error(`[ZodToMongoose] convertZodTypeToMongooseDefinition FAILED at path='${currentPath}', depth=${currentDepth}: ${describeCaughtError(error)}`);\n throw error;\n }\n }\n\n // =================================================================\n // FIELD CONVERSION METHODS\n // =================================================================\n\n /**\n * Converts a single Zod field to a Mongoose field definition\n * @param zodField The Zod field schema\n * @param processedSchemas Set to track circular references\n * @param inheritanceSchemas Array to collect union inheritance schemas\n * @param indexesToApply Array to collect index paths\n * @param ttlIndexesToApply Array to collect TTL index paths\n * @param currentPath Current field path\n * @param currentDepth Current recursion depth\n * @param maxDepth Maximum allowed recursion depth\n * @returns The Mongoose field definition\n */\n private convertZodFieldToMongooseField(\n zodField: z.ZodTypeAny,\n processedSchemas: WeakSet<z.ZodTypeAny>,\n schemaCache: WeakMap<z.ZodTypeAny, Schema>,\n inheritanceSchemas: UnionInheritance_SchemaInfo[],\n indexesToApply: string[],\n uniqueIndexesToApply: UniqueIndexInfo[],\n ttlIndexesToApply: TtlIndexInfo[],\n currentPath: string,\n currentDepth: number,\n maxDepth: number\n ): any {\n\n // Special handling for the TOP-LEVEL `_id` — the document's canonical Mongo\n // key — which is always an auto-generatable ObjectId. A NESTED/embedded `_id`\n // (currentPath like `standaloneTasks[]._id`) is a different thing: an authored\n // identity field declared in the Zod schema (e.g. the tasks embedded in an\n // ActorSystem execution's `standaloneTasks` array, whose `_id` is the task\n // row's id). Forcing THAT to ObjectId + disabling `_id` on the subdoc wrapper\n // (see the nested-object branch below) silently DROPPED it on the Mongo\n // round-trip (first-live bug, 2026-07-08: read-back embedded tasks had no\n // `_id`, so the execution-snapshot re-sync appended a duplicate and failed\n // validation). For a nested `_id`, fall through to the standard declared-type\n // conversion so its Zod type (typically `z.string()`) is honored and persists.\n const fieldName = currentPath.split('.').pop() || '';\n if (fieldName === '_id' && currentPath === '_id') {\n const definition: any = {\n type: Schema.Types.ObjectId,\n // Ensure Mongoose can auto-generate _id when not provided\n default: () => new Types.ObjectId(),\n required: false\n };\n\n return definition;\n }\n\n // Unwrap optional fields\n // In Zod v4, optional schemas have type: \"optional\"\n if (isZodOptional(zodField)) {\n const innerType = getZodDefSchemaProperty(zodField, 'innerType');\n if (!innerType) {\n return { type: Schema.Types.Mixed, required: false };\n }\n const innerField = this.convertZodFieldToMongooseField(\n innerType,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n // For optional fields, explicitly ensure they are NOT required\n if (!innerField || typeof innerField !== 'object') {\n return { type: Schema.Types.Mixed, required: false };\n }\n\n /*\n * An OPTIONAL array stays ABSENT when nothing wrote it. A bare Mongoose array path defaults to `[]` — on\n * save and again when a stored document that lacks the field is read back — so \"absent\" and \"empty\" became\n * one value on MongoDB while PostgreSQL keeps them apart. That broke every schema that tells them apart:\n * `providers.packages` is optional (\"absent means none\") but refuses an empty listing (#1676), so the\n * platform's own application config, written without it, came back with `packages: []` and a fresh\n * platform's INIT died re-reading it (framework 1.1.7). `default: undefined` is Mongoose's documented way to\n * disable the array default; a REQUIRED array keeps it, and an explicitly written `[]` is still stored.\n */\n if (Array.isArray(innerField)) {\n return { type: innerField, default: undefined };\n }\n\n // CRITICAL: If innerField is a Schema instance (from nested object), wrap it properly\n // Do NOT destructure Schema instances as this spreads their internal properties\n if (this.isSchemaLike(innerField)) {\n return {\n type: innerField,\n required: false,\n _id: false\n };\n }\n\n // Remove any required: true and explicitly set required: false for optional fields\n const { required, ...optionalField } = innerField;\n\n // Explicitly set required: false to ensure Mongoose recognizes this as optional\n const result = Object.keys(optionalField).length === 0 && innerField.type\n ? { type: innerField.type, required: false }\n : { ...optionalField, required: false };\n\n return result;\n }\n\n // Unwrap nullable fields\n // In Zod v4, nullable schemas have type: \"nullable\"\n if (isZodNullable(zodField)) {\n const innerType = getZodDefSchemaProperty(zodField, 'innerType');\n if (!innerType) {\n return { type: Schema.Types.Mixed };\n }\n const innerField = this.convertZodFieldToMongooseField(\n innerType,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n // Ensure we always have at least the type information\n if (!innerField || typeof innerField !== 'object') {\n return { type: Schema.Types.Mixed };\n }\n\n // An array definition (`[String]`) passes through untouched, as the optional and default branches\n // already do (#1776). Destructuring it below turned `[String]` into `{ \"0\": String }`, and an outer\n // `.optional()` then added `required: false` to that plain object, which Mongoose reads as a nested\n // PATH named `required` defined as `false` — so `z.array(…).nullish()` refused the whole model.\n if (Array.isArray(innerField)) {\n return innerField;\n }\n\n // CRITICAL: If innerField is a Schema instance (from nested object), wrap it properly\n // Do NOT destructure Schema instances as this spreads their internal properties\n if (this.isSchemaLike(innerField)) {\n return {\n type: innerField,\n _id: false\n };\n }\n\n // For nullable fields, we typically don't want required=true\n const { required, ...nullableField } = innerField;\n if (Object.keys(nullableField).length === 0 && innerField.type) {\n return { type: innerField.type };\n }\n return nullableField;\n }\n\n // Unwrap default fields\n // In Zod v4, default schemas have type: \"default\"\n if (isZodDefault(zodField)) {\n /**\n * ⚠️ In Zod 4 `def.defaultValue` is a GETTER, not a stored value.\n *\n * Reading it EVALUATES the default: `z.date().default(() => new Date())`\n * yields a fresh `Date` on every read (verified — two reads are not the same\n * reference), and a literal default yields its value. There is therefore no\n * \"thunk\" to detect and forward — `typeof … === 'function'` is never true for\n * a dynamic default, only for a default whose VALUE happens to be a function.\n *\n * So a single read here is a materialization, and this method runs ONCE per\n * model at model-build time (process start). Handing Mongoose that value\n * freezes it for the life of the process: every document inserted by that\n * process is stamped with the same instant. Mongoose does not rescue it — a\n * `default` is applied at document construction, and the `timestamps` plugin\n * explicitly DEFERS to an already-set path, so a frozen `createdAt` shadows\n * the plugin silently.\n *\n * Measured before this fix (Wonder Todos, 2026-08-10): `auditLogs` held three\n * distinct `createdAt` values across its newest 200 rows — one per backend\n * boot — and `createdAt` is that resource's only event timestamp, so ordering\n * within a boot was unrecoverable. The same freeze reached\n * `jobExecutions.createdAt`, which then carried a 30-day TTL index (rows expired\n * relative to boot, not to creation; current cleanup uses `expiresAt`), the pending-invitation and\n * anonymous-session sweeps (which DELETE by a `createdAt` cutoff), and\n * business fields such as `files.uploadedAt` / `userIdentityLinks.linkedAt`.\n * The error equals process uptime and always points into the past, so every\n * one of those consumers acts too early — invisible on a dev machine that\n * restarts constantly, progressively worse on a long-lived pod.\n */\n const defaultValueProp = getZodDefProperty(zodField, 'defaultValue');\n\n /**\n * The MATERIALIZED default — used ONLY for structural decisions below (is\n * this a nested object? which nested paths carry their own default?). Reading\n * it once is correct for inspection and wrong for persistence.\n */\n const defaultValue = typeof defaultValueProp === 'function'\n ? (defaultValueProp as () => unknown)()\n : defaultValueProp;\n\n /**\n * What Mongoose actually receives: a function that RE-READS the Zod getter,\n * so the default is evaluated per document instead of per model.\n *\n * Applied uniformly rather than only to dynamic defaults — a literal simply\n * returns its value on each read, and routing object/array literals through\n * the getter additionally retires a latent second defect, where a single\n * materialized instance was shared as the default of every document of the\n * model.\n */\n const mongooseDefault = (): unknown => getZodDefProperty(zodField, 'defaultValue');\n\n const innerType = getZodDefSchemaProperty(zodField, 'innerType');\n if (!innerType) {\n return { type: Schema.Types.Mixed, default: mongooseDefault };\n }\n\n const innerField = this.convertZodFieldToMongooseField(\n innerType,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n\n // Remove required property for fields with defaults (Mongoose treats absence as optional)\n // Ensure we always have at least the type information\n if (!innerField || typeof innerField !== 'object') {\n return { type: Schema.Types.Mixed, default: mongooseDefault };\n }\n\n // Handle arrays BEFORE destructuring (arrays don't have required property)\n if (Array.isArray(innerField)) {\n return {\n type: innerField,\n default: mongooseDefault\n };\n }\n\n // CRITICAL: If innerField is a Schema instance (from nested object), wrap it properly\n // Do NOT destructure Schema instances as this spreads their internal properties\n if (this.isSchemaLike(innerField)) {\n return {\n type: innerField,\n default: mongooseDefault,\n _id: false\n };\n }\n\n const { required, ...fieldWithoutRequired } = innerField;\n\n // Check if this is a nested object schema (has 'type' property with nested fields)\n // CRITICAL: Do NOT spread if type is a Schema instance!\n const isNestedObjectSchema = fieldWithoutRequired.type &&\n typeof fieldWithoutRequired.type === 'object' &&\n !Array.isArray(fieldWithoutRequired.type) &&\n !this.isSchemaLike(fieldWithoutRequired.type) &&\n Object.keys(fieldWithoutRequired.type).length > 0;\n\n if (isNestedObjectSchema && defaultValue && typeof defaultValue === 'object') {\n // For nested objects with defaults, preserve field type definitions\n // and merge defaults into the appropriate fields\n const nestedFields = { ...fieldWithoutRequired.type };\n\n for (const [fieldName, defaultFieldValue] of Object.entries(defaultValue)) {\n if (nestedFields[fieldName] && typeof nestedFields[fieldName] === 'object') {\n // Preserve the existing field definition and add the default\n nestedFields[fieldName] = {\n ...nestedFields[fieldName],\n default: defaultFieldValue\n };\n }\n }\n\n return {\n type: nestedFields,\n // The per-path defaults merged above come from the materialized value\n // (they are structural); the OBJECT default stays the thunk so each\n // document builds its own instance instead of sharing one.\n default: mongooseDefault,\n _id: false\n };\n }\n\n // This check is no longer needed since arrays are handled before destructuring\n\n // Ensure we have at least the type property for primitive fields\n const result = Object.keys(fieldWithoutRequired).length === 0 && innerField.type\n ? { type: innerField.type }\n : fieldWithoutRequired;\n\n return {\n ...result,\n default: mongooseDefault\n };\n }\n\n // Handle pipe types (from .transform(), .pipe(), etc.) - extract the input schema\n // In Zod v4, transforms create pipe types with 'in' and 'out' schemas\n if (isZodPipe(zodField)) {\n const inputSchema = getPipeInputSchema(zodField);\n if (inputSchema) {\n return this.convertZodFieldToMongooseField(\n inputSchema,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n }\n }\n\n // Handle transform types (standalone transform, no underlying schema)\n // In Zod v4, transform types are standalone\n if (isZodTransform(zodField)) {\n // Transform types don't have an underlying schema, return Mixed\n return { type: Schema.Types.Mixed };\n }\n\n // Handle custom types (from .refine(), .superRefine(), etc.)\n // In Zod v4, custom types don't wrap schemas - refinements are stored as checks\n // For custom types, we need to check if there's an underlying schema\n // This is complex - for now, return Mixed\n if (isZodCustom(zodField)) {\n return { type: Schema.Types.Mixed };\n }\n\n // Handle arrays\n // In Zod v4, array schemas have type: \"array\"\n if (isZodArray(zodField)) {\n const element = getZodDefSchemaProperty(zodField, 'element');\n if (!element) {\n return [{ type: Schema.Types.Mixed }];\n }\n\n const elementType = this.convertZodFieldToMongooseField(\n element,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n `${currentPath}[]`,\n currentDepth + 1,\n maxDepth\n );\n\n // Check for array-level decorators before returning\n let arrayDefinition: any = [elementType];\n\n // Handle array-level resource reference (convert array elements to ObjectId — or, for an array of keys of a\n // VIRTUAL resource, to its synthesized string keys: #1939)\n if (isForeignKey(zodField)) {\n arrayDefinition = [{\n type: this.foreignKeyStorageType(currentPath)\n }];\n }\n\n // Collect index information for decorated array fields\n // Skip primary keys - they're already indexed via unique index or field-level index\n if (isDBIndexed(zodField) && !isPrimaryKey(zodField) && currentPath) {\n indexesToApply.push(currentPath);\n }\n\n // Collect unique index information for array fields\n if (isUnique(zodField) && currentPath) {\n const uniqueParams = getUniqueParams(zodField);\n uniqueIndexesToApply.push({ path: currentPath, params: uniqueParams || {} });\n }\n\n // Collect TTL index information for array fields (rare, but possible for array of dates)\n if (hasTtl(zodField) && currentPath) {\n const ttlParams = getTtlParams(zodField);\n if (ttlParams) {\n ttlIndexesToApply.push({ path: currentPath, params: ttlParams });\n }\n }\n\n return arrayDefinition;\n }\n\n // Handle tuples\n // In Zod v4, tuple schemas have type: \"tuple\"\n if (isZodTuple(zodField)) {\n return [{ type: Schema.Types.Mixed }];\n }\n\n // Handle nested objects\n // In Zod v4, object schemas have type: \"object\"\n if (isZodObject(zodField)) {\n const nestedDefinition = this.convertZodTypeToMongooseDefinition(\n zodField,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n\n // Honor an EXPLICITLY-declared `_id` on the embedded object (the\n // \"unless explicitly defined\" the legacy comment promised but did not\n // deliver). A subdocument whose Zod shape declares `_id` carries an\n // authored identity that MUST persist; `_id: false` on the wrapper strips\n // the subschema's own `_id` path, silently losing it on the round-trip\n // (first-live bug, 2026-07-08). Anonymous nested objects (no declared\n // `_id`) keep `_id: false` so Mongoose does not inject a spurious ObjectId.\n const declaresOwnId = Object.prototype.hasOwnProperty.call(getZodObjectShape(zodField), '_id');\n\n // If nestedDefinition is a Schema instance (from cache or new), return it directly as type\n if (nestedDefinition instanceof Schema) {\n return declaresOwnId ? { type: nestedDefinition } : { type: nestedDefinition, _id: false };\n }\n\n // Otherwise wrap the definition\n return declaresOwnId ? { type: nestedDefinition } : { type: nestedDefinition, _id: false };\n }\n\n // Handle discriminated unions\n // At depth 0: collect schema info for Mongoose discriminator model creation (root-level).\n // At depth > 0: flatten into a superset schema. This is intentional — Mongoose embedded\n // discriminators are unstable at depth 3-6 and MongoDB enforces nothing on sub-documents.\n // Zod validates per-variant constraints in the resource pipeline before Mongoose writes.\n if (isDiscriminatedUnion(zodField)) {\n if (currentDepth === 0) {\n return this.handleDiscriminatedUnionField(\n zodField,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n }\n return this.flattenDiscriminatedUnionForSubdocument(\n zodField,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n }\n\n // Handle regular unions - analyze for smart type detection\n // In Zod v4, union schemas have type: \"union\"\n if (isZodUnion(zodField)) {\n return this.handleZodUnion(zodField);\n }\n\n // Handle intersections - merge the types\n // In Zod v4, intersection schemas have type: \"intersection\"\n if (isZodIntersection(zodField)) {\n const left = getZodDefSchemaProperty(zodField, 'left');\n const right = getZodDefSchemaProperty(zodField, 'right');\n\n if (!left || !right) {\n return { type: Schema.Types.Mixed };\n }\n\n const leftDef = this.convertZodFieldToMongooseField(\n left,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n const rightDef = this.convertZodFieldToMongooseField(\n right,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n\n // Merge object definitions\n if (this.isObjectDefinition(leftDef) && this.isObjectDefinition(rightDef)) {\n return { ...leftDef, ...rightDef };\n }\n return { type: Schema.Types.Mixed };\n }\n\n // Handle literals\n // In Zod v4, literal schemas have type: \"literal\" and store their value(s)\n // in def.values — an ARRAY, because z.literal(['a', 'b']) is legal in v4.\n // Reading the legacy Zod 3 def.value returned undefined and silently\n // degraded EVERY literal field to Mixed with enum: [null] — which is how\n // flattened discriminated-union tags escaped enum validation entirely.\n if (isZodLiteral(zodField)) {\n const literalValues = (getZodDefArrayProperty(zodField, 'values') ?? [getZodDefProperty(zodField, 'value')])\n .filter((value) => value !== undefined && value !== null);\n if (literalValues.length === 0) {\n // z.literal(null) / z.literal(undefined): Mixed accepts the nullish value.\n return { type: Schema.Types.Mixed };\n }\n const firstValue = literalValues[0];\n return {\n type: typeof firstValue === 'string' ? String :\n typeof firstValue === 'number' ? Number :\n typeof firstValue === 'boolean' ? Boolean : Schema.Types.Mixed,\n enum: literalValues\n };\n }\n\n // Handle lazy types (recursive schemas)\n // In Zod v4, lazy schemas have type: \"lazy\"\n if (isZodLazy(zodField)) {\n const getter = getZodDefFunctionProperty(zodField, 'getter');\n if (!getter) {\n return { type: Schema.Types.Mixed };\n }\n const innerSchema = getter();\n return this.convertZodFieldToMongooseField(\n innerSchema,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n }\n\n // Handle basic types with decorators - unwrap to get the core type\n const coreType = this.unwrapDecoratedType(zodField);\n const baseDefinition = this.getBaseMongooseType(coreType, schemaCache);\n\n // Apply resource reference (ObjectId — or the synthesized string key of a VIRTUAL target: #1939)\n if (isForeignKey(zodField)) {\n const definition: any = {\n type: this.foreignKeyStorageType(currentPath)\n };\n\n // Only add required property if the field is actually required\n if (this.isFieldRequired(zodField)) {\n definition.required = true;\n }\n\n // Collect index information instead of applying immediately\n // Skip primary keys - they're already indexed via unique index or field-level index\n if (isDBIndexed(zodField) && !isPrimaryKey(zodField) && currentPath) {\n indexesToApply.push(currentPath);\n }\n\n // Collect unique index information\n if (isUnique(zodField) && currentPath) {\n const uniqueParams = getUniqueParams(zodField);\n uniqueIndexesToApply.push({ path: currentPath, params: uniqueParams || {} });\n }\n\n return definition;\n }\n\n // Collect TTL index information for Date fields\n // TTL indexes enable automatic document expiration in MongoDB\n if (hasTtl(zodField) && currentPath) {\n const ttlParams = getTtlParams(zodField);\n if (ttlParams) {\n ttlIndexesToApply.push({ path: currentPath, params: ttlParams });\n }\n }\n\n // Collect index information for decorated fields\n // Skip primary keys - they're already indexed via unique index or field-level index\n if (isDBIndexed(zodField) && !isPrimaryKey(zodField) && currentPath) {\n indexesToApply.push(currentPath);\n }\n\n // Collect unique index information for decorated fields\n if (isUnique(zodField) && currentPath) {\n const uniqueParams = getUniqueParams(zodField);\n uniqueIndexesToApply.push({ path: currentPath, params: uniqueParams || {} });\n }\n\n // Only add required property if the field is actually required\n if (this.isFieldRequired(zodField)) {\n const definition = baseDefinition || { type: Schema.Types.Mixed };\n return {\n ...definition,\n required: true\n };\n }\n\n return baseDefinition || { type: Schema.Types.Mixed };\n }\n\n // =================================================================\n // TYPE HANDLING METHODS\n // =================================================================\n\n /**\n * Flattens a discriminated union into a superset schema for embedded sub-documents.\n *\n * This is the **intended persistence strategy** for discriminated unions nested inside\n * sub-documents. Mongoose embedded discriminators (both array and single-nested) exist\n * but have known instability at depth 3-6 (field stripping, validation inconsistencies,\n * query hydration bugs — see Mongoose issues #10702, #12318, #15075). MongoDB itself\n * enforces nothing about sub-document schemas regardless of Mongoose configuration.\n *\n * The architecture relies on **Zod as the authoritative validation layer**: all writes\n * pass through `requestDto.parse()` in the resource operation pipeline before reaching\n * Mongoose. The superset schema preserves field types and indexes while Zod enforces\n * per-variant required constraints.\n *\n * WHAT THIS METHOD DOES:\n * - Merges all fields from ALL union variants into one flat sub-document schema.\n * - The discriminator key merges the enum values of EVERY variant's tag —\n * the tag is a different literal per variant by construction, so keeping\n * only the first variant's enum would reject every other variant at the\n * Mongoose layer (recovered 2026-07-03: `type: 'structured'` artifacts\n * failed against `enum: ['text']`).\n * - All non-discriminator fields become optional at the Mongoose layer\n * (each variant persists only its own subset).\n * - A field declared by SEVERAL variants with DIFFERENT object shapes (the\n * `content`-per-kind pattern, e.g. `ArtifactInstanceSchema`) merges into a\n * deep all-optional superset of those shapes — NOT first-variant-wins,\n * which let the first variant's required inner paths reject every other\n * variant's payload (\"content.text: Path `text` is required.\" for a\n * Zod-valid structured artifact).\n * - Same-named fields that share a primitive base type union their enum\n * constraints; structurally incompatible fields (object vs primitive,\n * string vs number, differing arrays) degrade to `Schema.Types.Mixed`.\n * - Field types, indexes, and enum values ARE preserved wherever the\n * variants agree (unlike a blanket Schema.Types.Mixed).\n */\n private flattenDiscriminatedUnionForSubdocument(\n zodField: z.ZodTypeAny,\n processedSchemas: WeakSet<z.ZodTypeAny>,\n schemaCache: WeakMap<z.ZodTypeAny, Schema>,\n inheritanceSchemas: UnionInheritance_SchemaInfo[],\n indexesToApply: string[],\n uniqueIndexesToApply: UniqueIndexInfo[],\n ttlIndexesToApply: TtlIndexInfo[],\n currentPath: string,\n currentDepth: number,\n maxDepth: number\n ): any {\n const discriminatorKey = getZodDefStringProperty(zodField, 'discriminator');\n const optionsArray = getZodDefArrayProperty(zodField, 'options');\n\n if (!discriminatorKey || !optionsArray || optionsArray.length === 0) {\n return { type: Schema.Types.Mixed };\n }\n\n const options = optionsArray.filter(isZodTypeAny);\n if (options.length === 0) {\n return { type: Schema.Types.Mixed };\n }\n\n this.logDebug(\n `[ZodToMongoose] Discriminated union at path='${currentPath}' (depth=${currentDepth}): ` +\n `flattening ${options.length} variants into superset schema (discriminator='${discriminatorKey}'). ` +\n `Per-variant required constraints enforced by Zod validation in the resource operation pipeline.`\n );\n\n // Pass 1 — collect the DISTINCT Zod field schemas per field name across\n // all variants. Dedupe by reference: variants built from a common base via\n // `.extend()` share the base field instances, so shared fields collapse to\n // a single schema and only genuinely re-declared fields need merging.\n const variantFieldSchemas = new Map<string, z.ZodTypeAny[]>();\n for (const option of options) {\n if (!isZodObject(option)) continue;\n\n const optionShape = getZodObjectShape(option);\n for (const [fieldName, fieldSchema] of Object.entries(optionShape)) {\n if (typeof fieldSchema !== 'object' || fieldSchema === null) continue;\n let schemas = variantFieldSchemas.get(fieldName);\n if (!schemas) {\n schemas = [];\n variantFieldSchemas.set(fieldName, schemas);\n }\n if (!schemas.includes(fieldSchema as z.ZodTypeAny)) {\n schemas.push(fieldSchema as z.ZodTypeAny);\n }\n }\n }\n\n // Pass 2 — build the merged Mongoose definition.\n const mergedDefinition: Record<string, any> = {};\n for (const [fieldName, schemas] of variantFieldSchemas) {\n const fieldPath = currentPath ? `${currentPath}.${fieldName}` : fieldName;\n const convert = (schema: z.ZodTypeAny): any => this.convertZodFieldToMongooseField(\n schema,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n fieldPath,\n currentDepth + 1,\n maxDepth\n );\n\n if (fieldName === discriminatorKey) {\n // Union the tag values of every variant so each variant's document\n // passes the Mongoose enum validator.\n const discriminatorDef = convert(schemas[0]);\n for (const variantSchema of schemas.slice(1)) {\n const variantDef = convert(variantSchema);\n if (\n discriminatorDef && Array.isArray(discriminatorDef.enum) &&\n variantDef && Array.isArray(variantDef.enum)\n ) {\n discriminatorDef.enum = [...new Set([...discriminatorDef.enum, ...variantDef.enum])];\n }\n }\n mergedDefinition[fieldName] = discriminatorDef ?? { type: Schema.Types.Mixed };\n continue;\n }\n\n const fieldDef = schemas.length === 1\n ? convert(schemas[0])\n : this.convertConflictingVariantField(schemas, convert);\n\n // Non-discriminator fields are optional at the Mongoose layer — each\n // variant persists only its own subset; Zod owns per-variant required.\n if (typeof fieldDef === 'object' && fieldDef !== null && !Array.isArray(fieldDef) && !(fieldDef instanceof Schema)) {\n mergedDefinition[fieldName] = { ...fieldDef, required: false };\n } else {\n mergedDefinition[fieldName] = fieldDef;\n }\n }\n\n const nestedSchema = new Schema(mergedDefinition, SCHEMA_SUBDOCUMENT_OPTIONS);\n this.applyStandardTransforms(nestedSchema);\n return nestedSchema;\n }\n\n /**\n * Converts a field that is declared with DIFFERENT Zod schemas across the\n * variants of a flattened discriminated union (see\n * {@link flattenDiscriminatedUnionForSubdocument}).\n *\n * Resolution order:\n * 1. Every variant declares an object payload (the `content`-per-kind\n * pattern) → convert a deep all-optional superset of those shapes so\n * paths stay typed and no variant's required inner field leaks onto the\n * others.\n * 2. Every variant converts to the same primitive Mongoose type → keep the\n * shared type; union enum constraints when ALL variants are\n * enum-constrained, drop the enum when any variant is unconstrained\n * (a constrained enum would reject the unconstrained variant's values).\n * 3. Structurally incompatible (object vs primitive, string vs number,\n * differing array elements, …) → `Schema.Types.Mixed`. First-variant-wins\n * is NOT an option: it validates every other variant against a shape it\n * never declared.\n */\n private convertConflictingVariantField(\n schemas: z.ZodTypeAny[],\n convert: (schema: z.ZodTypeAny) => any\n ): any {\n const supersetObject = this.buildVariantObjectSupersetSchema(schemas);\n if (supersetObject) {\n return convert(supersetObject);\n }\n\n const isPlainDefinition = (definition: any): boolean =>\n typeof definition === 'object' && definition !== null &&\n !Array.isArray(definition) && !(definition instanceof Schema);\n\n const variantDefs = schemas.map(convert);\n const firstDef = variantDefs[0];\n if (isPlainDefinition(firstDef) && variantDefs.every((definition) => isPlainDefinition(definition) && definition.type === firstDef.type)) {\n if (variantDefs.every((definition) => Array.isArray(definition.enum))) {\n return { ...firstDef, enum: [...new Set(variantDefs.flatMap((definition) => definition.enum))] };\n }\n const { enum: _unconstrainedAcrossVariants, ...withoutEnum } = firstDef;\n return withoutEnum;\n }\n\n return { type: Schema.Types.Mixed };\n }\n\n /**\n * Builds an all-optional superset Zod object for a field whose variants each\n * declare a (different) object payload under the same name.\n *\n * The superset is built at the ZOD level — not by merging converted Mongoose\n * definitions — so the regular conversion pipeline (decorators, nested\n * unions, arrays, defaults) applies unchanged to the merged shape. Every\n * superset field is wrapped `.optional()`: a field required by one variant\n * is absent from the others by construction, and per-variant requiredness is\n * enforced by Zod in the resource operation pipeline before Mongoose writes.\n *\n * Inner same-named fields that are themselves objects in every variant merge\n * recursively; anything else that conflicts degrades to `z.any()` (persisted\n * as `Schema.Types.Mixed`).\n *\n * @returns the superset object schema, or null when any variant's core type\n * is not a plain Zod object (the caller falls back to primitive\n * enum merging or Mixed).\n */\n private buildVariantObjectSupersetSchema(schemas: z.ZodTypeAny[]): z.ZodTypeAny | null {\n const coreSchemas = schemas.map((schema) => this.unwrapDecoratedType(schema));\n if (coreSchemas.length === 0 || !coreSchemas.every((core) => isZodObject(core))) {\n return null;\n }\n\n const fieldSchemasByName = new Map<string, z.ZodTypeAny[]>();\n for (const core of coreSchemas) {\n const shape = getZodObjectShape(core);\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n if (typeof fieldSchema !== 'object' || fieldSchema === null) continue;\n let list = fieldSchemasByName.get(fieldName);\n if (!list) {\n list = [];\n fieldSchemasByName.set(fieldName, list);\n }\n if (!list.includes(fieldSchema as z.ZodTypeAny)) {\n list.push(fieldSchema as z.ZodTypeAny);\n }\n }\n }\n\n const supersetShape: Record<string, z.ZodTypeAny> = {};\n for (const [fieldName, fieldSchemas] of fieldSchemasByName) {\n const merged: z.ZodTypeAny = fieldSchemas.length === 1\n ? fieldSchemas[0]\n : (this.buildVariantObjectSupersetSchema(fieldSchemas) ?? z.any());\n supersetShape[fieldName] = isZodOptional(merged) ? merged : merged.optional();\n }\n\n return z.object(supersetShape);\n }\n\n /**\n * Handles discriminated union fields by collecting schema information\n * @param zodField The discriminated union field\n * @param processedSchemas Set to track circular references\n * @param inheritanceSchemas Array to collect union inheritance schemas\n * @param indexesToApply Array to collect index paths\n * @param currentPath Current field path\n * @param currentDepth Current recursion depth\n * @param maxDepth Maximum allowed recursion depth\n * @returns Base schema definition for the discriminated union\n */\n private handleDiscriminatedUnionField(\n zodField: z.ZodTypeAny,\n processedSchemas: WeakSet<z.ZodTypeAny>,\n schemaCache: WeakMap<z.ZodTypeAny, Schema>,\n inheritanceSchemas: UnionInheritance_SchemaInfo[],\n indexesToApply: string[],\n uniqueIndexesToApply: UniqueIndexInfo[],\n ttlIndexesToApply: TtlIndexInfo[],\n currentPath: string,\n currentDepth: number,\n maxDepth: number\n ): any {\n\n const discriminatorKey = getZodDefStringProperty(zodField, 'discriminator');\n const optionsArray = getZodDefArrayProperty(zodField, 'options');\n\n if (!discriminatorKey || !optionsArray || optionsArray.length === 0) {\n return { type: Schema.Types.Mixed };\n }\n\n // Filter and validate options are ZodTypeAny\n const options = optionsArray.filter(isZodTypeAny);\n if (options.length === 0) {\n return { type: Schema.Types.Mixed };\n }\n\n // Use the first option as the union root schema structure\n const rootOption = options[0];\n const rootDefinition = this.convertZodTypeToMongooseDefinition(\n rootOption,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n\n // Collect union inheritance schemas for later model creation (but don't create models here)\n for (let optionIndex = 0; optionIndex < options.length; optionIndex++) {\n const option = options[optionIndex];\n try {\n const optionDefinition = this.convertZodTypeToMongooseDefinition(\n option,\n processedSchemas,\n schemaCache,\n inheritanceSchemas,\n indexesToApply,\n uniqueIndexesToApply,\n ttlIndexesToApply,\n currentPath,\n currentDepth,\n maxDepth\n );\n\n // Create Mongoose schema for this union inheritance option\n const inheritanceOptionSchema = new Schema(optionDefinition, SCHEMA_SUBDOCUMENT_OPTIONS);\n this.applyStandardTransforms(inheritanceOptionSchema);\n\n // Extract discriminator value from the option's shape.\n // Unwrap the discriminator field to handle optional/nullable/default wrappers.\n //\n // `getEnumValues` is the Zod-4-correct reader: it reads a literal's\n // value from `def.values` (an ARRAY in Zod 4) and also handles\n // z.enum / native-enum / union discriminators. The prior code read the\n // legacy Zod-3 `def.value` (always undefined in Zod 4), so EVERY\n // literal-tagged variant fell through to the `option_${index}` fallback\n // below — root-union resources then registered their Mongoose\n // discriminators as `<Model>_option_0` instead of `<Model>_<tag>`.\n // getEnumValues only surfaces STRING literals; the direct `def.values`\n // read covers number/boolean literal discriminators it skips.\n let discriminatorValue: string | null = null;\n if (discriminatorKey && isZodObject(option)) {\n const optionShape = getZodObjectShape(option);\n const discriminatorField = optionShape[discriminatorKey];\n if (discriminatorField) {\n const unwrappedField = unwrapSchema(discriminatorField);\n const enumValues = getEnumValues(unwrappedField);\n if (enumValues.length > 0) {\n discriminatorValue = String(enumValues[0]);\n } else if (isZodLiteral(unwrappedField)) {\n const literalValues = getZodDefArrayProperty(unwrappedField, 'values')\n ?? [getZodDefProperty(unwrappedField, 'value')];\n const firstLiteral = literalValues.find((value) => value !== undefined && value !== null);\n if (firstLiteral !== undefined) {\n discriminatorValue = String(firstLiteral);\n }\n }\n }\n }\n\n // If we couldn't extract a discriminator value, use index-based fallback to ensure uniqueness\n // This prevents \"Discriminator with name 'unknown' already exists\" errors\n if (!discriminatorValue || discriminatorValue === 'unknown') {\n discriminatorValue = `option_${optionIndex}`;\n this.logDebug(`Could not extract discriminator value for union option ${optionIndex}, using fallback: ${discriminatorValue}`, {\n discriminatorKey,\n optionIndex\n });\n }\n\n // Store schema information for later inheritance model creation\n inheritanceSchemas.push({\n discriminatorKey,\n discriminatorValue: String(discriminatorValue),\n schema: inheritanceOptionSchema,\n zodSchema: option\n });\n } catch (error) {\n this.logger.warn(`Failed to process union inheritance option: ${describeCaughtError(error)}`);\n }\n }\n\n // Return the union root definition with discriminator key\n return {\n ...rootDefinition,\n discriminatorKey\n };\n }\n\n /**\n * Unwraps decorated Zod types to get the core type for instanceof checks\n * @param zodField The potentially decorated Zod field\n * @returns The core Zod type without decoration wrappers\n */\n private unwrapDecoratedType(zodField: z.ZodTypeAny): z.ZodTypeAny {\n // Use the centralized unwrapSchema function from zod-decorators\n return unwrapSchema(zodField);\n }\n\n /**\n * Handles ZodUnion types intelligently\n * @param zodUnion The Zod union to analyze\n * @returns Appropriate Mongoose type definition\n */\n private handleZodUnion(zodUnion: z.ZodTypeAny): any {\n const options = getZodDefArrayProperty(zodUnion, 'options');\n if (!options) {\n return { type: Schema.Types.Mixed };\n }\n\n // Collect all enum values and check if all options are string-like\n const enumValues: string[] = [];\n let allStringLike = true;\n\n for (const option of options) {\n if (!isZodTypeAny(option)) continue;\n\n const optionType = getZodType(option);\n\n // Handle enum (check for entries in Zod v4, or enum property for native enums)\n if (optionType === 'enum') {\n // Use centralized getEnumValues function\n const optionEnumValues = getEnumValues(option);\n enumValues.push(...optionEnumValues);\n continue;\n }\n\n // Handle ZodString (allows any string)\n if (optionType === 'string') {\n // String type allows any string value, so we just continue\n continue;\n }\n\n // If we encounter a non-string type, fall back to Mixed\n allStringLike = false;\n break;\n }\n\n // If all options are string-like (enum + string), return String with enum validation\n if (allStringLike) {\n if (enumValues.length > 0) {\n return {\n type: String,\n enum: [...new Set(enumValues)] // Remove duplicates\n };\n } else {\n return { type: String };\n }\n }\n\n // Fall back to Mixed for complex unions\n return { type: Schema.Types.Mixed };\n }\n\n /**\n * Gets the base Mongoose type for a Zod field\n * @param zodField The Zod field to get the type for\n * @param schemaCache Cache of created schemas for recursive types\n * @returns The base Mongoose type definition\n */\n private getBaseMongooseType(zodField: z.ZodTypeAny, schemaCache?: WeakMap<z.ZodTypeAny, Schema>): any {\n const zodType = getZodType(zodField);\n\n // Handle string types\n // In Zod v4, string schemas have type: \"string\"\n if (zodType === 'string') {\n const definition: any = { type: String };\n\n // Add string-specific validations\n // In Zod v4, checks are stored in def.checks array\n const checks = getZodDefArrayProperty(zodField, 'checks');\n if (checks) {\n\n for (const check of checks) {\n if (typeof check === 'object' && check !== null) {\n const checkKind = (check as Record<string, unknown>).kind;\n const checkValue = (check as Record<string, unknown>).value;\n\n if (checkKind === 'min' && typeof checkValue === 'number') {\n definition.minlength = checkValue;\n } else if (checkKind === 'max' && typeof checkValue === 'number') {\n definition.maxlength = checkValue;\n } else if (checkKind === 'regex' && checkValue instanceof RegExp) {\n definition.match = checkValue;\n }\n }\n }\n }\n\n return definition;\n }\n\n // Handle number types\n // In Zod v4, number schemas have type: \"number\" or \"int\"\n if (zodType === 'number' || zodType === 'int') {\n const definition: any = { type: Number };\n\n const checks = getZodDefArrayProperty(zodField, 'checks');\n if (checks) {\n\n for (const check of checks) {\n if (typeof check === 'object' && check !== null) {\n const checkKind = (check as Record<string, unknown>).kind;\n const checkValue = (check as Record<string, unknown>).value;\n\n if (checkKind === 'min' && typeof checkValue === 'number') {\n definition.min = checkValue;\n } else if (checkKind === 'max' && typeof checkValue === 'number') {\n definition.max = checkValue;\n }\n }\n }\n }\n\n return definition;\n }\n\n // Handle bigint types\n // In Zod v4, bigint schemas have type: \"bigint\"\n // Mongoose 6+ supports BigInt natively, which stores as BSON Long (64-bit)\n // For arbitrarily large bigints, we store as String for maximum precision\n if (zodType === 'bigint') {\n // Use String type for storage to preserve full precision of arbitrarily large bigints\n // The application layer handles conversion to/from BigInt\n return {\n type: String,\n get: (v: string | null | undefined) => v ? BigInt(v) : v,\n set: (v: bigint | string | null | undefined) => v !== null && v !== undefined ? String(v) : v\n };\n }\n\n // Handle boolean types\n // In Zod v4, boolean schemas have type: \"boolean\"\n if (zodType === 'boolean') {\n return { type: Boolean };\n }\n\n // Handle date types\n // In Zod v4, date schemas have type: \"date\"\n if (zodType === 'date') {\n return { type: Date };\n }\n\n // Handle enum types\n // In Zod v4, enum schemas have type: \"enum\" and values are in def.entries\n if (zodType === 'enum') {\n // Use centralized getEnumValues function\n const enumValues = getEnumValues(zodField);\n\n return {\n type: String,\n enum: enumValues\n };\n }\n\n // NOTE: In Zod v4, .brand() no longer creates a wrapper type.\n // Branded schemas report their underlying type (e.g., 'string') directly.\n // The branding is purely a TypeScript compile-time feature.\n // No special handling is needed for branded types in Zod v4.\n\n // Handle record types - z.record() represents plain objects with dynamic keys\n // In Zod v4, record schemas have type: \"record\"\n if (isZodRecord(zodField)) {\n // Default to Mixed for non-recursive records\n // Only use Map if we detect a recursive schema that requires it\n const valueType = getZodDefSchemaProperty(zodField, 'valueType');\n let mapValueType: any = null;\n\n if (valueType && isZodLazy(valueType)) {\n // For recursive records (like properties: z.record(z.lazy(...))), we MUST use Map with the schema\n // otherwise we lose the recursive structure.\n\n // Try to resolve lazy type from cache if available\n if (schemaCache) {\n const getter = getZodDefFunctionProperty(valueType, 'getter');\n if (getter) {\n const inner = getter();\n if (schemaCache.has(inner)) {\n mapValueType = schemaCache.get(inner);\n }\n }\n }\n }\n\n // If we found a recursive schema, return Map\n if (mapValueType) {\n return { type: Map, of: mapValueType };\n }\n\n // Default to Mixed for non-recursive records\n return { type: Schema.Types.Mixed };\n }\n\n // Handle Set types\n // In Zod v4, set schemas have type: \"set\"\n // Sets are stored as arrays in MongoDB with getter/setter for conversion\n if (zodType === 'set') {\n const valueType = getZodDefSchemaProperty(zodField, 'valueType');\n\n // Try to determine the value type for the Set\n let setValueType: any = Schema.Types.Mixed;\n if (valueType) {\n const valueTypeDefinition = this.getBaseMongooseType(valueType, schemaCache);\n if (valueTypeDefinition?.type) {\n setValueType = valueTypeDefinition.type;\n }\n }\n\n return {\n type: [setValueType],\n get: (v: any[] | null | undefined) => v ? new Set(v) : v,\n set: (v: Set<any> | any[] | null | undefined) => {\n if (v === null || v === undefined) return v;\n return v instanceof Set ? Array.from(v) : v;\n }\n };\n }\n\n // Handle Map types\n // In Zod v4, map schemas have type: \"map\"\n if (zodType === 'map') {\n const valueType = getZodDefSchemaProperty(zodField, 'valueType');\n\n // Try to determine the value type for the Map\n let mapValueType: any = Schema.Types.Mixed;\n if (valueType) {\n const valueTypeDefinition = this.getBaseMongooseType(valueType, schemaCache);\n if (valueTypeDefinition?.type) {\n mapValueType = valueTypeDefinition.type;\n }\n }\n\n return { type: Map, of: mapValueType };\n }\n\n // Handle any/unknown types\n // In Zod v4, any/unknown schemas have type: \"any\" or \"unknown\"\n if (zodType === 'any' || zodType === 'unknown') {\n return { type: Schema.Types.Mixed };\n }\n\n // Handle void/undefined types\n // In Zod v4, void/undefined schemas have type: \"void\" or \"undefined\"\n if (zodType === 'void' || zodType === 'undefined') {\n return { type: Schema.Types.Mixed };\n }\n\n // Handle never type\n // In Zod v4, never schemas have type: \"never\"\n if (zodType === 'never') {\n return { type: Schema.Types.Mixed };\n }\n\n // Fallback for unknown types\n this.logger.warn(`[ZodToMongoose] Unknown Zod type, using Mixed. Type: ${typeof zodField}`);\n return { type: Schema.Types.Mixed };\n }\n\n // =================================================================\n // VALIDATION AND HELPER METHODS\n // =================================================================\n\n /**\n * Validates and fixes field types to ensure Mongoose compatibility\n * @param mongooseDefinition The mongoose schema definition to validate\n * @param resourceType The resource type for debugging\n */\n private validateAndFixFieldTypes(mongooseDefinition: any, resourceType: string): void {\n this.validateFieldsRecursively(mongooseDefinition, resourceType, '');\n }\n\n /**\n * Recursively validates and fixes field types\n * @param obj The object to validate\n * @param resourceType The resource type for debugging\n * @param path The current field path for debugging\n */\n /**\n * Checks if a value is a Mongoose Schema instance or looks like one\n * More robust than instanceof to handle different Schema versions/instances\n */\n private isSchemaLike(value: any): boolean {\n if (!value || typeof value !== 'object') return false;\n // Check instanceof first (most reliable)\n if (value instanceof Schema) {\n return true;\n }\n // Check for Schema constructor\n if (value.constructor && value.constructor.name === 'Schema') {\n return true;\n }\n // Check for Schema-specific properties as fallback\n // A real Schema instance has: paths, methods, statics, virtuals, options\n // Even newly created empty schemas have these\n return (\n typeof value.paths === 'object' &&\n typeof value.methods === 'object' &&\n typeof value.statics === 'object' &&\n typeof value.virtuals === 'object' &&\n typeof value.options === 'object'\n );\n }\n\n\n private validateFieldsRecursively(obj: any, resourceType: string, path: string): void {\n if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {\n return;\n }\n\n\n // CRITICAL: If obj itself is a Schema instance, do not iterate over it\n // Schema instances have internal properties that should not be validated as fields\n if (this.isSchemaLike(obj)) {\n return;\n }\n\n for (const [fieldName, fieldValue] of Object.entries(obj)) {\n const fieldPath = path ? `${path}.${fieldName}` : fieldName;\n\n // CRITICAL: If fieldValue is a Schema instance, skip it entirely\n // Schema instances are already valid and should not be validated\n if (this.isSchemaLike(fieldValue)) {\n continue;\n }\n\n if (fieldValue && typeof fieldValue === 'object' && !Array.isArray(fieldValue)) {\n // CRITICAL: If fieldValue has a 'type' property that is a Schema instance,\n // skip validation entirely - it's already properly wrapped\n if ('type' in fieldValue && this.isSchemaLike(fieldValue.type)) {\n continue;\n }\n\n // Check if this is a field definition (should have a type property or be a nested object)\n const hasTypeProperty = 'type' in fieldValue;\n const hasNestedFields = Object.keys(fieldValue).some(key =>\n key !== 'default' && key !== 'required' && key !== '_id' && key !== 'type' &&\n typeof fieldValue[key] === 'object'\n );\n\n // Valid Mongoose schema properties that don't require a 'type' property\n const validMongooseProperties = [\n 'match', 'min', 'max', 'minlength', 'maxlength',\n 'enum', 'required', 'default', 'validate', 'get', 'set',\n 'transform', 'alias', 'immutable', 'sparse', 'unique',\n 'index', 'select', 'populate', 'discriminator', '_id'\n ];\n\n const hasOnlyValidMongooseProperties = Object.keys(fieldValue).every(key =>\n validMongooseProperties.includes(key)\n );\n\n if (!hasTypeProperty && !hasNestedFields && !hasOnlyValidMongooseProperties) {\n // This field is missing a type property - fix it\n this.logger.warn(`[ZodToMongoose] FIXING field '${fieldPath}' in resource '${resourceType}': Missing type property`);\n this.logger.warn(`[ZodToMongoose] Field value keys: ${Object.keys(fieldValue as Record<string, unknown>).join(', ')}`);\n\n let mongooseType: any = Schema.Types.Mixed; // Default fallback\n\n // Try to infer type from default value if available\n if ('default' in fieldValue) {\n const defaultValue = fieldValue.default;\n if (typeof defaultValue === 'boolean') {\n mongooseType = Schema.Types.Boolean;\n } else if (typeof defaultValue === 'string') {\n mongooseType = Schema.Types.String;\n } else if (typeof defaultValue === 'number') {\n mongooseType = Schema.Types.Number;\n } else if (defaultValue instanceof Date) {\n mongooseType = Schema.Types.Date;\n }\n }\n // For fields with only 'required: true', assume String as a safe default\n else if ('required' in fieldValue && Object.keys(fieldValue).length === 1) {\n mongooseType = String;\n }\n\n // Fix the field definition\n obj[fieldName] = {\n type: mongooseType,\n ...fieldValue\n };\n\n this.logger.warn(`[ZodToMongoose] Fixed to: ${JSON.stringify(obj[fieldName])}`);\n } else if (hasNestedFields) {\n // Recursively validate nested objects, but exclude valid Mongoose properties AND type\n const validMongooseKeys = ['match', 'min', 'max', 'minlength', 'maxlength', 'enum', 'required', 'default', 'validate', 'get', 'set', 'transform', 'alias', 'immutable', 'sparse', 'unique', 'index', 'select', 'populate', 'discriminator', '_id', 'type'];\n const nestedFields = Object.fromEntries(\n Object.entries(fieldValue).filter(([key]) => !validMongooseKeys.includes(key))\n );\n this.validateFieldsRecursively(nestedFields, resourceType, fieldPath);\n } else if (hasTypeProperty && fieldValue.type && typeof fieldValue.type === 'object') {\n // CRITICAL: If fieldValue.type is a Schema instance, DO NOT validate it\n // Schema instances have internal properties (methods, options, etc.) that should not be treated as fields\n if (!this.isSchemaLike(fieldValue.type)) {\n // This is a nested object type (plain object definition) - validate its contents\n this.validateFieldsRecursively(fieldValue.type, resourceType, fieldPath);\n }\n // If it's a Schema instance, we skip validation - it's already a valid Mongoose schema\n }\n }\n }\n }\n\n\n // =================================================================\n // UTILITY AND HELPER METHODS\n // =================================================================\n\n /**\n * The MongoDB collection this resource's model is built over.\n *\n * `USER_SELF*` resources deliberately share their non-SELF counterpart's\n * collection — separate models, one set of rows — so the self door and the\n * admin door address the same records.\n *\n * Delegates to the shared authority\n * (`RESOURCE_SHARED_PERSISTENCE_COLLECTION_ALIASES` in `@wildo-ai/saas-models`)\n * rather than declaring the mapping here. This method is what actually creates\n * and reads the collection, so a local copy makes this the de-facto truth while\n * other consumers — the aggregation collection resolver, and the boot-time\n * retention-coherence guard — quietly disagree with it. That has already\n * happened once: the aggregation resolver returned the FK field identifier\n * instead of the collection, and every aggregation silently read a\n * non-existent collection.\n */\n private getCollectionNameForResource(resourceType: ResourceType): string {\n return resolveSharedPersistenceCollectionName(resourceType);\n }\n\n /**\n * Make the schema paths owned by the Mongoose `timestamps` option\n * (`SCHEMA_DEFAULT_OPTIONS.timestamps` → createdAt/updatedAt) genuinely\n * plugin-owned: drop their `required` validators AND their `default`.\n *\n * Resource zod schemas declare `createdAt`/`updatedAt` as non-optional —\n * truthful for every PERSISTED document — so the zod→mongoose field\n * conversion marks those paths `required: true`. Population, however, is\n * infrastructure-owned: the Mongoose timestamps plugin sets both fields in\n * a pre('save') hook, and since Mongoose 9 document validation runs BEFORE\n * pre('save') middleware (ordering change vs ≤8). A `required` validator on\n * a plugin-populated timestamp therefore rejects EVERY insert with\n * \"Path `createdAt` is required\" — reproduced standalone against\n * mongoose@9.3.3 and recovered 2026-06-12 on the Wonder Todos todoLists\n * create flow (first dogfooded resource CREATE on Mongoose 9).\n *\n * Dropping `required` at the DB layer loses nothing: the plugin\n * deterministically populates both fields on every insert/update, and the\n * zod layer keeps the non-optional read contract. Rejected alternatives:\n * stamping the dates in the repository enrichment (two writers for the\n * same fields, contradicts the repository's \"timestamps are handled by\n * Mongoose\" contract) and making the zod fields optional (weakens the read\n * DTO truth for all consumers).\n *\n * ## Why the `default` goes too (2026-08-11)\n *\n * \"Timestamps are handled by Mongoose\" is the stated contract, and a `default`\n * on those paths quietly breaks it — Mongoose applies a default at DOCUMENT\n * CONSTRUCTION and the timestamps plugin then defers to the already-set path,\n * so the default WINS and the plugin never writes. That made the zod-declared\n * `.default(() => new Date())` the real writer of every `createdAt`, which is\n * how the model-build freeze (see `mongooseDefault` in the default-unwrap\n * branch) reached persistence at all.\n *\n * Passing the thunk through already fixes the freeze. This removal fixes the\n * OWNERSHIP: with the default gone there is exactly ONE writer for these two\n * paths, the one the contract names, instead of two that happen to agree.\n * Note that it is the create path being stripped — `.excludeFromCreate()` —\n * that lets the DB-layer default apply in the first place, so this is not a\n * theoretical tidy-up; it is the seam where the two writers met.\n *\n * Scope is deliberately narrow: ONLY the paths the plugin owns. Every other\n * defaulted field keeps its (now per-document) default.\n */\n private relaxPluginOwnedTimestampRequiredValidators(mongooseSchema: Schema): void {\n const timestampsOption = (mongooseSchema as any).options?.timestamps as\n | boolean\n | { createdAt?: string | boolean; updatedAt?: string | boolean }\n | undefined;\n if (!timestampsOption) {\n return;\n }\n\n const resolvePathName = (value: string | boolean | undefined, fallback: string): string | null => {\n if (value === false) return null;\n return typeof value === 'string' ? value : fallback;\n };\n const timestampPathNames = typeof timestampsOption === 'object'\n ? [resolvePathName(timestampsOption.createdAt, 'createdAt'), resolvePathName(timestampsOption.updatedAt, 'updatedAt')]\n : ['createdAt', 'updatedAt'];\n\n for (const pathName of timestampPathNames) {\n if (!pathName) continue;\n const schemaType = mongooseSchema.path(pathName);\n if (schemaType) {\n schemaType.required(false);\n // Hand the path back to the plugin. `SchemaType#default(undefined)` is\n // Mongoose's documented way to REMOVE a default (as opposed to setting\n // one to `undefined`), and it clears `defaultValue` so nothing is applied\n // at document construction.\n schemaType.default(undefined);\n }\n }\n }\n\n /**\n * Standardizes toObject/toJSON to serialize ObjectId fields as strings.\n * Keeps internal schema types as ObjectId for queries, but outputs strings for DTO parsing.\n */\n private applyStandardTransforms(mongooseSchema: Schema): void {\n const hasToObject = (mongooseSchema as any).options?.toObject;\n const hasToJSON = (mongooseSchema as any).options?.toJSON;\n\n mongooseSchema.set('toObject', {\n ...(hasToObject || {}),\n transform: (doc: any, ret: any) => {\n this.serializeObjectIds(ret);\n if (typeof (hasToObject as any)?.transform === 'function') {\n (hasToObject as any).transform(doc, ret);\n }\n return ret;\n }\n });\n\n mongooseSchema.set('toJSON', {\n ...(hasToJSON || {}),\n transform: (doc: any, ret: any) => {\n this.serializeObjectIds(ret);\n if (typeof (hasToJSON as any)?.transform === 'function') {\n (hasToJSON as any).transform(doc, ret);\n }\n return ret;\n }\n });\n }\n\n private serializeObjectIds(obj: any): void {\n if (!obj || typeof obj !== 'object') return;\n const stack: any[] = [obj];\n while (stack.length) {\n const current = stack.pop();\n for (const key of Object.keys(current)) {\n const value = current[key];\n if (value && typeof value === 'object') {\n // ObjectId array\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const v = value[i] as any;\n if (v && typeof v === 'object' && (v as any)?._bsontype === 'ObjectId') {\n value[i] = String(v);\n } else if (v && typeof v === 'object') {\n stack.push(v);\n }\n }\n } else if ((value as any)?._bsontype === 'ObjectId' || value instanceof (Types as any).ObjectId) {\n current[key] = String(value);\n } else {\n stack.push(value);\n }\n }\n }\n }\n }\n\n /**\n * Determines if a Zod field is required\n * @param zodField The Zod field to check\n * @returns True if the field is required\n */\n private isFieldRequired(zodField: z.ZodTypeAny): boolean {\n // Check if it's wrapped in ZodOptional or ZodNullable\n // In Zod v4, optional/nullable schemas have type: \"optional\" or \"nullable\"\n if (isZodOptional(zodField) || isZodNullable(zodField)) {\n return false;\n }\n\n // Check if it has a default value\n // In Zod v4, default schemas have type: \"default\"\n if (isZodDefault(zodField)) {\n return false;\n }\n\n // Otherwise, it's required\n return true;\n }\n\n /**\n * Applies indexes to a Mongoose schema\n * @param mongooseSchema The schema to apply indexes to\n * @param indexesToApply Array of field paths to index\n * @param uniqueIndexesToApply Array of unique index info with paths and params\n * @param ttlIndexesToApply Array of TTL index info with paths and params\n * @param resourceType Optional resource type for diagnostic logging\n */\n private applyIndexesToSchema(\n mongooseSchema: Schema,\n indexesToApply: string[],\n uniqueIndexesToApply: UniqueIndexInfo[] = [],\n ttlIndexesToApply: TtlIndexInfo[] = [],\n resourceType?: string,\n resourceConfiguration?: RetentionGovernanceSignal,\n ): void {\n const appliedPaths = new Set<string>();\n\n // First, collect all paths that will have unique indexes to avoid duplicates\n const uniqueIndexPaths = new Set<string>();\n for (const uniqueInfo of uniqueIndexesToApply) {\n const normalizedPath = (uniqueInfo.path || '').replace(/\\[\\]/g, '').trim();\n if (normalizedPath) {\n uniqueIndexPaths.add(normalizedPath);\n }\n }\n\n // Collect paths that already have a schema-level index registered by\n // applyRelationshipForeignKeyPersistence (which runs before this method).\n // Those are relationship-derived unique indexes for 1:1 FK fields. Adding\n // a plain index on the same path would trigger Mongoose's \"Duplicate schema\n // index\" warning because Mongoose sees two index definitions for the same\n // single-field key — the unique one from the relationship and the non-unique\n // one from the Zod decorator.\n const alreadyIndexedPaths = new Set<string>();\n for (const [indexSpec] of mongooseSchema.indexes()) {\n const keys = Object.keys(indexSpec as Record<string, unknown>);\n // Only pre-filter single-field indexes — compound indexes are composed of\n // multiple fields and we should not block plain indexing of the individual\n // participating fields.\n if (keys.length === 1) {\n alreadyIndexedPaths.add(keys[0]);\n }\n }\n\n // Apply regular indexes\n for (const rawPath of indexesToApply) {\n try {\n // Normalize array notation and trim whitespace\n const normalizedPath = (rawPath || '').replace(/\\[\\]/g, '').trim();\n\n // Skip invalid or empty paths\n if (!normalizedPath) continue;\n\n // Never attempt to index _id (MongoDB manages it). Also skip nested '.*._id'\n if (normalizedPath === '_id' || normalizedPath.endsWith('._id')) {\n continue;\n }\n\n // Skip paths that will have unique indexes (unique indexes already create an index)\n if (uniqueIndexPaths.has(normalizedPath)) {\n continue;\n }\n\n // Skip paths that already have a schema-level index from\n // applyRelationshipForeignKeyPersistence (relationship-derived unique\n // indexes for 1:1 FK fields). The unique index supersedes a plain one;\n // registering both causes a \"Duplicate schema index\" warning.\n if (alreadyIndexedPaths.has(normalizedPath)) {\n continue;\n }\n\n // De-duplicate\n if (appliedPaths.has(normalizedPath)) continue;\n appliedPaths.add(normalizedPath);\n\n // A plain index on the field, ENDED ON `_id` (#1915).\n //\n // Every paged read now orders by `<key>, _id` (`completeToTotalOrder`), so that rows tied on the key are\n // served exactly once across pages. A single-field `{ <key>: 1 }` index cannot serve that sort: measured on\n // MongoDB 8.2 over 50,000 rows, `sort({ createdAt: -1 })` walked the index and examined 20 documents for a\n // page, while `sort({ createdAt: -1, _id: -1 })` fell back to COLLSCAN + an in-memory SORT examining all\n // 50,000. `{ <key>: 1, _id: 1 }` restores the index walk in both directions and still serves every query the\n // single-field index did, since `<key>` is its prefix. It costs one ObjectId per index entry.\n //\n // PostgreSQL owes nothing equivalent: the planner turns a `<key>` btree into an Incremental Sort over the\n // tied groups (measured on the live Wonder Todos database), so no migration follows from this.\n //\n // Rejected: extending only `createdAt`. The default ordering is `createdAt`, but a declared `sortFields[0]`\n // (a status, an attempt count) is ordered the same way, and which fields an operation sorts by is not known\n // here. Every plain index is a potential sort index, so every one ends on `_id`.\n const indexSpec: Record<string, 1> = { [normalizedPath]: 1, [REPOSITORY_ROW_IDENTITY_FIELD]: 1 };\n this.logDebug(`[ZodToMongoose] Applying plain index on '${normalizedPath}' (ended on _id)`, { resourceType });\n mongooseSchema.index(indexSpec);\n } catch (error) {\n this.logger.warn(`[ZodToMongoose] Failed to apply index on path '${rawPath}': ${describeCaughtError(error)}`);\n }\n }\n\n // Apply unique indexes\n const appliedUniquePaths = new Set<string>();\n for (const uniqueInfo of uniqueIndexesToApply) {\n try {\n // Normalize array notation and trim whitespace\n const normalizedPath = (uniqueInfo.path || '').replace(/\\[\\]/g, '').trim();\n\n // Skip invalid or empty paths\n if (!normalizedPath) continue;\n\n // Never attempt to index _id (MongoDB manages it). Also skip nested '.*._id'\n if (normalizedPath === '_id' || normalizedPath.endsWith('._id')) {\n continue;\n }\n\n // De-duplicate within this invocation\n if (appliedUniquePaths.has(normalizedPath)) continue;\n\n // Skip paths that already have a schema-level index from\n // applyRelationshipForeignKeyPersistence. For single-field unique indexes,\n // re-registering the same key pattern triggers Mongoose's \"Duplicate schema\n // index\" warning. The relationship-derived index supersedes the Zod-derived one\n // because it may carry a partialFilterExpression for sparse semantics.\n if (alreadyIndexedPaths.has(normalizedPath)) {\n this.logDebug(`[ZodToMongoose] Skipped duplicate unique index on '${normalizedPath}' (already registered by relationship FK persistence)`, { resourceType });\n continue;\n }\n\n appliedUniquePaths.add(normalizedPath);\n\n const params = uniqueInfo.params || {};\n const scope = params.scope || 'global';\n const sparse = params.sparse !== false; // Default to true\n\n // Create index spec based on scope or compoundWith\n const indexSpec: Record<string, 1> = {};\n\n if (params.compoundWith) {\n // Resolve compoundWith field — handles polymorphic renames automatically\n let compoundField = params.compoundWith;\n if (!(mongooseSchema as any).paths?.[compoundField]) {\n const suffix = compoundField.charAt(0).toUpperCase() + compoundField.slice(1);\n const schemaFields = Object.keys((mongooseSchema as any).paths || {});\n const match = schemaFields.find(p => p.endsWith(suffix) && p !== normalizedPath);\n if (match) {\n compoundField = match;\n } else {\n this.logger.warn(`[ZodToMongoose] compoundWith field '${params.compoundWith}' not found in schema paths (suffix '${suffix}'). Available: ${schemaFields.join(', ')}`);\n }\n }\n indexSpec[compoundField] = 1;\n indexSpec[normalizedPath] = 1;\n } else if (scope === 'organization') {\n // Compound unique index: organizationId + field\n indexSpec['organizationId'] = 1;\n indexSpec[normalizedPath] = 1;\n } else if (scope === 'user') {\n // Compound unique index: createdByUserId + field\n indexSpec['createdByUserId'] = 1;\n indexSpec[normalizedPath] = 1;\n } else {\n // Global unique index\n indexSpec[normalizedPath] = 1;\n }\n\n // Apply unique index with options.\n //\n // G-BKEY: on a retention-governed resource, uniqueness covers only non-retained rows, so a\n // hidden retained row can neither block re-creation of its key nor reject the scrub's repeated\n // mask/null values (see buildRetentionPartialFilterExpression).\n //\n // ⚠️ `sparse` and `partialFilterExpression` are MUTUALLY EXCLUSIVE in MongoDB — the server\n // rejects the combination with `CannotCreateIndex`. Worse, the framework relies on Mongoose's\n // background `autoIndex` and never awaits `Model.init()`, so that rejection surfaces only as a\n // console error and the index is NEVER CREATED: uniqueness would be silently LOST rather than\n // scoped. So when the retention filter applies we express the sparse intent INSIDE the partial\n // filter (`$exists: true`), which is the MongoDB-legal equivalent and matches the shape already\n // used by the relationship-FK unique indexes below.\n // A COMPOUND index (scope organization/user, or `compoundWith`) cannot express \"skip when the\n // optional field is absent\" via `sparse: true`: MongoDB only sparse-EXCLUDES a document when it\n // is missing EVERY indexed key, and the scope key (`organizationId`/`createdByUserId`) or the\n // compound partner is always present — so every document missing the optional field indexes as\n // `(scope, null)` and the unique constraint collides on the FIRST such pair. The MongoDB-legal\n // equivalent is a partial filter requiring the field to exist. This is the same `$exists: true`\n // shape used on the retention path above and by the relationship-FK unique indexes below; a\n // SINGLE-key sparse index behaves correctly, so it keeps plain `sparse: true`.\n const isCompoundIndex = Object.keys(indexSpec).length > 1;\n const indexOptions: { unique: true; sparse?: boolean; partialFilterExpression?: Record<string, unknown> } = { unique: true };\n const retentionPartialFilter = this.buildRetentionPartialFilterExpression(resourceConfiguration);\n if (retentionPartialFilter) {\n indexOptions.partialFilterExpression = sparse\n ? { ...retentionPartialFilter, [normalizedPath]: { $exists: true } }\n : retentionPartialFilter;\n } else if (sparse && isCompoundIndex) {\n // Compound + sparse: express the sparse intent as a partial filter so absent-field rows are\n // genuinely excluded (a plain compound `sparse: true` would silently collide on `(scope, null)`).\n indexOptions.partialFilterExpression = { [normalizedPath]: { $exists: true } };\n } else if (sparse) {\n indexOptions.sparse = true;\n }\n\n mongooseSchema.index(indexSpec, indexOptions);\n } catch (error) {\n this.logger.warn(`[ZodToMongoose] Failed to apply unique index on path '${uniqueInfo.path}': ${describeCaughtError(error)}`);\n }\n }\n\n // Apply TTL indexes\n // MongoDB TTL indexes automatically delete documents after a specified time\n // TTL indexes can only be applied to Date fields\n const appliedTtlPaths = new Set<string>();\n for (const ttlInfo of ttlIndexesToApply) {\n try {\n // Normalize array notation and trim whitespace\n const normalizedPath = (ttlInfo.path || '').replace(/\\[\\]/g, '').trim();\n\n // Skip invalid or empty paths\n if (!normalizedPath) continue;\n\n // De-duplicate\n if (appliedTtlPaths.has(normalizedPath)) continue;\n appliedTtlPaths.add(normalizedPath);\n\n const params = ttlInfo.params;\n const expireAfterSeconds = params.expireAfterSeconds;\n\n // Create TTL index on the field\n const indexSpec: Record<string, 1> = {};\n indexSpec[normalizedPath] = 1;\n\n // Apply TTL index with expireAfterSeconds option\n mongooseSchema.index(indexSpec, { expireAfterSeconds });\n\n this.logDebug(`Applied TTL index on path '${normalizedPath}' with expireAfterSeconds: ${expireAfterSeconds}`);\n } catch (error) {\n this.logger.warn(`[ZodToMongoose] Failed to apply TTL index on path '${ttlInfo.path}': ${describeCaughtError(error)}`);\n }\n }\n }\n\n /**\n * Materialise a top-level `.businessKeySet([...])` decorator as a\n * Mongo compound `{ unique: true }` index on the resulting schema.\n *\n * **Why this exists** (Phase 3.2 review fix R2-4): the framework's\n * Zod-decorator surface declares two business-key shapes —\n * field-level `.isBusinessKey()` (single-field identity) and\n * object-level `.businessKeySet([...])` (composite identity, e.g.\n * `(seedKey, scopeKind, relatedResourceType, relatedId, seedVersion)`\n * for `DataSeedRun`). The single-field shape was already enforced\n * at the DB layer because `isBusinessKey` flows through the existing\n * `isUnique` path inside `convertZodTypeToMongooseDefinition`. The\n * composite shape was NOT — `.businessKeySet([...])` lived as Zod\n * metadata only, consumed by `business-key-resolver.shared.utils.ts`\n * (filter builder) and `findByBusinessKey` callers, but invisible\n * to MongoDB. That left every consumer doing find-then-create\n * race-prone (e.g. `DataSeedDispatcher.startRun` could insert two\n * ledger rows under concurrent boots).\n *\n * **Cardinality contract**:\n * - length === 0 / undefined → no-op (no decorator declared)\n * - length === 1 → no-op (the single field necessarily also carries\n * `.isBusinessKey()` per the decorator's validation pass, which\n * flows into `isUnique` and gets a single-field unique index\n * elsewhere — adding a \"compound\" index over one field would be\n * redundant)\n * - length ≥ 2 → compound `{ field1: 1, field2: 1, …, unique: true }`\n *\n * **Sparse handling is OFF BY DEFAULT**: a partial business key\n * (some fields null, others set) MUST collide with another partial\n * key bearing the same shape. For `DataSeedRun.CUSTOM` scope rows\n * with `relatedId === null`, sparse: true would let two rows with\n * `{seedKey: 'x', scopeKind: CUSTOM, relatedResourceType: null,\n * relatedId: null, seedVersion: 1}` co-exist — exactly the\n * collision F-4 widened the key to prevent. Mongo treats `null` as\n * a real value in non-sparse compound indexes, which is what the\n * business-key contract requires.\n *\n * A key whose member is optional IN THE DOMAIN opts out per member\n * with `skipRowsMissing`. `ORGANIZATION_UNITS`' \"code unique among\n * siblings\" is the motivating case: any number of siblings may carry\n * NO code, so rows without one must sit outside the constraint\n * entirely, while rows WITH one still collide. Only the listed\n * members are scoped — an unlisted optional member keeps the\n * null-collides default, which is what makes \"two roots may not\n * share a code\" work (an absent `parentUnitId` indexes as null, so\n * roots collide with each other, exactly as intended).\n *\n * The opt-out is expressed as `$exists: true` inside\n * `partialFilterExpression` rather than as `sparse: true` because\n * the two are MUTUALLY EXCLUSIVE in MongoDB and a retention-governed\n * resource already needs the partial filter. Combining them is\n * rejected by the server with `CannotCreateIndex`, and since the\n * framework never awaits `Model.init()`, that rejection would\n * surface only as a console error — the index would simply never be\n * created and uniqueness would be silently LOST.\n *\n * **Path validation**: every declared field name must exist in the\n * resolved Mongoose schema. The Zod-decorator validator already\n * enforces this at decoration time (`businessKeySet([...]) references\n * field(s) not present in the schema shape: …`), so a runtime\n * mismatch here would indicate a regression in the decorator\n * validation. We log a warning + skip rather than throw to avoid\n * blocking application boot on a non-critical index issue.\n */\n /**\n * Partial-index predicate that stops a UNIQUE index from permanently blocking re-creation of a\n * business key held by an impersonalized-and-retained row (gate **G-BKEY**).\n *\n * A RETAINED row is hidden from every normal read, so a find-then-create / upsert path does not see\n * it — but a plain unique index still does. The INSERT branch then collides with `E11000` on a row\n * the caller cannot see: a permanent re-creation lockout AND an existence oracle. Scoping the\n * uniqueness to non-retained rows resolves it at the DB layer while PRESERVING the retained row's\n * own business key (severing it instead would destroy the audit identity — an invoice must keep its\n * invoice number).\n *\n * Uniqueness among retained rows is deliberately dropped: they are immutable historical records, and\n * the scrub intentionally writes identical values (a shared mask constant, or null) across a batch —\n * which is exactly what a still-covering unique index would reject.\n *\n * Uses PLAIN EQUALITY, which every MongoDB version supporting partial indexes accepts. Expressing\n * \"any of several non-retained states\" would need `$in`, whose partial-index support is\n * version-dependent — so a future third `RetentionStatus` member fails LOUD here rather than\n * silently narrowing every unique index on every retention-governed resource.\n *\n * This is the INVERTED expression of the hide rule — it selects the rows the hide KEEPS — which is\n * the most dangerous kind of duplicate, because it drifts in the opposite direction and fails\n * silently (a lost uniqueness constraint, or an erasure that aborts on E11000). Both the status it\n * names and the field it names therefore come from the single retention authority, derived from the\n * same hidden-status constant the hide predicate negates; this method owns only the Mongo-specific\n * \"must be a plain equality\" constraint and the error it raises.\n */\n private buildRetentionPartialFilterExpression(\n resourceConfiguration?: RetentionGovernanceSignal,\n ): Record<string, unknown> | undefined {\n if (!isRetentionGovernedResource(resourceConfiguration)) {\n return undefined;\n }\n const visibleStatus = resolveSoleVisibleRetentionStatus();\n if (visibleStatus === undefined) {\n const visibleStatuses = getVisibleRetentionStatuses();\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.ZOD_CONVERTER_SCHEMA_CONVERSION_FAILED,\n context: {\n message:\n `RetentionStatus now has ${visibleStatuses.length} non-retained members, so the unique-index ` +\n `partial filter can no longer be a plain equality. Update buildRetentionPartialFilterExpression ` +\n `(and verify the target MongoDB supports the operator you choose) before adding the member.`,\n nonRetainedStatuses: visibleStatuses,\n },\n });\n }\n return buildRetentionVisibleRowsEqualityFragment(visibleStatus);\n }\n\n private applyBusinessKeyCompoundUniqueIndex(\n mongooseSchema: Schema,\n zodSchema: z.ZodTypeAny,\n resourceConfiguration?: RetentionGovernanceSignal,\n ): void {\n const businessKeyParams = getBusinessKeySetParams(zodSchema);\n const businessKeyFields = businessKeyParams?.fields;\n if (!businessKeyFields || businessKeyFields.length < 2) {\n return;\n }\n\n const schemaPaths = Object.keys((mongooseSchema as any).paths ?? {});\n const missing = businessKeyFields.filter((f) => !schemaPaths.includes(f));\n if (missing.length > 0) {\n this.logger.warn(\n `[ZodToMongoose] businessKeySet declared field(s) not present in resolved Mongoose schema — skipping compound unique index: ${missing.join(', ')}. Available paths: ${schemaPaths.join(', ')}`,\n );\n return;\n }\n\n const indexSpec: Record<string, 1> = {};\n for (const field of businessKeyFields) {\n indexSpec[field] = 1;\n }\n\n try {\n // Two independent reasons to narrow the index, which is why they are MERGED rather than\n // chosen between:\n // - G-BKEY: scope the uniqueness to non-retained rows so a retained row's business key\n // cannot permanently lock out re-creation (see buildRetentionPartialFilterExpression).\n // - `skipRowsMissing`: take rows that omit a domain-optional member out of the constraint.\n // A retention-governed resource declaring `skipRowsMissing` needs BOTH predicates; keeping\n // only one would either lose the re-creation escape hatch or re-collide the key-less rows.\n const retentionPartialFilter = this.buildRetentionPartialFilterExpression(resourceConfiguration);\n const presencePartialFilter = (businessKeyParams?.skipRowsMissing ?? []).reduce<Record<string, unknown>>(\n (accumulator, field) => {\n accumulator[field] = { $exists: true };\n return accumulator;\n },\n {},\n );\n const partialFilterExpression: Record<string, unknown> = { ...retentionPartialFilter, ...presencePartialFilter };\n const hasPartialFilter = Object.keys(partialFilterExpression).length > 0;\n\n mongooseSchema.index(indexSpec, {\n unique: true,\n ...(hasPartialFilter ? { partialFilterExpression } : {}),\n });\n this.logDebug(\n `Applied businessKeySet compound unique index: { ${businessKeyFields.join(', ')} }`,\n {\n retentionScoped: !!retentionPartialFilter,\n presenceScopedFields: businessKeyParams?.skipRowsMissing ?? [],\n },\n );\n } catch (error) {\n this.logger.warn(\n `[ZodToMongoose] Failed to apply businessKeySet compound unique index on { ${businessKeyFields.join(', ')} }: ${describeCaughtError(error)}`,\n );\n }\n }\n\n /**\n * Materialise relationship-derived FK persistence behavior.\n *\n * The shared relationship factory compiles authored topology into\n * `resolvedSemantics.persistence`. Storage adapters consume that runtime\n * contract instead of re-deriving from raw cardinality/nature. This keeps the\n * developer-facing declaration small while making FK materialization and\n * uniqueness a first-class framework consequence of relationship meaning.\n *\n * The contract's `holderResourceType` is the ONLY resource this FK may be\n * materialized/validated on. Positional `resourceType1`/`resourceType2`\n * checks are not a holder signal: declaration order is author-dependent\n * (parent-first vs child-first), and gating on `resourceType2` synthesizes\n * required FK columns onto the referenced TARGET of every child-first\n * relationship — e.g. the `users` model growing required\n * `postedByUserId`/`createdByUserId` paths from inbound\n * `(<holder>, USERS, MANY, ONE)` references, which fails validated saves of\n * every user (self-registration).\n *\n * Scope note: this method iterates the parent + self relationship buckets of\n * the resource under build. A child-first relationship lives in its HOLDER's\n * child bucket, so its authored FK column is governed by the Zod schema\n * conversion alone — relationship-level required/unique enforcement for the\n * child bucket is intentionally not active here (activating it is a separate\n * coherence decision across existing authored schemas).\n */\n private applyRelationshipForeignKeyPersistence(\n mongooseSchema: Schema,\n resourceConfiguration?: Partial<ResourceConfiguration<any, any, any>> & {\n resourceRelationships?: {\n parentRelationships?: ResourceRelationship[];\n selfRelationships?: ResourceRelationship[];\n } | ResourceRelationship[];\n },\n applyUniqueIndexes = true,\n ): void {\n if (!resourceConfiguration?.resourceIdentifier || !resourceConfiguration.resourceRelationships) {\n return;\n }\n\n const relationships = Array.isArray(resourceConfiguration.resourceRelationships)\n ? resourceConfiguration.resourceRelationships\n : [\n ...(resourceConfiguration.resourceRelationships.parentRelationships ?? []),\n ...(resourceConfiguration.resourceRelationships.selfRelationships ?? []),\n ];\n const indexedFields = new Set<string>();\n\n for (const relationship of relationships) {\n const foreignKeyPersistence = (relationship.resolvedSemantics as {\n persistence?: {\n foreignKey?: RelationshipPersistenceForeignKeyContract;\n };\n } | undefined)?.persistence?.foreignKey;\n if (\n !foreignKeyPersistence?.materializeField ||\n foreignKeyPersistence.holderResourceType !== resourceConfiguration.resourceIdentifier\n ) {\n continue;\n }\n\n const existingPath = mongooseSchema.path(foreignKeyPersistence.fieldIdentifier) as\n | { instance?: string; isRequired?: boolean; caster?: { instance?: string } }\n | undefined;\n // `wasMaterializedByFramework` distinguishes \"schema author explicitly\n // authored this field\" from \"framework synthesized this field from\n // relationship metadata.\" It matters for unique-index strategy below:\n // a materialized field's `required` constraint is enforceable ONLY by\n // Mongoose validators, which **raw MongoDB driver writes bypass**\n // (e.g. INIT-mode writers use `db.collection().insertOne()` directly).\n // For those fields we MUST use `partialFilterExpression` on the\n // unique index, otherwise an absent value materializes as `null` in\n // Mongo and the second insert collides with the first on the\n // unique index — exact bug pattern seen with the\n // `platformApplications.applicationId` synthesis (see Subsystem E in\n // `.claude/plans/platform-bootstrap-regression-fix.md`).\n const wasMaterializedByFramework = !existingPath;\n const expectedInstances = foreignKeyPersistence.isArray\n ? ['Array']\n : ['String', 'ObjectId'];\n if (existingPath) {\n if (!expectedInstances.includes(existingPath.instance ?? '')) {\n throw new Error(\n `[ZodToMongoose] Relationship FK '${foreignKeyPersistence.fieldIdentifier}' on resource '${String(resourceConfiguration.resourceIdentifier)}' resolves to ${expectedInstances.join(' or ')}, but the existing schema path is ${existingPath.instance ?? 'unknown'}. Align the authored relationship FK with the resource schema.`,\n );\n }\n if (\n foreignKeyPersistence.isArray &&\n !['String', 'ObjectId'].includes(existingPath.caster?.instance ?? '')\n ) {\n throw new Error(\n `[ZodToMongoose] Relationship FK '${foreignKeyPersistence.fieldIdentifier}' on resource '${String(resourceConfiguration.resourceIdentifier)}' resolves to an array FK, but the existing schema path has array element type ${existingPath.caster?.instance ?? 'unknown'}. Align the authored relationship FK with the resource schema.`,\n );\n }\n if (\n !foreignKeyPersistence.isArray &&\n Boolean(existingPath.isRequired) !== foreignKeyPersistence.required &&\n // M:N junction parent relationships use parentResourceRequirement=OPTIONAL for\n // URL-routing semantics (either parent path is valid). The Zod schema is the\n // authoritative source for junction FK requiredness; accessScopeStrategy=\n // OPTIONAL_CONTEXT already captures the routing concern independently.\n !relationship.jointResourceType\n ) {\n throw new Error(\n `[ZodToMongoose] Relationship FK '${foreignKeyPersistence.fieldIdentifier}' on resource '${String(resourceConfiguration.resourceIdentifier)}' resolves required=${foreignKeyPersistence.required}, but the existing schema path has required=${Boolean(existingPath.isRequired)}. Align parentResourceRequirement with the resource schema.`,\n );\n }\n this.logDebug('Relationship FK persistence path already present', {\n resourceType: resourceConfiguration.resourceIdentifier,\n parentResourceType: relationship.resourceType1,\n fieldIdentifier: foreignKeyPersistence.fieldIdentifier,\n instance: existingPath.instance,\n casterInstance: existingPath.caster?.instance,\n required: Boolean(existingPath.isRequired),\n unique: foreignKeyPersistence.unique,\n });\n } else {\n mongooseSchema.add({\n [foreignKeyPersistence.fieldIdentifier]: foreignKeyPersistence.isArray\n ? [{\n type: String,\n required: foreignKeyPersistence.required,\n }]\n : {\n type: String,\n required: foreignKeyPersistence.required,\n },\n });\n this.logDebug('Materialized relationship FK persistence path', {\n resourceType: resourceConfiguration.resourceIdentifier,\n parentResourceType: relationship.resourceType1,\n fieldIdentifier: foreignKeyPersistence.fieldIdentifier,\n isArray: foreignKeyPersistence.isArray,\n required: foreignKeyPersistence.required,\n unique: foreignKeyPersistence.unique,\n });\n }\n\n const persistedPath = mongooseSchema.path(foreignKeyPersistence.fieldIdentifier) as\n | { instance?: string; isRequired?: boolean; caster?: { instance?: string } }\n | undefined;\n const partialFilterBsonType = persistedPath?.instance === 'ObjectId'\n ? 'objectId'\n : 'string';\n\n if (\n !applyUniqueIndexes ||\n !foreignKeyPersistence.unique ||\n indexedFields.has(foreignKeyPersistence.fieldIdentifier)\n ) {\n this.logDebug('Skipped relationship FK unique index', {\n resourceType: resourceConfiguration.resourceIdentifier,\n parentResourceType: relationship.resourceType1,\n fieldIdentifier: foreignKeyPersistence.fieldIdentifier,\n applyUniqueIndexes,\n unique: foreignKeyPersistence.unique,\n duplicateIndexField: indexedFields.has(foreignKeyPersistence.fieldIdentifier),\n });\n continue;\n }\n indexedFields.add(foreignKeyPersistence.fieldIdentifier);\n\n const indexSpec: Record<string, 1> = { [foreignKeyPersistence.fieldIdentifier]: 1 };\n // Use a plain `unique` index ONLY when the field was explicitly\n // authored in the Zod schema with required: true. In that case the\n // schema author has guaranteed every persisted doc populates the\n // field (Mongoose validators enforce it for `.save()` / `Model.create()`).\n //\n // For ALL other cases — field materialized by framework, or\n // explicitly optional — use `partialFilterExpression` so absent\n // values don't collide as `null`. This is defensive even for\n // declared-required materialized fields, because raw-driver writes\n // (`db.collection().insertOne()`) bypass Mongoose validation.\n // G-BKEY: this is the THIRD unique-index emission path, and it is the one that MATTERS MOST for\n // retention — it also SUPPRESSES the Zod-derived unique index for the same path (see the\n // duplicate-path skip above), so if the retention predicate were only applied there, a\n // retention-governed resource whose unique key is a relationship FK (including the polymorphic\n // singleton scope FK) would keep a retention-BLIND unique index: the retained row stays in it,\n // permanently locking out re-creation and aborting the scrub batch with E11000.\n const retentionPartialFilter = this.buildRetentionPartialFilterExpression(resourceConfiguration);\n const usePlainUniqueIndex =\n foreignKeyPersistence.required && !wasMaterializedByFramework;\n const fkExistencePredicate = {\n [foreignKeyPersistence.fieldIdentifier]: { $exists: true, $type: partialFilterBsonType },\n };\n const indexOptions = usePlainUniqueIndex\n ? (retentionPartialFilter\n ? { unique: true, partialFilterExpression: retentionPartialFilter }\n : { unique: true })\n : {\n unique: true,\n partialFilterExpression: retentionPartialFilter\n ? { ...retentionPartialFilter, ...fkExistencePredicate }\n : fkExistencePredicate,\n };\n try {\n mongooseSchema.index(indexSpec, indexOptions);\n this.logDebug(\n `Applied relationship FK unique index: { ${foreignKeyPersistence.fieldIdentifier}: 1 }`,\n {\n resourceType: resourceConfiguration.resourceIdentifier,\n parentResourceType: relationship.resourceType1,\n required: foreignKeyPersistence.required,\n partialFilterBsonType: foreignKeyPersistence.required ? undefined : partialFilterBsonType,\n },\n );\n } catch (error) {\n this.logger.warn(\n `[ZodToMongoose] Failed to apply relationship FK unique index on path '${foreignKeyPersistence.fieldIdentifier}': ${describeCaughtError(error)}`,\n );\n }\n }\n }\n\n /**\n * Checks if a definition is an object definition (not a primitive type)\n * @param definition The definition to check\n * @returns True if it's an object definition\n */\n private isObjectDefinition(definition: any): boolean {\n return definition &&\n typeof definition === 'object' &&\n !Array.isArray(definition) &&\n !definition.type &&\n Object.keys(definition).length > 0;\n }\n\n /**\n * Generates a hash for a schema for caching purposes\n * @param schema The schema to hash\n * @returns A hash string\n */\n private getSchemaHash(schema: any): string {\n try {\n const schemaString = JSON.stringify(schema, (key, value) => {\n if (typeof value === 'function') return '[Function]';\n if (value instanceof RegExp) return value.toString();\n return value;\n });\n return schemaString.length.toString(36) + schemaString.slice(0, 10);\n } catch {\n return Math.random().toString(36).substr(2, 9);\n }\n }\n\n // =================================================================\n // DEBUG AND UTILITY METHODS\n // =================================================================\n\n /**\n * Debug display method to show schema structure for a specific model\n * @param model The Mongoose model to analyze\n * @param showDetails Whether to show detailed field information\n */\n debugDisplayModelSchema(model: Model<any>, showDetails: boolean = true): void {\n\n this.logDebug(`\\n🔍 === MODEL SCHEMA DEBUG: ${model.modelName} ===`);\n this.logDebug(`Collection: ${model.collection.name}`);\n this.logDebug(`Schema Fields: ${this.countSchemaFields(model.schema)}`);\n this.logDebug(`Indexes: ${model.schema.indexes().length}`);\n\n if (showDetails) {\n this.displaySchemaStructure(model.schema, model.modelName);\n\n const indexes = model.schema.indexes();\n if (indexes.length > 0) {\n this.logDebug('\\n🗂️ Indexes:');\n indexes.forEach((index, i) => {\n const [fields, options] = index;\n const fieldsStr = Object.entries(fields)\n .map(([field, direction]) => `${field}:${direction}`)\n .join(', ');\n const optionsStr = options && Object.keys(options).length > 0\n ? ` (${Object.entries(options).map(([k, v]) => `${k}:${v}`).join(', ')})`\n : '';\n this.logDebug(` ${i + 1}. {${fieldsStr}}${optionsStr}`);\n });\n }\n }\n this.logDebug('=================================\\n');\n }\n\n /**\n * Debug method to show simplified schema summary\n * @param models Array of models to analyze\n */\n debugShowModelsSummary(models: Model<any>[]): void {\n\n this.logDebug('\\n📋 === MODELS SUMMARY ===');\n\n if (models.length === 0) {\n this.logDebug('No models provided.');\n return;\n }\n\n for (const model of models) {\n const fieldCount = this.countSchemaFields(model.schema);\n const indexCount = model.schema.indexes().length;\n this.logDebug(`${model.modelName}: ${fieldCount} fields, ${indexCount} indexes`);\n }\n this.logDebug('========================\\n');\n }\n\n /**\n * Counts schema fields recursively\n * @param schema The Mongoose schema\n * @returns Total field count\n */\n private countSchemaFields(schema: Schema): number {\n if (!schema || !schema.paths) return 0;\n\n const paths = schema.paths;\n const pathNames = Object.keys(paths)\n .filter(path => !['__v', '_version_db_doc'].includes(path))\n .sort();\n\n return pathNames.length;\n }\n\n /**\n * Displays the structure of a Mongoose schema for debugging\n * @param schema The schema to display\n * @param schemaName Optional name for the schema\n * @param options Display options\n */\n private displaySchemaStructure(\n schema: Schema,\n schemaName: string = 'Schema',\n options: {\n showIndexes?: boolean;\n showValidators?: boolean;\n maxDepth?: number;\n } = {}\n ): void {\n const { showIndexes = true, showValidators = false, maxDepth = 3 } = options;\n\n this.logDebug(`\\n=== ${schemaName} Structure ===`);\n\n if (!schema || !schema.paths) {\n this.logDebug('No schema paths found');\n return;\n }\n\n const paths = schema.paths;\n const pathNames = Object.keys(paths)\n .filter(path => !['__v', '_version_db_doc'].includes(path))\n .sort();\n\n for (const pathName of pathNames) {\n const pathInfo = this.getPathTypeInfo(paths[pathName]);\n\n // Start with base type\n let pathDisplay = `${pathName}: `;\n\n if (pathInfo.isArray) {\n // For arrays, show [ElementType] format\n const elementType = pathInfo.arrayElementType || 'Mixed';\n pathDisplay += `[${elementType}]`;\n } else {\n pathDisplay += pathInfo.type;\n }\n\n // Collect all additional info in parentheses\n const additionalInfo: string[] = [];\n\n // Required vs Optional\n if (pathInfo.isRequired) {\n additionalInfo.push('required');\n } else {\n additionalInfo.push('optional');\n }\n\n // Enum values\n if (pathInfo.enumValues.length > 0) {\n const enumList = pathInfo.enumValues.join(', ');\n additionalInfo.push(`enum: [${enumList}]`);\n }\n\n // Default value\n if (pathInfo.hasDefault) {\n let defaultStr = '';\n if (Array.isArray(pathInfo.defaultValue)) {\n defaultStr = `[${pathInfo.defaultValue.join(', ')}]`;\n } else if (typeof pathInfo.defaultValue === 'object' && pathInfo.defaultValue !== null) {\n defaultStr = JSON.stringify(pathInfo.defaultValue);\n } else if (typeof pathInfo.defaultValue === 'string') {\n defaultStr = `\"${pathInfo.defaultValue}\"`;\n } else {\n defaultStr = String(pathInfo.defaultValue);\n }\n additionalInfo.push(`default: ${defaultStr}`);\n }\n\n // Validators\n if (showValidators && pathInfo.validators.length > 0) {\n additionalInfo.push(`validators: [${pathInfo.validators.join(', ')}]`);\n }\n\n // Add all additional info in parentheses\n if (additionalInfo.length > 0) {\n pathDisplay += ` (${additionalInfo.join(', ')})`;\n }\n\n this.logDebug(` ${pathDisplay}`);\n\n // Show nested structure for objects\n if (pathInfo.isNested && maxDepth > 0) {\n this.displayNestedPathStructure(paths[pathName], 2, maxDepth - 1, showValidators);\n }\n }\n\n if (showIndexes) {\n const indexes = schema.indexes();\n if (indexes.length > 0) {\n this.logDebug('\\n Indexes:');\n indexes.forEach((index, i) => {\n this.logDebug(` ${i + 1}. ${JSON.stringify(index[0])} ${JSON.stringify(index[1] || {})}`);\n });\n }\n }\n\n this.logDebug(`\\nTotal paths: ${pathNames.length}`);\n }\n\n /**\n * Displays nested path structure recursively with comprehensive details\n * @param path The path to display\n * @param indent Current indentation level\n * @param maxDepth Maximum depth to display\n * @param showValidators Whether to show validator information\n */\n private displayNestedPathStructure(path: any, indent: number = 0, maxDepth: number = 2, showValidators: boolean = false): void {\n if (maxDepth <= 0) return;\n\n const spaces = ' '.repeat(indent);\n\n if (path.schema && path.schema.paths) {\n const nestedPaths = Object.keys(path.schema.paths)\n .filter(nestedPath => !['__v', '_version_db_doc'].includes(nestedPath))\n .sort();\n\n for (const nestedPath of nestedPaths) {\n const nestedPathInfo = this.getPathTypeInfo(path.schema.paths[nestedPath]);\n\n // Build display string for nested field\n let nestedDisplay = `${nestedPath}: `;\n\n if (nestedPathInfo.isArray) {\n const elementType = nestedPathInfo.arrayElementType || 'Mixed';\n nestedDisplay += `[${elementType}]`;\n } else {\n nestedDisplay += nestedPathInfo.type;\n }\n\n // Collect additional info for nested fields\n const nestedAdditionalInfo: string[] = [];\n\n // Required vs Optional\n if (nestedPathInfo.isRequired) {\n nestedAdditionalInfo.push('required');\n } else {\n nestedAdditionalInfo.push('optional');\n }\n\n // Enum values\n if (nestedPathInfo.enumValues.length > 0) {\n const enumList = nestedPathInfo.enumValues.join(', ');\n nestedAdditionalInfo.push(`enum: [${enumList}]`);\n }\n\n // Default value\n if (nestedPathInfo.hasDefault) {\n let defaultStr = '';\n if (Array.isArray(nestedPathInfo.defaultValue)) {\n defaultStr = `[${nestedPathInfo.defaultValue.join(', ')}]`;\n } else if (typeof nestedPathInfo.defaultValue === 'object' && nestedPathInfo.defaultValue !== null) {\n defaultStr = JSON.stringify(nestedPathInfo.defaultValue);\n } else if (typeof nestedPathInfo.defaultValue === 'string') {\n defaultStr = `\"${nestedPathInfo.defaultValue}\"`;\n } else {\n defaultStr = String(nestedPathInfo.defaultValue);\n }\n nestedAdditionalInfo.push(`default: ${defaultStr}`);\n }\n\n // Validators\n if (showValidators && nestedPathInfo.validators.length > 0) {\n nestedAdditionalInfo.push(`validators: [${nestedPathInfo.validators.join(', ')}]`);\n }\n\n // Add additional info in parentheses\n if (nestedAdditionalInfo.length > 0) {\n nestedDisplay += ` (${nestedAdditionalInfo.join(', ')})`;\n }\n\n this.logDebug(`${spaces}${nestedDisplay}`);\n\n if (nestedPathInfo.isNested) {\n this.displayNestedPathStructure(path.schema.paths[nestedPath], indent + 1, maxDepth - 1, showValidators);\n }\n }\n }\n }\n\n /**\n * Gets comprehensive type information for a schema path\n * @param schemaType The schema type to analyze\n * @returns Object containing detailed type information\n */\n private getPathTypeInfo(schemaType: any): {\n type: string;\n isRequired: boolean;\n hasDefault: boolean;\n defaultValue: any;\n isArray: boolean;\n arrayElementType: string;\n isNested: boolean;\n validators: string[];\n enumValues: string[];\n isOptional: boolean;\n } {\n let type = 'Mixed';\n let isRequired = false;\n let hasDefault = false;\n let defaultValue: any = undefined;\n let isArray = false;\n let arrayElementType = '';\n let isNested = false;\n const validators: string[] = [];\n const enumValues: string[] = [];\n\n if (schemaType) {\n // Get type name\n if (schemaType.instance) {\n type = schemaType.instance;\n } else if (schemaType.constructor && schemaType.constructor.name) {\n type = schemaType.constructor.name;\n }\n\n // Check if required\n if (schemaType.isRequired) {\n isRequired = true;\n }\n\n // Check if has default and get the actual value\n if (schemaType.defaultValue !== undefined) {\n hasDefault = true;\n defaultValue = schemaType.defaultValue;\n\n // Handle function defaults\n if (typeof defaultValue === 'function') {\n try {\n const result = defaultValue();\n defaultValue = result;\n } catch (e) {\n defaultValue = '[Function]';\n }\n }\n }\n\n // Check if array and get element type\n if (schemaType.constructor && schemaType.constructor.name === 'Array') {\n isArray = true;\n\n // Try to get array element type\n if (schemaType.caster) {\n if (schemaType.caster.instance) {\n arrayElementType = schemaType.caster.instance;\n } else if (schemaType.caster.constructor && schemaType.caster.constructor.name) {\n arrayElementType = schemaType.caster.constructor.name;\n }\n\n // Check for enum values in array elements\n if (schemaType.caster.enumValues && Array.isArray(schemaType.caster.enumValues)) {\n enumValues.push(...schemaType.caster.enumValues);\n }\n }\n }\n\n // Check if nested (has embedded schema)\n if (schemaType.schema) {\n isNested = true;\n type = 'Object';\n }\n\n // Check for enum values\n if (schemaType.enumValues && Array.isArray(schemaType.enumValues)) {\n enumValues.push(...schemaType.enumValues);\n }\n\n // Collect validators\n if (schemaType.validators && Array.isArray(schemaType.validators)) {\n validators.push(...schemaType.validators.map((v: any) => v.type || 'custom'));\n }\n }\n\n const isOptional = !isRequired;\n\n return {\n type,\n isRequired,\n hasDefault,\n defaultValue,\n isArray,\n arrayElementType,\n isNested,\n validators,\n enumValues,\n isOptional\n };\n }\n}\n"]}