{"version":3,"sources":["../../../../../src/orm/adapters/mongodb/index.ts","../../../../../src/orm/adapters/mongodb/query.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport { MongoClient, type ClientSession, type MongoClientOptions, type OptionalUnlessRequiredId } from 'mongodb'\nimport { v, type PipeOutput } from 'valleyed'\n\nimport { compileMongoAggregate, compileMongoFilter, compileMongoOps, compileMongoQuery, compileMongoUpdate } from './query'\nimport { EquippedError } from '../../../errors'\nimport { configurable } from '../../../utilities/configurable'\nimport type { FilterGroup } from '../../filter'\nimport type { DiscoveredSchema } from '../../migrations/introspection-types'\nimport type { AddIndexChange, DropIndexChange } from '../../migrations/types'\nimport { OrmAdapter, type AggregateSpec } from '../../orm-adapter'\nimport type { IterationQueryOptions, QueryOptions } from '../../query-options'\nimport type { AnySchema } from '../../schema'\nimport type { AnyUpdateOp } from '../../updates'\n\nconst mongoSchemaConfigPipe = () => v.object({ db: v.string(), col: v.string() })\nexport type MongoDbRepoConfig = PipeOutput<ReturnType<typeof mongoSchemaConfigPipe>>\n\nconst mongoConnectionPipe = () =>\n\tv.object({\n\t\turi: v.string(),\n\t})\n\nconst MIGRATION_TRACKER_COLLECTION = 'equipped_migrations'\n\nexport class MongoDbAdapter extends configurable(mongoConnectionPipe, OrmAdapter) {\n\treadonly schemaConfigPipe = mongoSchemaConfigPipe()\n\n\treadonly queryableOps = ['eq', 'ne', 'gt', 'gte', 'lt', 'lte', 'in', 'notIn', 'like', 'exists', 'notExists', 'contains', 'notContains'] as const\n\treadonly updateOps = ['set', 'inc', 'mul', 'min', 'max', 'unset', 'push', 'pull', 'patch'] as const\n\treadonly aggregateOps = ['count', 'countDistinct', 'sum', 'avg', 'min', 'max'] as const\n\treadonly supportedFieldTypes = ['string', 'number', 'boolean', 'null', 'object', 'array', 'date'] as const\n\n\treadonly client: MongoClient\n\treadonly #sessionStore = new AsyncLocalStorage<ClientSession | undefined>()\n\n\tprotected constructor(config: typeof MongoDbAdapter.Config, options?: MongoClientOptions) {\n\t\tsuper(config)\n\t\tthis.client = new MongoClient(config.uri, {\n\t\t\t...options,\n\t\t\tignoreUndefined: true,\n\t\t})\n\t}\n\n\t#getCollection(schemaCfg: MongoDbRepoConfig) {\n\t\treturn this.client.db(schemaCfg.db).collection(schemaCfg.col)\n\t}\n\n\tasync connect() {\n\t\ttry {\n\t\t\tawait this.client.connect()\n\t\t} catch (error) {\n\t\t\tthrow new EquippedError('Failed to connect MongoDB client', { adapter: 'mongodb' }, error)\n\t\t}\n\t}\n\n\tasync disconnect() {\n\t\ttry {\n\t\t\tawait this.client.close()\n\t\t} catch (error) {\n\t\t\tthrow new EquippedError('Failed to disconnect MongoDB client', { adapter: 'mongodb' }, error)\n\t\t}\n\t}\n\n\tasync findByPk(schema: AnySchema, config: unknown, pk: unknown) {\n\t\tconst schemaCfg = config as MongoDbRepoConfig\n\t\ttry {\n\t\t\tconst pkName = schema.pkField.name\n\t\t\tconst collection = this.#getCollection(schemaCfg)\n\t\t\tconst doc = await collection.findOne(\n\t\t\t\t{ [pkName]: pk },\n\t\t\t\t{ session: this.#sessionStore.getStore() },\n\t\t\t)\n\t\t\treturn doc as Record<string, unknown> | null\n\t\t} catch (error) {\n\t\t\tthrow new EquippedError(\n\t\t\t\t'MongoDB findByPk failed',\n\t\t\t\t{ adapter: 'mongodb', operation: 'findByPk', collection: schemaCfg.col },\n\t\t\t\terror,\n\t\t\t)\n\t\t}\n\t}\n\n\tasync createMany(_schema: AnySchema, config: unknown, data: Record<string, unknown>[]) {\n\t\tconst schemaCfg = config as MongoDbRepoConfig\n\t\ttry {\n\t\t\tconst collection = this.#getCollection(schemaCfg)\n\t\t\tconst docs = data.map((d) => d as OptionalUnlessRequiredId<any>)\n\t\t\tawait collection.insertMany(docs, { session: this.#sessionStore.getStore() })\n\t\t\treturn data\n\t\t} catch (error) {\n\t\t\tthrow new EquippedError(\n\t\t\t\t'MongoDB createMany failed',\n\t\t\t\t{ adapter: 'mongodb', operation: 'createMany', collection: schemaCfg.col },\n\t\t\t\terror,\n\t\t\t)\n\t\t}\n\t}\n\n\tasync updateByPk(schema: AnySchema, config: unknown, pk: unknown, ops: AnyUpdateOp[]) {\n\t\tconst schemaCfg = config as MongoDbRepoConfig\n\t\ttry {\n\t\t\tconst pkName = schema.pkField.name\n\t\t\tconst collection = this.#getCollection(schemaCfg)\n\t\t\tconst update = compileMongoOps(ops)\n\t\t\tif (Object.keys(update).length === 0) {\n\t\t\t\treturn await collection.findOne({ [pkName]: pk }, { session: this.#sessionStore.getStore() }) as Record<string, unknown> | null\n\t\t\t}\n\t\t\treturn await collection.findOneAndUpdate(\n\t\t\t\t{ [pkName]: pk },\n\t\t\t\tupdate,\n\t\t\t\t{ returnDocument: 'after', session: this.#sessionStore.getStore() },\n\t\t\t) as Record<string, unknown> | null\n\t\t} catch (error) {\n\t\t\tthrow new EquippedError(\n\t\t\t\t'MongoDB updateByPk failed',\n\t\t\t\t{ adapter: 'mongodb', operation: 'updateByPk', collection: schemaCfg.col },\n\t\t\t\terror,\n\t\t\t)\n\t\t}\n\t}\n\n\tasync deleteByPk(schema: AnySchema, config: unknown, pk: unknown) {\n\t\tconst schemaCfg = config as MongoDbRepoConfig\n\t\ttry {\n\t\t\tconst pkName = schema.pkField.name\n\t\t\tconst collection = this.#getCollection(schemaCfg)\n\t\t\treturn await collection.findOneAndDelete(\n\t\t\t\t{ [pkName]: pk },\n\t\t\t\t{ session: this.#sessionStore.getStore() },\n\t\t\t) as Record<string, unknown> | null\n\t\t} catch (error) {\n\t\t\tthrow new EquippedError(\n\t\t\t\t'MongoDB deleteByPk failed',\n\t\t\t\t{ adapter: 'mongodb', operation: 'deleteByPk', collection: schemaCfg.col },\n\t\t\t\terror,\n\t\t\t)\n\t\t}\n\t}\n\n\tasync raw(_schema: AnySchema, config: unknown, pipeline: Record<string, unknown>[]) {\n\t\tconst schemaCfg = config as MongoDbRepoConfig\n\t\ttry {\n\t\t\tconst collection = this.#getCollection(schemaCfg)\n\t\t\tconst result = await collection.aggregate(pipeline, { session: this.#sessionStore.getStore() }).toArray()\n\t\t\treturn result\n\t\t} catch (error) {\n\t\t\tif (error instanceof EquippedError) throw error\n\t\t\tthrow new EquippedError(\n\t\t\t\t'MongoDB raw failed',\n\t\t\t\t{ adapter: 'mongodb', operation: 'raw', collection: schemaCfg.col },\n\t\t\t\terror,\n\t\t\t)\n\t\t}\n\t}\n\n\tasync aggregate(schema: AnySchema, config: unknown, spec: AggregateSpec): Promise<Array<Record<string, unknown>>> {\n\t\tconst schemaCfg = config as MongoDbRepoConfig\n\t\ttry {\n\t\t\tconst pk = schema.pkField.name\n\t\t\tconst collection = this.#getCollection(schemaCfg)\n\t\t\tconst pipeline = compileMongoAggregate(spec, pk)\n\t\t\tconst result = await collection.aggregate(pipeline, { session: this.#sessionStore.getStore() }).toArray()\n\t\t\treturn result as Array<Record<string, unknown>>\n\t\t} catch (error) {\n\t\t\tif (error instanceof EquippedError) throw error\n\t\t\tthrow new EquippedError(\n\t\t\t\t'MongoDB aggregate failed',\n\t\t\t\t{ adapter: 'mongodb', operation: 'aggregate', collection: schemaCfg.col },\n\t\t\t\terror,\n\t\t\t)\n\t\t}\n\t}\n\n\tasync findMany(schema: AnySchema, config: unknown, filter: FilterGroup, options?: QueryOptions) {\n\t\tconst schemaCfg = config as MongoDbRepoConfig\n\t\ttry {\n\t\t\tconst pk = schema.pkField.name\n\t\t\tconst { filter: mongoFilter, sort, limit, skip, projection } = compileMongoQuery(filter, options, pk)\n\t\t\tconst collection = this.#getCollection(schemaCfg)\n\n\t\t\tlet cursor = collection.find(mongoFilter, {\n\t\t\t\tsession: this.#sessionStore.getStore(),\n\t\t\t\tprojection,\n\t\t\t})\n\t\t\tif (sort) cursor = cursor.sort(sort)\n\t\t\tif (limit) cursor = cursor.limit(limit)\n\t\t\tif (skip) cursor = cursor.skip(skip)\n\n\t\t\treturn await cursor.toArray()\n\t\t} catch (error) {\n\t\t\tthrow new EquippedError(\n\t\t\t\t'MongoDB findMany failed',\n\t\t\t\t{ adapter: 'mongodb', operation: 'findMany', collection: schemaCfg.col },\n\t\t\t\terror,\n\t\t\t)\n\t\t}\n\t}\n\n\tasync count(schema: AnySchema, config: unknown, filter: FilterGroup) {\n\t\tconst schemaCfg = config as MongoDbRepoConfig\n\t\ttry {\n\t\t\tconst pk = schema.pkField.name\n\t\t\tconst collection = this.#getCollection(schemaCfg)\n\t\t\treturn await collection.countDocuments(compileMongoFilter(filter, pk), { session: this.#sessionStore.getStore() })\n\t\t} catch (error) {\n\t\t\tthrow new EquippedError(\n\t\t\t\t'MongoDB count failed',\n\t\t\t\t{ adapter: 'mongodb', operation: 'count', collection: schemaCfg.col },\n\t\t\t\terror,\n\t\t\t)\n\t\t}\n\t}\n\n\tasync *iterateMany(schema: AnySchema, config: unknown, filter: FilterGroup, options?: IterationQueryOptions) {\n\t\tconst schemaCfg = config as MongoDbRepoConfig\n\t\tlet cursor: any\n\t\ttry {\n\t\t\tconst pk = schema.pkField.name\n\t\t\tconst { filter: mongoFilter, sort, limit, skip, projection } = compileMongoQuery(filter, options, pk)\n\t\t\tconst collection = this.#getCollection(schemaCfg)\n\n\t\t\tcursor = collection.find(mongoFilter, {\n\t\t\t\tsession: this.#sessionStore.getStore(),\n\t\t\t\tprojection,\n\t\t\t})\n\t\t\tif (sort) cursor = cursor.sort(sort)\n\t\t\tif (limit) cursor = cursor.limit(limit)\n\t\t\tif (skip) cursor = cursor.skip(skip)\n\t\t\tif (options?.batchSize !== undefined) cursor = cursor.batchSize(options.batchSize)\n\n\t\t\tfor await (const row of cursor) {\n\t\t\t\tyield row as Record<string, unknown>\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrow new EquippedError(\n\t\t\t\t'MongoDB iterateMany failed',\n\t\t\t\t{ adapter: 'mongodb', operation: 'iterateMany', collection: schemaCfg.col },\n\t\t\t\terror,\n\t\t\t)\n\t\t} finally {\n\t\t\tawait cursor?.close()\n\t\t}\n\t}\n\n\tasync updateMany(schema: AnySchema, config: unknown, filter: FilterGroup, data: Record<string, unknown>) {\n\t\tconst schemaCfg = config as MongoDbRepoConfig\n\t\ttry {\n\t\t\tconst pk = schema.pkField.name\n\t\t\tconst collection = this.#getCollection(schemaCfg)\n\t\t\tconst session = this.#sessionStore.getStore()\n\t\t\tconst mongoFilter = compileMongoFilter(filter, pk)\n\n\t\t\tconst matchingDocs = await collection.find(mongoFilter, { session, projection: { [pk]: 1 } }).toArray()\n\t\t\tconst ids = matchingDocs.map((d) => d[pk])\n\t\t\tconst idFilter = { [pk]: { $in: ids } }\n\n\t\t\tconst update = compileMongoUpdate(data)\n\t\t\tif (Object.keys(update).length > 0) {\n\t\t\t\tawait collection.updateMany(idFilter, update, { session })\n\t\t\t}\n\n\t\t\treturn await collection.find({ [pk]: { $in: ids } }, { session }).toArray()\n\t\t} catch (error) {\n\t\t\tthrow new EquippedError(\n\t\t\t\t'MongoDB updateMany failed',\n\t\t\t\t{ adapter: 'mongodb', operation: 'updateMany', collection: schemaCfg.col },\n\t\t\t\terror,\n\t\t\t)\n\t\t}\n\t}\n\n\tasync deleteMany(schema: AnySchema, config: unknown, filter: FilterGroup) {\n\t\tconst schemaCfg = config as MongoDbRepoConfig\n\t\ttry {\n\t\t\tconst pk = schema.pkField.name\n\t\t\tconst collection = this.#getCollection(schemaCfg)\n\t\t\tconst session = this.#sessionStore.getStore()\n\t\t\tconst mongoFilter = compileMongoFilter(filter, pk)\n\n\t\t\tconst docs = await collection.find(mongoFilter, { session }).toArray()\n\t\t\tif (docs.length > 0) {\n\t\t\t\tawait collection.deleteMany(mongoFilter, { session })\n\t\t\t}\n\t\t\treturn docs\n\t\t} catch (error) {\n\t\t\tthrow new EquippedError(\n\t\t\t\t'MongoDB deleteMany failed',\n\t\t\t\t{ adapter: 'mongodb', operation: 'deleteMany', collection: schemaCfg.col },\n\t\t\t\terror,\n\t\t\t)\n\t\t}\n\t}\n\n\tasync upsertOne(schema: AnySchema, config: unknown, filter: FilterGroup, create: Record<string, unknown>, ops: AnyUpdateOp[]) {\n\t\tconst schemaCfg = config as MongoDbRepoConfig\n\t\ttry {\n\t\t\tconst pk = schema.pkField.name\n\t\t\tconst collection = this.#getCollection(schemaCfg)\n\t\t\tconst mongoFilter = compileMongoFilter(filter, pk)\n\n\t\t\tconst updateDoc = compileMongoOps(ops)\n\t\t\tconst doc = await collection.findOneAndUpdate(\n\t\t\t\tmongoFilter,\n\t\t\t\t{\n\t\t\t\t\t...updateDoc,\n\t\t\t\t\t$setOnInsert: create,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\treturnDocument: 'after',\n\t\t\t\t\tsession: this.#sessionStore.getStore(),\n\t\t\t\t\tupsert: true,\n\t\t\t\t},\n\t\t\t)\n\n\t\t\treturn doc as Record<string, unknown>\n\t\t} catch (error) {\n\t\t\tthrow new EquippedError(\n\t\t\t\t'MongoDB upsertOne failed',\n\t\t\t\t{ adapter: 'mongodb', operation: 'upsertOne', collection: schemaCfg.col },\n\t\t\t\terror,\n\t\t\t)\n\t\t}\n\t}\n\n\tasync session<T>(fn: () => Promise<T>): Promise<T> {\n\t\tif (this.#sessionStore.getStore()) return fn()\n\t\ttry {\n\t\t\tconst session = await this.client.startSession()\n\t\t\ttry {\n\t\t\t\treturn await session.withTransaction(async () => this.#sessionStore.run(session, fn))\n\t\t\t} finally {\n\t\t\t\tawait session.endSession()\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (error instanceof EquippedError) throw error\n\t\t\tthrow new EquippedError('MongoDB session failed', { adapter: 'mongodb', operation: 'session' }, error)\n\t\t}\n\t}\n\n\tasync loadMigrations(): Promise<{ id: string; appliedAt: number }[]> {\n\t\tconst db = this.client.db()\n\t\tconst docs = await db.collection(MIGRATION_TRACKER_COLLECTION).find({}).toArray()\n\t\treturn docs.map((d) => ({ id: String(d._id), appliedAt: d.appliedAt as number }))\n\t}\n\n\tasync recordMigration(id: string, appliedAt: number): Promise<void> {\n\t\tconst db = this.client.db()\n\t\tawait db.collection(MIGRATION_TRACKER_COLLECTION).insertOne({ _id: id as any, appliedAt })\n\t}\n\n\tasync applyAddIndex(change: AddIndexChange): Promise<void> {\n\t\tconst db = this.client.db()\n\t\tconst fields: Record<string, 1> = {}\n\t\tfor (const f of change.on) {\n\t\t\tfields[f] = 1\n\t\t}\n\t\tconst name = change.name ?? `${change.table}_${change.on.join('_')}_idx`\n\t\tawait db.collection(change.table).createIndex(fields, { unique: change.unique ?? false, name })\n\t}\n\n\tasync applyDropIndex(change: DropIndexChange): Promise<void> {\n\t\tconst db = this.client.db()\n\t\tconst collections = await db.listCollections().toArray()\n\t\tfor (const col of collections) {\n\t\t\tconst indexes = await db.collection(col.name).listIndexes().toArray()\n\t\t\tif (indexes.some((idx) => idx.name === change.name)) {\n\t\t\t\tawait db.collection(col.name).dropIndex(change.name)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tasync introspect(): Promise<DiscoveredSchema[]> {\n\t\tconst db = this.client.db()\n\t\tconst collections = await db.listCollections().toArray()\n\t\tconst schemas: DiscoveredSchema[] = []\n\t\tfor (const col of collections) {\n\t\t\tif (col.name === MIGRATION_TRACKER_COLLECTION) continue\n\t\t\tconst rawIndexes = await db.collection(col.name).listIndexes().toArray()\n\t\t\tconst indexes = rawIndexes\n\t\t\t\t.filter((idx) => idx.name !== '_id_')\n\t\t\t\t.map((idx) => ({\n\t\t\t\t\tname: idx.name as string,\n\t\t\t\t\ton: Object.keys(idx.key as Record<string, unknown>) as ReadonlyArray<string>,\n\t\t\t\t\tunique: !!(idx.unique),\n\t\t\t\t}))\n\t\t\tschemas.push({\n\t\t\t\tname: col.name,\n\t\t\t\tpk: undefined,\n\t\t\t\tfields: [],\n\t\t\t\tindexes,\n\t\t\t\tforeignKeys: [],\n\t\t\t})\n\t\t}\n\t\treturn schemas\n\t}\n}\n\nif (import.meta.vitest) {\n\tconst { describe, test, expect, expectTypeOf } = import.meta.vitest\n\n\tdescribe('MongoDbAdapter: class-via-configurable shape', () => {\n\t\ttest('MongoDbAdapter.create validates connection config via pipe', () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\texpect(adapter).toBeInstanceOf(MongoDbAdapter)\n\t\t\texpect(adapter.client).toBeInstanceOf(MongoClient)\n\t\t})\n\n\t\ttest('MongoDbAdapter.create rejects invalid config', () => {\n\t\t\texpect(() => MongoDbAdapter.create({} as any)).toThrow()\n\t\t\texpect(() => MongoDbAdapter.create({ uri: 123 } as any)).toThrow()\n\t\t})\n\n\t\ttest('readonly schemaConfigPipe declared with { db, col } shape', () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\texpect(adapter.schemaConfigPipe).toBeDefined()\n\t\t})\n\n\t\ttest('capability declarations use as const', () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\n\t\t\texpect(adapter.supportedFieldTypes).toEqual([\n\t\t\t\t'string', 'number', 'boolean', 'null', 'object', 'array', 'date',\n\t\t\t])\n\t\t\texpect(adapter.queryableOps).toEqual([\n\t\t\t\t'eq', 'ne', 'gt', 'gte', 'lt', 'lte', 'in', 'notIn', 'like', 'exists', 'notExists', 'contains', 'notContains',\n\t\t\t])\n\t\t\texpect(adapter.updateOps).toEqual([\n\t\t\t\t'set', 'inc', 'mul', 'min', 'max', 'unset', 'push', 'pull', 'patch',\n\t\t\t])\n\t\t\texpect(adapter.aggregateOps).toEqual([\n\t\t\t\t'count', 'countDistinct', 'sum', 'avg', 'min', 'max',\n\t\t\t])\n\t\t})\n\n\t\ttest('underlying MongoClient exposed as readonly instance field', () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\texpect(adapter.client).toBeInstanceOf(MongoClient)\n\t\t})\n\n\t\ttest('adapter.use returns OrmUse-shaped object', async () => {\n\t\t\tconst { Schema } = await import('../../schema')\n\t\t\tconst { v } = await import('valleyed')\n\t\t\tconst schema = Schema.from('test').pk('id', v.string(), () => 'x').build()\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\tconst use = adapter.use(schema, { db: 'testdb', col: 'testcol' })\n\n\t\t\texpect(use.findMany).toBeTypeOf('function')\n\t\t\texpect(use.iterateMany).toBeTypeOf('function')\n\t\t\texpect(use.findOne).toBeTypeOf('function')\n\t\t\texpect(use.count).toBeTypeOf('function')\n\t\t\texpect(use.createOne).toBeTypeOf('function')\n\t\t\texpect(use.createMany).toBeTypeOf('function')\n\t\t\texpect(use.updateMany).toBeTypeOf('function')\n\t\t\texpect(use.updateOne).toBeTypeOf('function')\n\t\t\texpect(use.upsertOne).toBeTypeOf('function')\n\t\t\texpect(use.deleteOne).toBeTypeOf('function')\n\t\t\texpect(use.deleteMany).toBeTypeOf('function')\n\t\t\texpect(use.raw).toBeTypeOf('function')\n\t\t})\n\n\t\ttest('type-level: adapter declares all 9 canonical update ops', () => {\n\t\t\tconst _adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\ttype Ops = typeof _adapter.updateOps\n\t\t\texpectTypeOf<Ops>().toEqualTypeOf<\n\t\t\t\treadonly ['set', 'inc', 'mul', 'min', 'max', 'unset', 'push', 'pull', 'patch']\n\t\t\t>()\n\t\t})\n\n\t\ttest('type-level: adapter declares all 7 field types', () => {\n\t\t\tconst _adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\ttype Types = typeof _adapter.supportedFieldTypes\n\t\t\texpectTypeOf<Types>().toEqualTypeOf<\n\t\t\t\treadonly ['string', 'number', 'boolean', 'null', 'object', 'array', 'date']\n\t\t\t>()\n\t\t})\n\n\t\ttest('type-level: adapter declares all 13 queryable ops', () => {\n\t\t\tconst _adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\ttype Ops = typeof _adapter.queryableOps\n\t\t\texpectTypeOf<Ops>().toEqualTypeOf<\n\t\t\t\treadonly ['eq', 'ne', 'gt', 'gte', 'lt', 'lte', 'in', 'notIn', 'like', 'exists', 'notExists', 'contains', 'notContains']\n\t\t\t>()\n\t\t})\n\n\t\ttest('type-level: Repo.from with MongoDbAdapter enables all builder methods', async () => {\n\t\t\tconst { Repo } = await import('../../repo/repo')\n\t\t\tconst { Schema } = await import('../../schema')\n\t\t\tconst { v } = await import('valleyed')\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\tconst repo = Repo.from(adapter).resolve(() => ({ db: 'test', col: 'test' })).build()\n\t\t\tconst _TestSchema = Schema.from('test').pk('id', v.string(), () => 'x').build()\n\n\t\t\tconst _one = repo.on(_TestSchema).one()\n\t\t\tconst _all = repo.on(_TestSchema).all()\n\t\t\tconst _ref = repo.on(_TestSchema)\n\t\t\texpectTypeOf(_one.create).toBeFunction()\n\t\t\texpectTypeOf(_one.find).toBeFunction()\n\t\t\texpectTypeOf(_one.update).toBeFunction()\n\t\t\texpectTypeOf(_one.delete).toBeFunction()\n\t\t\texpectTypeOf(_one.upsert).toBeFunction()\n\t\t\texpectTypeOf(_all.create).toBeFunction()\n\t\t\texpectTypeOf(_all.find).toBeFunction()\n\t\t\texpectTypeOf(_all.count).toBeFunction()\n\t\t\texpectTypeOf(_all.update).toBeFunction()\n\t\t\texpectTypeOf(_all.delete).toBeFunction()\n\t\t\texpectTypeOf(_ref.raw).toBeFunction()\n\t\t\texpectTypeOf(repo.session).toBeFunction()\n\t\t})\n\n\t\ttest('type-level: raw arg-tuple infers (pipeline: Record<string, unknown>[]) from MongoDbAdapter', async () => {\n\t\t\tconst { Repo } = await import('../../repo/repo')\n\t\t\tconst { Schema } = await import('../../schema')\n\t\t\tconst { v } = await import('valleyed')\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\tconst repo = Repo.from(adapter).resolve(() => ({ db: 'test', col: 'test' })).build()\n\t\t\tconst _TestSchema = Schema.from('test').pk('id', v.string(), () => 'x').build()\n\t\t\tconst _ref = repo.on(_TestSchema)\n\n\t\t\texpectTypeOf(_ref.raw).parameters.toEqualTypeOf<[pipeline: Record<string, unknown>[]]>()\n\t\t})\n\n\t\ttest('type-level: per-call <T> override narrows MongoDbAdapter raw return type', async () => {\n\t\t\tconst { Repo } = await import('../../repo/repo')\n\t\t\tconst { Schema } = await import('../../schema')\n\t\t\tconst { v } = await import('valleyed')\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\tconst repo = Repo.from(adapter).resolve(() => ({ db: 'test', col: 'test' })).build()\n\t\t\tconst _TestSchema = Schema.from('test').pk('id', v.string(), () => 'x').build()\n\t\t\tconst _ref = repo.on(_TestSchema)\n\n\t\t\texpectTypeOf(_ref.raw<{ total: number }[]>).returns.toEqualTypeOf<Promise<{ total: number }[]>>()\n\t\t})\n\n\t\ttest('count forwards compiled filter to collection.countDocuments', async () => {\n\t\t\tconst { Schema } = await import('../../schema')\n\t\t\tconst { v } = await import('valleyed')\n\t\t\tconst { FilterGroup } = await import('../../filter')\n\t\t\tconst schema = Schema.from('mongo_count').pk('_id', v.string(), () => 'x').field('name', v.string()).build()\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\tlet capturedFilter: unknown\n\t\t\t;(adapter.client as any).db = () => ({\n\t\t\t\tcollection: () => ({\n\t\t\t\t\tcountDocuments: async (filter: unknown, _opts: unknown) => {\n\t\t\t\t\t\tcapturedFilter = filter\n\t\t\t\t\t\treturn 7\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t})\n\n\t\t\tconst result = await adapter.count(schema, { db: 'testdb', col: 'things' }, FilterGroup.create().eq('name', 'Alice'))\n\t\t\texpect(capturedFilter).toEqual({ name: { $eq: 'Alice' } })\n\t\t\texpect(result).toBe(7)\n\t\t})\n\n\t\ttest('raw forwards pipeline to collection.aggregate at runtime', async () => {\n\t\t\tconst { Schema } = await import('../../schema')\n\t\t\tconst { v } = await import('valleyed')\n\t\t\tconst schema = Schema.from('mongo_raw').pk('id', v.string(), () => 'x').build()\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\tlet capturedPipeline: unknown\n\t\t\tconst mockResults = [{ total: 42 }]\n\t\t\t;(adapter.client as any).db = () => ({\n\t\t\t\tcollection: () => ({\n\t\t\t\t\taggregate: (pipeline: unknown, _opts: unknown) => {\n\t\t\t\t\t\tcapturedPipeline = pipeline\n\t\t\t\t\t\treturn { toArray: async () => mockResults }\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t})\n\t\t\tconst result = await adapter.use(schema, { db: 'testdb', col: 'things' }).raw([{ $count: 'total' }])\n\t\t\texpect(capturedPipeline).toEqual([{ $count: 'total' }])\n\t\t\texpect(result).toEqual(mockResults)\n\t\t})\n\n\t\ttest('iterateMany forwards batchSize and closes cursor on early return', async () => {\n\t\t\tconst { Schema } = await import('../../schema')\n\t\t\tconst { v } = await import('valleyed')\n\t\t\tconst { FilterGroup } = await import('../../filter')\n\t\t\tconst { OrderBy } = await import('../../query-options')\n\t\t\tconst schema = Schema.from('mongo_iter').pk('_id', v.string(), () => 'x').field('age', v.number()).build()\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\tlet capturedFindFilter: unknown\n\t\t\tlet capturedFindOptions: unknown\n\t\t\tlet capturedSort: unknown\n\t\t\tlet capturedLimit: unknown\n\t\t\tlet capturedSkip: unknown\n\t\t\tlet capturedBatchSize: unknown\n\t\t\tlet closeCalls = 0\n\t\t\tconst cursor = {\n\t\t\t\tsort(sort: unknown) {\n\t\t\t\t\tcapturedSort = sort\n\t\t\t\t\treturn this\n\t\t\t\t},\n\t\t\t\tlimit(limit: unknown) {\n\t\t\t\t\tcapturedLimit = limit\n\t\t\t\t\treturn this\n\t\t\t\t},\n\t\t\t\tskip(skip: unknown) {\n\t\t\t\t\tcapturedSkip = skip\n\t\t\t\t\treturn this\n\t\t\t\t},\n\t\t\t\tbatchSize(batchSize: unknown) {\n\t\t\t\t\tcapturedBatchSize = batchSize\n\t\t\t\t\treturn this\n\t\t\t\t},\n\t\t\t\tasync close() {\n\t\t\t\t\tcloseCalls += 1\n\t\t\t\t},\n\t\t\t\tasync *[Symbol.asyncIterator]() {\n\t\t\t\t\tyield { _id: 'u4', age: 50 }\n\t\t\t\t\tyield { _id: 'u3', age: 40 }\n\t\t\t\t},\n\t\t\t}\n\t\t\t;(adapter.client as any).db = () => ({\n\t\t\t\tcollection: () => ({\n\t\t\t\t\tfind: (filter: unknown, options: unknown) => {\n\t\t\t\t\t\tcapturedFindFilter = filter\n\t\t\t\t\t\tcapturedFindOptions = options\n\t\t\t\t\t\treturn cursor\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t})\n\n\t\t\tconst rows: Record<string, unknown>[] = []\n\t\t\tfor await (const row of adapter.use(schema, { db: 'testdb', col: 'people' }).iterateMany(FilterGroup.create().gt('age', 19), {\n\t\t\t\torderBy: [new OrderBy('age', 'desc')],\n\t\t\t\toffset: 1,\n\t\t\t\tlimit: 2,\n\t\t\t\tbatchSize: 25,\n\t\t\t})) {\n\t\t\t\trows.push(row)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\texpect(capturedFindFilter).toEqual({ age: { $gt: 19 } })\n\t\t\texpect(capturedFindOptions).toEqual({ session: undefined, projection: undefined })\n\t\t\texpect(capturedSort).toEqual({ age: -1 })\n\t\t\texpect(capturedLimit).toBe(2)\n\t\t\texpect(capturedSkip).toBe(1)\n\t\t\texpect(capturedBatchSize).toBe(25)\n\t\t\texpect(rows).toEqual([{ _id: 'u4', age: 50 }])\n\t\t\texpect(closeCalls).toBe(1)\n\t\t})\n\n\t\ttest('iterateMany closes cursor on normal completion', async () => {\n\t\t\tconst { Schema } = await import('../../schema')\n\t\t\tconst { v } = await import('valleyed')\n\t\t\tconst { FilterGroup } = await import('../../filter')\n\t\t\tconst schema = Schema.from('mongo_iter_complete').pk('_id', v.string(), () => 'x').field('age', v.number()).build()\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\tlet closeCalls = 0\n\t\t\tconst cursor = {\n\t\t\t\tasync close() {\n\t\t\t\t\tcloseCalls += 1\n\t\t\t\t},\n\t\t\t\tasync *[Symbol.asyncIterator]() {\n\t\t\t\t\tyield { _id: 'u1', age: 30 }\n\t\t\t\t\tyield { _id: 'u2', age: 40 }\n\t\t\t\t},\n\t\t\t}\n\t\t\t;(adapter.client as any).db = () => ({\n\t\t\t\tcollection: () => ({\n\t\t\t\t\tfind: () => cursor,\n\t\t\t\t}),\n\t\t\t})\n\n\t\t\tconst rows: Record<string, unknown>[] = []\n\t\t\tfor await (const row of adapter.use(schema, { db: 'testdb', col: 'people' }).iterateMany(FilterGroup.create())) {\n\t\t\t\trows.push(row)\n\t\t\t}\n\n\t\t\texpect(rows).toEqual([{ _id: 'u1', age: 30 }, { _id: 'u2', age: 40 }])\n\t\t\texpect(closeCalls).toBe(1)\n\t\t})\n\n\t\ttest('nested session returns callback without starting new transaction', () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\texpect(adapter.session).toBeTypeOf('function')\n\t\t})\n\n\t\ttest('type-level: adapter declares all 6 canonical aggregate ops', () => {\n\t\t\tconst _adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\ttype Ops = typeof _adapter.aggregateOps\n\t\t\texpectTypeOf<Ops>().toEqualTypeOf<\n\t\t\t\treadonly ['count', 'countDistinct', 'sum', 'avg', 'min', 'max']\n\t\t\t>()\n\t\t})\n\n\t\ttest('type-level: Repo.from with MongoDbAdapter enables aggregate method', async () => {\n\t\t\tconst { Repo } = await import('../../repo/repo')\n\t\t\tconst { Schema } = await import('../../schema')\n\t\t\tconst { v } = await import('valleyed')\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\tconst repo = Repo.from(adapter).resolve(() => ({ db: 'test', col: 'test' })).build()\n\t\t\tconst _TestSchema = Schema.from('test').pk('id', v.string(), () => 'x').build()\n\t\t\tconst _ref = repo.on(_TestSchema)\n\t\t\texpectTypeOf(_ref.aggregate).toBeFunction()\n\t\t})\n\n\t\ttest('aggregate forwards compiled pipeline to collection.aggregate', async () => {\n\t\t\tconst { Schema } = await import('../../schema')\n\t\t\tconst { v } = await import('valleyed')\n\t\t\tconst schema = Schema.from('mongo_agg').pk('_id', v.string(), () => 'x').field('amount', v.number()).build()\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\tlet capturedPipeline: unknown\n\t\t\tconst mockResults = [{ total: 3, revenue: 150 }]\n\t\t\t;(adapter.client as any).db = () => ({\n\t\t\t\tcollection: () => ({\n\t\t\t\t\taggregate: (pipeline: unknown, _opts: unknown) => {\n\t\t\t\t\t\tcapturedPipeline = pipeline\n\t\t\t\t\t\treturn { toArray: async () => mockResults }\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t})\n\t\t\tconst result = await adapter.aggregate(schema, { db: 'testdb', col: 'orders' }, {\n\t\t\t\taggregates: [\n\t\t\t\t\t{ fn: 'count', alias: 'total' },\n\t\t\t\t\t{ fn: 'sum', field: 'amount', alias: 'revenue' },\n\t\t\t\t],\n\t\t\t\tgroupBy: [],\n\t\t\t})\n\t\t\texpect(capturedPipeline).toEqual([\n\t\t\t\t{ $group: { _id: null, total: { $sum: 1 }, revenue: { $sum: '$amount' } } },\n\t\t\t\t{ $project: { _id: 0, total: 1, revenue: 1 } },\n\t\t\t])\n\t\t\texpect(result).toEqual(mockResults)\n\t\t})\n\n\t\ttest('aggregate with where and groupBy produces correct pipeline', async () => {\n\t\t\tconst { Schema } = await import('../../schema')\n\t\t\tconst { v } = await import('valleyed')\n\t\t\tconst { FilterGroup } = await import('../../filter')\n\t\t\tconst schema = Schema.from('mongo_agg2').pk('_id', v.string(), () => 'x').field('region', v.string()).field('amount', v.number()).build()\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\t\t\tlet capturedPipeline: unknown\n\t\t\t;(adapter.client as any).db = () => ({\n\t\t\t\tcollection: () => ({\n\t\t\t\t\taggregate: (pipeline: unknown, _opts: unknown) => {\n\t\t\t\t\t\tcapturedPipeline = pipeline\n\t\t\t\t\t\treturn { toArray: async () => [{ region: 'US', total: 2 }] }\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t})\n\t\t\tawait adapter.aggregate(schema, { db: 'testdb', col: 'orders' }, {\n\t\t\t\twhere: FilterGroup.create().gt('amount', 10),\n\t\t\t\taggregates: [{ fn: 'count', alias: 'total' }],\n\t\t\t\tgroupBy: ['region'],\n\t\t\t})\n\t\t\texpect(capturedPipeline).toEqual([\n\t\t\t\t{ $match: { amount: { $gt: 10 } } },\n\t\t\t\t{ $group: { _id: { region: '$region' }, total: { $sum: 1 } } },\n\t\t\t\t{ $project: { _id: 0, region: '$_id.region', total: 1 } },\n\t\t\t])\n\t\t})\n\n\t\ttest('auto-wires Instance hooks for connect/disconnect', async () => {\n\t\t\tconst { Instance: Inst } = await import('../../../instance')\n\t\t\tconst { vi } = await import('vitest')\n\t\t\tconst onSpy = vi.spyOn(Inst, 'on').mockImplementation(() => {})\n\n\t\t\tMongoDbAdapter.create({ uri: 'mongodb://localhost:27017' })\n\n\t\t\texpect(onSpy).toHaveBeenCalledWith('start', expect.any(Function), expect.objectContaining({ class: MongoDbAdapter }))\n\t\t\texpect(onSpy).toHaveBeenCalledWith('close', expect.any(Function), expect.objectContaining({ class: MongoDbAdapter }))\n\n\t\t\tonSpy.mockRestore()\n\t\t})\n\t})\n\n\tdescribe('MongoDbAdapter: migrations', () => {\n\t\tfunction mockMongoDb(adapter: MongoDbAdapter) {\n\t\t\tconst state = {\n\t\t\t\tmigrations: new Map<string, { _id: string; appliedAt: number }>(),\n\t\t\t\tcollections: new Map<string, { indexes: Array<{ name: string; key: Record<string, number>; unique?: boolean }> }>(),\n\t\t\t}\n\n\t\t\tconst getCol = (name: string) => {\n\t\t\t\tif (!state.collections.has(name)) {\n\t\t\t\t\tstate.collections.set(name, { indexes: [] })\n\t\t\t\t}\n\t\t\t\treturn state.collections.get(name)!\n\t\t\t}\n\n\t\t\t;(adapter.client as any).db = () => ({\n\t\t\t\tcollection: (name: string) => {\n\t\t\t\t\tif (name === MIGRATION_TRACKER_COLLECTION) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tfind: () => ({ toArray: async () => [...state.migrations.values()] }),\n\t\t\t\t\t\t\tinsertOne: async (doc: { _id: string; appliedAt: number }) => {\n\t\t\t\t\t\t\t\tstate.migrations.set(doc._id, doc)\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst col = getCol(name)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcreateIndex: async (fields: Record<string, number>, opts: { unique?: boolean; name: string }) => {\n\t\t\t\t\t\t\tcol.indexes.push({ name: opts.name, key: fields, unique: opts.unique })\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdropIndex: async (indexName: string) => {\n\t\t\t\t\t\t\tcol.indexes = col.indexes.filter((i) => i.name !== indexName)\n\t\t\t\t\t\t},\n\t\t\t\t\t\tlistIndexes: () => ({\n\t\t\t\t\t\t\ttoArray: async () => [\n\t\t\t\t\t\t\t\t{ name: '_id_', key: { _id: 1 } },\n\t\t\t\t\t\t\t\t...col.indexes,\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t}),\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tlistCollections: () => ({\n\t\t\t\t\ttoArray: async () => [...state.collections.keys()].map((name) => ({ name })),\n\t\t\t\t}),\n\t\t\t})\n\n\t\t\treturn state\n\t\t}\n\n\t\ttest('loadMigrations reads from equipped_migrations collection', async () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst state = mockMongoDb(adapter)\n\t\t\tstate.migrations.set('0001', { _id: '0001', appliedAt: 1000 })\n\t\t\tstate.migrations.set('0002', { _id: '0002', appliedAt: 2000 })\n\n\t\t\tconst result = await adapter.loadMigrations()\n\t\t\texpect(result).toEqual([\n\t\t\t\t{ id: '0001', appliedAt: 1000 },\n\t\t\t\t{ id: '0002', appliedAt: 2000 },\n\t\t\t])\n\t\t})\n\n\t\ttest('loadMigrations returns empty array when no migrations exist', async () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tmockMongoDb(adapter)\n\n\t\t\tconst result = await adapter.loadMigrations()\n\t\t\texpect(result).toEqual([])\n\t\t})\n\n\t\ttest('recordMigration inserts into equipped_migrations with _id', async () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst state = mockMongoDb(adapter)\n\n\t\t\tawait adapter.recordMigration('0001', 1234)\n\n\t\t\texpect(state.migrations.has('0001')).toBe(true)\n\t\t\texpect(state.migrations.get('0001')).toEqual({ _id: '0001', appliedAt: 1234 })\n\t\t})\n\n\t\ttest('applyAddIndex creates index with specified name and fields', async () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst state = mockMongoDb(adapter)\n\n\t\t\tawait adapter.applyAddIndex({ kind: 'addIndex', table: 'users', on: ['email'], unique: true, name: 'users_email_unique' })\n\n\t\t\tconst col = state.collections.get('users')!\n\t\t\texpect(col.indexes).toHaveLength(1)\n\t\t\texpect(col.indexes[0]).toEqual({ name: 'users_email_unique', key: { email: 1 }, unique: true })\n\t\t})\n\n\t\ttest('applyAddIndex auto-derives name when absent', async () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst state = mockMongoDb(adapter)\n\n\t\t\tawait adapter.applyAddIndex({ kind: 'addIndex', table: 'users', on: ['email'] })\n\n\t\t\tconst col = state.collections.get('users')!\n\t\t\texpect(col.indexes[0].name).toBe('users_email_idx')\n\t\t})\n\n\t\ttest('applyAddIndex auto-derived compound index name', async () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst state = mockMongoDb(adapter)\n\n\t\t\tawait adapter.applyAddIndex({ kind: 'addIndex', table: 'orders', on: ['userId', 'createdAt'] })\n\n\t\t\tconst col = state.collections.get('orders')!\n\t\t\texpect(col.indexes[0].name).toBe('orders_userId_createdAt_idx')\n\t\t\texpect(col.indexes[0].key).toEqual({ userId: 1, createdAt: 1 })\n\t\t})\n\n\t\ttest('applyDropIndex finds and drops index by scanning collections', async () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst state = mockMongoDb(adapter)\n\t\t\tstate.collections.set('users', { indexes: [{ name: 'users_email_idx', key: { email: 1 }, unique: true }] })\n\n\t\t\tawait adapter.applyDropIndex({ kind: 'dropIndex', name: 'users_email_idx' })\n\n\t\t\texpect(state.collections.get('users')!.indexes).toHaveLength(0)\n\t\t})\n\n\t\ttest('applyDropIndex is a no-op when index not found', async () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tmockMongoDb(adapter)\n\n\t\t\tawait adapter.applyDropIndex({ kind: 'dropIndex', name: 'nonexistent_idx' })\n\t\t})\n\n\t\ttest('introspect returns DiscoveredSchema with empty fields, pk, and foreignKeys', async () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst state = mockMongoDb(adapter)\n\t\t\tstate.collections.set('users', { indexes: [] })\n\t\t\tstate.collections.set('posts', { indexes: [] })\n\n\t\t\tconst schemas = await adapter.introspect()\n\n\t\t\texpect(schemas).toHaveLength(2)\n\t\t\tfor (const s of schemas) {\n\t\t\t\texpect(s.pk).toBeUndefined()\n\t\t\t\texpect(s.fields).toEqual([])\n\t\t\t\texpect(s.foreignKeys).toEqual([])\n\t\t\t}\n\t\t})\n\n\t\ttest('introspect skips _id_ index', async () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst state = mockMongoDb(adapter)\n\t\t\tstate.collections.set('users', { indexes: [{ name: 'users_email_idx', key: { email: 1 }, unique: false }] })\n\n\t\t\tconst schemas = await adapter.introspect()\n\n\t\t\texpect(schemas).toHaveLength(1)\n\t\t\texpect(schemas[0].indexes).toHaveLength(1)\n\t\t\texpect(schemas[0].indexes[0].name).toBe('users_email_idx')\n\t\t})\n\n\t\ttest('introspect skips tracker collection', async () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst state = mockMongoDb(adapter)\n\t\t\tstate.collections.set('users', { indexes: [] })\n\t\t\tstate.collections.set(MIGRATION_TRACKER_COLLECTION, { indexes: [] })\n\n\t\t\tconst schemas = await adapter.introspect()\n\n\t\t\texpect(schemas).toHaveLength(1)\n\t\t\texpect(schemas[0].name).toBe('users')\n\t\t})\n\n\t\ttest('introspect maps index keys to on array and unique flag', async () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst state = mockMongoDb(adapter)\n\t\t\tstate.collections.set('orders', {\n\t\t\t\tindexes: [\n\t\t\t\t\t{ name: 'orders_userId_createdAt_idx', key: { userId: 1, createdAt: 1 }, unique: false },\n\t\t\t\t\t{ name: 'orders_email_unique', key: { email: 1 }, unique: true },\n\t\t\t\t],\n\t\t\t})\n\n\t\t\tconst schemas = await adapter.introspect()\n\n\t\t\texpect(schemas[0].indexes).toEqual([\n\t\t\t\t{ name: 'orders_userId_createdAt_idx', on: ['userId', 'createdAt'], unique: false },\n\t\t\t\t{ name: 'orders_email_unique', on: ['email'], unique: true },\n\t\t\t])\n\t\t})\n\n\t\ttest('adapter does not implement acquireMigrationLock', () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\texpect((adapter as any).acquireMigrationLock).toBeUndefined()\n\t\t})\n\n\t\ttest('adapter does not implement DDL apply methods', () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\texpect((adapter as any).applyCreateTable).toBeUndefined()\n\t\t\texpect((adapter as any).applyDropTable).toBeUndefined()\n\t\t\texpect((adapter as any).applyAddField).toBeUndefined()\n\t\t\texpect((adapter as any).applyDropField).toBeUndefined()\n\t\t\texpect((adapter as any).applyModifyField).toBeUndefined()\n\t\t\texpect((adapter as any).applyRenameTable).toBeUndefined()\n\t\t\texpect((adapter as any).applyRenameField).toBeUndefined()\n\t\t\texpect((adapter as any).applyAddForeignKey).toBeUndefined()\n\t\t\texpect((adapter as any).applyDropForeignKey).toBeUndefined()\n\t\t})\n\n\t\ttest('type-level: ChangeFor<MongoDbAdapter> excludes DDL variants', () => {\n\t\t\ttype Changes = import('../../migrations/types').ChangeFor<MongoDbAdapter>\n\n\t\t\texpectTypeOf<Extract<Changes, { kind: 'addIndex' }>>().not.toBeNever()\n\t\t\texpectTypeOf<Extract<Changes, { kind: 'dropIndex' }>>().not.toBeNever()\n\t\t\texpectTypeOf<Extract<Changes, { kind: 'execute' }>>().not.toBeNever()\n\n\t\t\texpectTypeOf<Extract<Changes, { kind: 'addField' }>>().toBeNever()\n\t\t\texpectTypeOf<Extract<Changes, { kind: 'createTable' }>>().toBeNever()\n\t\t\texpectTypeOf<Extract<Changes, { kind: 'dropTable' }>>().toBeNever()\n\t\t\texpectTypeOf<Extract<Changes, { kind: 'modifyField' }>>().toBeNever()\n\t\t\texpectTypeOf<Extract<Changes, { kind: 'renameTable' }>>().toBeNever()\n\t\t\texpectTypeOf<Extract<Changes, { kind: 'renameField' }>>().toBeNever()\n\t\t\texpectTypeOf<Extract<Changes, { kind: 'dropField' }>>().toBeNever()\n\t\t\texpectTypeOf<Extract<Changes, { kind: 'addForeignKey' }>>().toBeNever()\n\t\t\texpectTypeOf<Extract<Changes, { kind: 'dropForeignKey' }>>().toBeNever()\n\t\t})\n\n\t\ttest('type-level: Migrator.from(repo, adapter).build() works without withoutLock', async () => {\n\t\t\tconst { Migrator } = await import('../../migrations/migrator')\n\t\t\tconst { Repo } = await import('../../repo/repo')\n\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst repo = Repo.from(adapter).resolve(() => ({ db: 'test', col: 'test' })).build()\n\t\t\tconst step = Migrator.from(repo, adapter).migrations([])\n\n\t\t\texpectTypeOf(step).toHaveProperty('build')\n\t\t\texpectTypeOf(step).toHaveProperty('withoutLock')\n\t\t})\n\n\t\ttest('type-level: Migrator.from(repo, adapter).withoutLock().build() also works', async () => {\n\t\t\tconst { Migrator } = await import('../../migrations/migrator')\n\t\t\tconst { Repo } = await import('../../repo/repo')\n\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst repo = Repo.from(adapter).resolve(() => ({ db: 'test', col: 'test' })).build()\n\t\t\tconst migrator = Migrator.from(repo, adapter).migrations([]).withoutLock().build()\n\t\t\texpect(migrator).toBeDefined()\n\t\t})\n\n\t\ttest('end-to-end: Migrator runs addIndex + dropIndex + execute changes', async () => {\n\t\t\tconst { Migrator } = await import('../../migrations/migrator')\n\t\t\tconst { Repo } = await import('../../repo/repo')\n\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst state = mockMongoDb(adapter)\n\t\t\tconst repo = Repo.from(adapter).resolve(() => ({ db: 'test', col: 'test' })).build()\n\n\t\t\tlet executeRan = false\n\t\t\ttype M = import('../../migrations/types').Migration<typeof adapter>\n\t\t\tconst migrations: M[] = [\n\t\t\t\t{\n\t\t\t\t\tid: '0001-add-idx',\n\t\t\t\t\ttx: false,\n\t\t\t\t\tchanges: [\n\t\t\t\t\t\t{ kind: 'addIndex', table: 'users', on: ['email'], unique: true },\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: '0002-backfill',\n\t\t\t\t\ttx: false,\n\t\t\t\t\tchanges: [\n\t\t\t\t\t\t{ kind: 'execute', up: async () => { executeRan = true } },\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: '0003-drop-idx',\n\t\t\t\t\ttx: false,\n\t\t\t\t\tchanges: [\n\t\t\t\t\t\t{ kind: 'dropIndex', name: 'users_email_idx' },\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t]\n\n\t\t\tconst migrator = Migrator.from(repo, adapter).migrations(migrations).build()\n\t\t\tconst result = await migrator.up()\n\n\t\t\texpect(result.ran).toEqual(['0001-add-idx', '0002-backfill', '0003-drop-idx'])\n\t\t\texpect(executeRan).toBe(true)\n\t\t\texpect(state.migrations.size).toBe(3)\n\t\t\texpect(state.collections.get('users')!.indexes).toHaveLength(0)\n\t\t})\n\n\t\ttest('introspect round-trip: addIndex then introspect sees the index', async () => {\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tconst state = mockMongoDb(adapter)\n\n\t\t\tstate.collections.set('users', {\n\t\t\t\tindexes: [{ name: 'users_email_idx', key: { email: 1 }, unique: true }],\n\t\t\t})\n\n\t\t\tconst schemas = await adapter.introspect()\n\n\t\t\texpect(schemas).toHaveLength(1)\n\t\t\texpect(schemas[0].name).toBe('users')\n\t\t\texpect(schemas[0].pk).toBeUndefined()\n\t\t\texpect(schemas[0].fields).toEqual([])\n\t\t\texpect(schemas[0].foreignKeys).toEqual([])\n\t\t\texpect(schemas[0].indexes).toEqual([\n\t\t\t\t{ name: 'users_email_idx', on: ['email'], unique: true },\n\t\t\t])\n\t\t})\n\n\t\ttest('data backfill via execute change', async () => {\n\t\t\tconst { Migrator } = await import('../../migrations/migrator')\n\t\t\tconst { Repo } = await import('../../repo/repo')\n\n\t\t\tconst adapter = MongoDbAdapter.create({ uri: 'mongodb://localhost:27017/testdb' })\n\t\t\tmockMongoDb(adapter)\n\t\t\tconst repo = Repo.from(adapter).resolve(() => ({ db: 'test', col: 'test' })).build()\n\n\t\t\tconst backfilledData: string[] = []\n\t\t\ttype M = import('../../migrations/types').Migration<typeof adapter>\n\t\t\tconst m: M = {\n\t\t\t\tid: '0001-backfill',\n\t\t\t\ttx: false,\n\t\t\t\tchanges: [{\n\t\t\t\t\tkind: 'execute',\n\t\t\t\t\tup: async () => {\n\t\t\t\t\t\tbackfilledData.push('user-1-normalized')\n\t\t\t\t\t\tbackfilledData.push('user-2-normalized')\n\t\t\t\t\t},\n\t\t\t\t}],\n\t\t\t}\n\n\t\t\tconst migrator = Migrator.from(repo, adapter).migrations([m]).build()\n\t\t\tawait migrator.up()\n\n\t\t\texpect(backfilledData).toEqual(['user-1-normalized', 'user-2-normalized'])\n\t\t})\n\t})\n}\n","import { Filter, FilterGroup, type FilterChild } from '../../filter'\nimport type { AggregateSpec } from '../../orm-adapter'\nimport type { QueryOptions } from '../../query-options'\nimport { flattenOps, IncOp, MaxOp, MinOp, MulOp, PatchOp, PullOp, PushOp, SetOp, UnsetOp, type AnyUpdateOp } from '../../updates'\n\ntype MongoFilter = Record<string, unknown>\n\nexport function compileMongoFilter(group: FilterGroup, primaryKey: string): MongoFilter {\n\tconst clauses: MongoFilter[] = []\n\tfor (const child of group.children) {\n\t\tconst compiled = compileChild(child, primaryKey)\n\t\tif (compiled) clauses.push(compiled)\n\t}\n\n\tif (clauses.length === 0) return {}\n\tif (clauses.length === 1) return clauses[0]\n\treturn { $and: clauses }\n}\n\nexport function compileMongoQuery(\n\tgroup: FilterGroup,\n\toptions: QueryOptions | undefined,\n\tprimaryKey: string,\n): {\n\tfilter: MongoFilter\n\tsort: Record<string, 1 | -1> | undefined\n\tlimit: number | undefined\n\tskip: number | undefined\n\tprojection: Record<string, 1> | undefined\n} {\n\tconst mongoFilter = compileMongoFilter(group, primaryKey)\n\n\tconst orderBys = options?.orderBy ?? []\n\tconst sort =\n\t\torderBys.length > 0\n\t\t\t? Object.fromEntries(orderBys.map((o) => [mapField(o.field, primaryKey), o.direction === 'desc' ? -1 : 1]))\n\t\t\t: undefined\n\n\tconst selects = options?.select ?? []\n\tconst projection = selects.length > 0 ? Object.fromEntries(selects.map((f) => [mapField(f, primaryKey), 1])) : undefined\n\n\treturn {\n\t\tfilter: mongoFilter,\n\t\tsort: sort as Record<string, 1 | -1> | undefined,\n\t\tlimit: options?.limit,\n\t\tskip: options?.offset,\n\t\tprojection: projection as Record<string, 1> | undefined,\n\t}\n}\n\nfunction mapField(field: string, primaryKey: string): string {\n\tif (field === 'id' && primaryKey === '_id') return '_id'\n\treturn field\n}\n\nfunction compileFilter(f: Filter, primaryKey: string): MongoFilter {\n\tconst field = mapField(f.field, primaryKey)\n\n\tswitch (f.op) {\n\t\tcase 'eq':\n\t\t\treturn { [field]: { $eq: f.value } }\n\t\tcase 'ne':\n\t\t\treturn { [field]: { $ne: f.value } }\n\t\tcase 'gt':\n\t\t\treturn { [field]: { $gt: f.value } }\n\t\tcase 'gte':\n\t\t\treturn { [field]: { $gte: f.value } }\n\t\tcase 'lt':\n\t\t\treturn { [field]: { $lt: f.value } }\n\t\tcase 'lte':\n\t\t\treturn { [field]: { $lte: f.value } }\n\t\tcase 'in':\n\t\t\treturn { [field]: { $in: f.value } }\n\t\tcase 'notIn':\n\t\t\treturn { [field]: { $nin: f.value } }\n\t\tcase 'like':\n\t\t\treturn { [field]: { $regex: new RegExp(String(f.value), 'i') } }\n\t\tcase 'exists':\n\t\t\treturn { [field]: { $exists: true, $ne: null } }\n\t\tcase 'notExists':\n\t\t\treturn { [field]: { $eq: null } }\n\t\tcase 'contains':\n\t\t\treturn { [field]: { $all: Array.isArray(f.value) ? f.value : [f.value] } }\n\t\tcase 'notContains':\n\t\t\treturn { [field]: { $not: { $all: Array.isArray(f.value) ? f.value : [f.value] } } }\n\t\tdefault:\n\t\t\treturn { [field]: { $eq: f.value } }\n\t}\n}\n\nfunction compileChild(child: FilterChild, primaryKey: string): MongoFilter | null {\n\tif (child instanceof Filter) return compileFilter(child, primaryKey)\n\tif (child instanceof FilterGroup) return compileGroup(child, primaryKey)\n\treturn null\n}\n\nfunction compileGroup(group: FilterGroup, primaryKey: string): MongoFilter | null {\n\tconst clauses = group.children.map((c) => compileChild(c, primaryKey)).filter((c): c is MongoFilter => c !== null)\n\tif (clauses.length === 0) return null\n\tif (clauses.length === 1) return clauses[0]\n\treturn { [group.op === 'or' ? '$or' : '$and']: clauses }\n}\n\nexport function compileMongoUpdate(data: Record<string, unknown>): Record<string, unknown> {\n\tconst $set: Record<string, unknown> = {}\n\tconst $inc: Record<string, unknown> = {}\n\tconst $mul: Record<string, unknown> = {}\n\tconst $min: Record<string, unknown> = {}\n\tconst $max: Record<string, unknown> = {}\n\tconst $unset: Record<string, ''> = {}\n\tconst $push: Record<string, unknown> = {}\n\tconst $pull: Record<string, unknown> = {}\n\n\tfor (const [key, value] of Object.entries(data)) {\n\t\tif (value instanceof IncOp) $inc[key] = value.value\n\t\telse if (value instanceof MulOp) $mul[key] = value.value\n\t\telse if (value instanceof MinOp) $min[key] = value.value\n\t\telse if (value instanceof MaxOp) $max[key] = value.value\n\t\telse if (value instanceof UnsetOp) $unset[key] = ''\n\t\telse if (value instanceof PushOp) $push[key] = value.value\n\t\telse if (value instanceof PullOp) $pull[key] = value.value\n\t\telse if (value instanceof PatchOp) {\n\t\t\tconst patchVal = value.value as Record<string, unknown>\n\t\t\tfor (const [subKey, subVal] of Object.entries(patchVal)) {\n\t\t\t\t$set[`${key}.${subKey}`] = subVal\n\t\t\t}\n\t\t} else $set[key] = value\n\t}\n\n\tconst result: Record<string, unknown> = {}\n\tif (Object.keys($set).length) result.$set = $set\n\tif (Object.keys($inc).length) result.$inc = $inc\n\tif (Object.keys($mul).length) result.$mul = $mul\n\tif (Object.keys($min).length) result.$min = $min\n\tif (Object.keys($max).length) result.$max = $max\n\tif (Object.keys($unset).length) result.$unset = $unset\n\tif (Object.keys($push).length) result.$push = $push\n\tif (Object.keys($pull).length) result.$pull = $pull\n\n\treturn result\n}\n\nexport function compileMongoOps(ops: AnyUpdateOp[]): Record<string, unknown> {\n\treturn compileMongoUpdate(flattenOps(ops))\n}\n\nexport function compileMongoAggregate(spec: AggregateSpec, primaryKey: string): Record<string, unknown>[] {\n\tconst pipeline: Record<string, unknown>[] = []\n\n\tif (spec.where) {\n\t\tconst match = compileMongoFilter(spec.where, primaryKey)\n\t\tif (Object.keys(match).length > 0) pipeline.push({ $match: match })\n\t}\n\n\tconst groupId: Record<string, string> | null =\n\t\tspec.groupBy.length > 0\n\t\t\t? Object.fromEntries(spec.groupBy.map((f) => [f, `$${mapField(f, primaryKey)}`]))\n\t\t\t: null\n\n\tconst accumulators: Record<string, unknown> = {}\n\tfor (const agg of spec.aggregates) {\n\t\tconst fieldRef = agg.field ? `$${mapField(agg.field, primaryKey)}` : undefined\n\t\tswitch (agg.fn) {\n\t\t\tcase 'count':\n\t\t\t\taccumulators[agg.alias] = { $sum: 1 }\n\t\t\t\tbreak\n\t\t\tcase 'countDistinct':\n\t\t\t\taccumulators[agg.alias] = { $addToSet: fieldRef }\n\t\t\t\tbreak\n\t\t\tcase 'sum':\n\t\t\tcase 'avg':\n\t\t\tcase 'min':\n\t\t\tcase 'max':\n\t\t\t\taccumulators[agg.alias] = { [`$${agg.fn}`]: fieldRef }\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\tpipeline.push({ $group: { _id: groupId, ...accumulators } })\n\n\tconst project: Record<string, unknown> = { _id: 0 }\n\tfor (const f of spec.groupBy) {\n\t\tproject[f] = `$_id.${f}`\n\t}\n\tfor (const agg of spec.aggregates) {\n\t\tif (agg.fn === 'countDistinct') {\n\t\t\tproject[agg.alias] = { $size: `$${agg.alias}` }\n\t\t} else {\n\t\t\tproject[agg.alias] = 1\n\t\t}\n\t}\n\tpipeline.push({ $project: project })\n\n\tif (spec.having) {\n\t\tconst havingMatch = compileMongoFilter(spec.having, '')\n\t\tif (Object.keys(havingMatch).length > 0) pipeline.push({ $match: havingMatch })\n\t}\n\n\treturn pipeline\n}\n\nif (import.meta.vitest) {\n\tconst { describe, test, expect } = import.meta.vitest\n\tconst { FilterGroup } = await import('../../filter')\n\tconst { OrderBy } = await import('../../query-options')\n\n\tdescribe('compileMongoFilter', () => {\n\t\ttest('empty filter group compiles to empty object', () => {\n\t\t\tconst group = FilterGroup.create()\n\t\t\texpect(compileMongoFilter(group, 'id')).toEqual({})\n\t\t})\n\n\t\ttest('single eq filter compiles to $eq', () => {\n\t\t\tconst group = FilterGroup.create().eq('name', 'Alice')\n\t\t\texpect(compileMongoFilter(group, 'id')).toEqual({ name: { $eq: 'Alice' } })\n\t\t})\n\n\t\ttest('ne, gt, gte, lt, lte compile to corresponding Mongo ops', () => {\n\t\t\texpect(compileMongoFilter(FilterGroup.create().ne('age', 5), 'id')).toEqual({ age: { $ne: 5 } })\n\t\t\texpect(compileMongoFilter(FilterGroup.create().gt('age', 10), 'id')).toEqual({ age: { $gt: 10 } })\n\t\t\texpect(compileMongoFilter(FilterGroup.create().gte('age', 20), 'id')).toEqual({ age: { $gte: 20 } })\n\t\t\texpect(compileMongoFilter(FilterGroup.create().lt('age', 30), 'id')).toEqual({ age: { $lt: 30 } })\n\t\t\texpect(compileMongoFilter(FilterGroup.create().lte('age', 40), 'id')).toEqual({ age: { $lte: 40 } })\n\t\t})\n\n\t\ttest('in compiles to $in', () => {\n\t\t\tconst group = FilterGroup.create().in('status', ['a', 'b'])\n\t\t\texpect(compileMongoFilter(group, 'id')).toEqual({ status: { $in: ['a', 'b'] } })\n\t\t})\n\n\t\ttest('notIn compiles to $nin (canonical name notIn, Mongo op $nin)', () => {\n\t\t\tconst group = FilterGroup.create().notIn('status', ['x', 'y'])\n\t\t\texpect(compileMongoFilter(group, 'id')).toEqual({ status: { $nin: ['x', 'y'] } })\n\t\t})\n\n\t\ttest('like compiles to $regex with case-insensitive flag', () => {\n\t\t\tconst group = FilterGroup.create().like('name', 'ali')\n\t\t\tconst result = compileMongoFilter(group, 'id')\n\t\t\texpect(result.name).toEqual({ $regex: expect.any(RegExp) })\n\t\t\tconst regex = (result.name as any).$regex as RegExp\n\t\t\texpect(regex.flags).toBe('i')\n\t\t\texpect(regex.test('Alice')).toBe(true)\n\t\t})\n\n\t\ttest('exists compiles to $exists: true, $ne: null', () => {\n\t\t\tconst group = FilterGroup.create().exists('val')\n\t\t\texpect(compileMongoFilter(group, 'id')).toEqual({ val: { $exists: true, $ne: null } })\n\t\t})\n\n\t\ttest('notExists is its own op — compiles to $eq: null', () => {\n\t\t\tconst group = FilterGroup.create().notExists('val')\n\t\t\texpect(compileMongoFilter(group, 'id')).toEqual({ val: { $eq: null } })\n\t\t})\n\n\t\ttest('contains compiles to $all', () => {\n\t\t\tconst group = FilterGroup.create().contains('tags', ['a', 'b'])\n\t\t\texpect(compileMongoFilter(group, 'id')).toEqual({ tags: { $all: ['a', 'b'] } })\n\t\t})\n\n\t\ttest('notContains compiles to $not: { $all }', () => {\n\t\t\tconst group = FilterGroup.create().notContains('tags', ['x'])\n\t\t\texpect(compileMongoFilter(group, 'id')).toEqual({ tags: { $not: { $all: ['x'] } } })\n\t\t})\n\n\t\ttest('multiple clauses produce $and', () => {\n\t\t\tconst group = FilterGroup.create().eq('a', 1).gt('b', 2)\n\t\t\tconst result = compileMongoFilter(group, 'id')\n\t\t\texpect(result).toEqual({ $and: [{ a: { $eq: 1 } }, { b: { $gt: 2 } }] })\n\t\t})\n\n\t\ttest('nested and/or groups compile correctly', () => {\n\t\t\tconst group = FilterGroup.create().and([\n\t\t\t\t(q) => q.eq('a', 1),\n\t\t\t\t(q) => q.or([(g) => g.eq('b', 2), (g) => g.eq('c', 3)]),\n\t\t\t])\n\t\t\tconst result = compileMongoFilter(group, 'id')\n\t\t\texpect(result).toEqual({\n\t\t\t\t$and: [{ a: { $eq: 1 } }, { $or: [{ b: { $eq: 2 } }, { c: { $eq: 3 } }] }],\n\t\t\t})\n\t\t})\n\n\t\ttest('maps id field to _id when primaryKey is _id', () => {\n\t\t\tconst group = FilterGroup.create().eq('id', 'abc')\n\t\t\texpect(compileMongoFilter(group, '_id')).toEqual({ _id: { $eq: 'abc' } })\n\t\t})\n\t})\n\n\tdescribe('compileMongoQuery', () => {\n\t\ttest('options: sort, limit, skip, projection', () => {\n\t\t\tconst group = FilterGroup.create().eq('active', true)\n\t\t\tconst options = {\n\t\t\t\torderBy: [new OrderBy('name', 'asc'), new OrderBy('age', 'desc')],\n\t\t\t\tlimit: 10,\n\t\t\t\toffset: 5,\n\t\t\t\tselect: ['name', 'age'] as const,\n\t\t\t}\n\t\t\tconst result = compileMongoQuery(group, options, 'id')\n\t\t\texpect(result.filter).toEqual({ active: { $eq: true } })\n\t\t\texpect(result.sort).toEqual({ name: 1, age: -1 })\n\t\t\texpect(result.limit).toBe(10)\n\t\t\texpect(result.skip).toBe(5)\n\t\t\texpect(result.projection).toEqual({ name: 1, age: 1 })\n\t\t})\n\n\t\ttest('undefined options returns undefined for sort/limit/skip/projection', () => {\n\t\t\tconst group = FilterGroup.create().eq('x', 1)\n\t\t\tconst result = compileMongoQuery(group, undefined, 'id')\n\t\t\texpect(result.sort).toBeUndefined()\n\t\t\texpect(result.limit).toBeUndefined()\n\t\t\texpect(result.skip).toBeUndefined()\n\t\t\texpect(result.projection).toBeUndefined()\n\t\t})\n\t})\n\n\tdescribe('compileMongoUpdate', () => {\n\t\ttest('plain values go into $set', () => {\n\t\t\tconst result = compileMongoUpdate({ name: 'Alice', age: 30 })\n\t\t\texpect(result).toEqual({ $set: { name: 'Alice', age: 30 } })\n\t\t})\n\n\t\ttest('IncOp goes into $inc', () => {\n\t\t\tconst result = compileMongoUpdate({ count: new IncOp('count', 5) })\n\t\t\texpect(result).toEqual({ $inc: { count: 5 } })\n\t\t})\n\n\t\ttest('MulOp goes into $mul', () => {\n\t\t\tconst result = compileMongoUpdate({ score: new MulOp('score', 2) })\n\t\t\texpect(result).toEqual({ $mul: { score: 2 } })\n\t\t})\n\n\t\ttest('MinOp/MaxOp go into $min/$max', () => {\n\t\t\tconst result = compileMongoUpdate({\n\t\t\t\tlo: new MinOp('lo', 1),\n\t\t\t\thi: new MaxOp('hi', 99),\n\t\t\t})\n\t\t\texpect(result).toEqual({ $min: { lo: 1 }, $max: { hi: 99 } })\n\t\t})\n\n\t\ttest('UnsetOp goes into $unset', () => {\n\t\t\tconst result = compileMongoUpdate({ old: new UnsetOp('old') })\n\t\t\texpect(result).toEqual({ $unset: { old: '' } })\n\t\t})\n\n\t\ttest('PushOp/PullOp go into $push/$pull', () => {\n\t\t\tconst result = compileMongoUpdate({\n\t\t\t\ttags: new PushOp('tags', 'new'),\n\t\t\t\tremoved: new PullOp('removed', 'old'),\n\t\t\t})\n\t\t\texpect(result).toEqual({ $push: { tags: 'new' }, $pull: { removed: 'old' } })\n\t\t})\n\n\t\ttest('PatchOp produces dot-notation $set entries', () => {\n\t\t\tconst result = compileMongoUpdate({ meta: new PatchOp('meta', { a: 1, b: 2 }) })\n\t\t\texpect(result).toEqual({ $set: { 'meta.a': 1, 'meta.b': 2 } })\n\t\t})\n\n\t\ttest('empty data produces empty result', () => {\n\t\t\tconst result = compileMongoUpdate({})\n\t\t\texpect(result).toEqual({})\n\t\t})\n\t})\n\n\tdescribe('compileMongoOps', () => {\n\t\ttest('SetOp values go into $set', () => {\n\t\t\tconst result = compileMongoOps([new SetOp({ name: 'Bob', age: 25 })])\n\t\t\texpect(result).toEqual({ $set: { name: 'Bob', age: 25 } })\n\t\t})\n\n\t\ttest('mixed ops compile to separate Mongo update operators', () => {\n\t\t\tconst result = compileMongoOps([\n\t\t\t\tnew SetOp({ name: 'Alice' }),\n\t\t\t\tnew IncOp('count', 1),\n\t\t\t\tnew PushOp('tags', 'x'),\n\t\t\t])\n\t\t\texpect(result).toEqual({\n\t\t\t\t$set: { name: 'Alice' },\n\t\t\t\t$inc: { count: 1 },\n\t\t\t\t$push: { tags: 'x' },\n\t\t\t})\n\t\t})\n\n\t\ttest('empty ops produces empty result', () => {\n\t\t\texpect(compileMongoOps([])).toEqual({})\n\t\t})\n\t})\n\n\tdescribe('compileMongoAggregate', () => {\n\t\ttest('bare count produces $group with $sum:1 and $project', () => {\n\t\t\tconst spec: AggregateSpec = {\n\t\t\t\taggregates: [{ fn: 'count', alias: 'total' }],\n\t\t\t\tgroupBy: [],\n\t\t\t}\n\t\t\texpect(compileMongoAggregate(spec, '_id')).toEqual([\n\t\t\t\t{ $group: { _id: null, total: { $sum: 1 } } },\n\t\t\t\t{ $project: { _id: 0, total: 1 } },\n\t\t\t])\n\t\t})\n\n\t\ttest('multi-aggregator produces all accumulators in $group', () => {\n\t\t\tconst spec: AggregateSpec = {\n\t\t\t\taggregates: [\n\t\t\t\t\t{ fn: 'count', alias: 'total' },\n\t\t\t\t\t{ fn: 'sum', field: 'amount', alias: 'revenue' },\n\t\t\t\t\t{ fn: 'avg', field: 'price', alias: 'avgPrice' },\n\t\t\t\t],\n\t\t\t\tgroupBy: [],\n\t\t\t}\n\t\t\texpect(compileMongoAggregate(spec, '_id')).toEqual([\n\t\t\t\t{\n\t\t\t\t\t$group: {\n\t\t\t\t\t\t_id: null,\n\t\t\t\t\t\ttotal: { $sum: 1 },\n\t\t\t\t\t\trevenue: { $sum: '$amount' },\n\t\t\t\t\t\tavgPrice: { $avg: '$price' },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ $project: { _id: 0, total: 1, revenue: 1, avgPrice: 1 } },\n\t\t\t])\n\t\t})\n\n\t\ttest('single-column groupBy produces composite _id and $project lift', () => {\n\t\t\tconst spec: AggregateSpec = {\n\t\t\t\taggregates: [{ fn: 'count', alias: 'total' }],\n\t\t\t\tgroupBy: ['region'],\n\t\t\t}\n\t\t\texpect(compileMongoAggregate(spec, '_id')).toEqual([\n\t\t\t\t{ $group: { _id: { region: '$region' }, total: { $sum: 1 } } },\n\t\t\t\t{ $project: { _id: 0, region: '$_id.region', total: 1 } },\n\t\t\t])\n\t\t})\n\n\t\ttest('multi-column groupBy via composite _id', () => {\n\t\t\tconst spec: AggregateSpec = {\n\t\t\t\taggregates: [{ fn: 'sum', field: 'amount', alias: 'revenue' }],\n\t\t\t\tgroupBy: ['region', 'year'],\n\t\t\t}\n\t\t\texpect(compileMongoAggregate(spec, '_id')).toEqual([\n\t\t\t\t{\n\t\t\t\t\t$group: {\n\t\t\t\t\t\t_id: { region: '$region', year: '$year' },\n\t\t\t\t\t\trevenue: { $sum: '$amount' },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$project: {\n\t\t\t\t\t\t_id: 0,\n\t\t\t\t\t\tregion: '$_id.region',\n\t\t\t\t\t\tyear: '$_id.year',\n\t\t\t\t\t\trevenue: 1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t])\n\t\t})\n\n\t\ttest('where-only emits $match before $group', () => {\n\t\t\tconst spec: AggregateSpec = {\n\t\t\t\twhere: FilterGroup.create().eq('active', true),\n\t\t\t\taggregates: [{ fn: 'count', alias: 'total' }],\n\t\t\t\tgroupBy: [],\n\t\t\t}\n\t\t\texpect(compileMongoAggregate(spec, '_id')).toEqual([\n\t\t\t\t{ $match: { active: { $eq: true } } },\n\t\t\t\t{ $group: { _id: null, total: { $sum: 1 } } },\n\t\t\t\t{ $project: { _id: 0, total: 1 } },\n\t\t\t])\n\t\t})\n\n\t\ttest('having-only emits $match after $project', () => {\n\t\t\tconst spec: AggregateSpec = {\n\t\t\t\taggregates: [{ fn: 'count', alias: 'total' }],\n\t\t\t\tgroupBy: ['region'],\n\t\t\t\thaving: FilterGroup.create().gt('total', 5),\n\t\t\t}\n\t\t\texpect(compileMongoAggregate(spec, '_id')).toEqual([\n\t\t\t\t{ $group: { _id: { region: '$region' }, total: { $sum: 1 } } },\n\t\t\t\t{ $project: { _id: 0, region: '$_id.region', total: 1 } },\n\t\t\t\t{ $match: { total: { $gt: 5 } } },\n\t\t\t])\n\t\t})\n\n\t\ttest('where + having produces both $match stages', () => {\n\t\t\tconst spec: AggregateSpec = {\n\t\t\t\twhere: FilterGroup.create().eq('active', true),\n\t\t\t\taggregates: [{ fn: 'sum', field: 'amount', alias: 'revenue' }],\n\t\t\t\tgroupBy: ['region'],\n\t\t\t\thaving: FilterGroup.create().gte('revenue', 1000),\n\t\t\t}\n\t\t\texpect(compileMongoAggregate(spec, '_id')).toEqual([\n\t\t\t\t{ $match: { active: { $eq: true } } },\n\t\t\t\t{\n\t\t\t\t\t$group: {\n\t\t\t\t\t\t_id: { region: '$region' },\n\t\t\t\t\t\trevenue: { $sum: '$amount' },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ $project: { _id: 0, region: '$_id.region', revenue: 1 } },\n\t\t\t\t{ $match: { revenue: { $gte: 1000 } } },\n\t\t\t])\n\t\t})\n\n\t\ttest('countDistinct uses $addToSet in $group and $size in $project', () => {\n\t\t\tconst spec: AggregateSpec = {\n\t\t\t\taggregates: [{ fn: 'countDistinct', field: 'userId', alias: 'uniqueUsers' }],\n\t\t\t\tgroupBy: [],\n\t\t\t}\n\t\t\texpect(compileMongoAggregate(spec, '_id')).toEqual([\n\t\t\t\t{ $group: { _id: null, uniqueUsers: { $addToSet: '$userId' } } },\n\t\t\t\t{ $project: { _id: 0, uniqueUsers: { $size: '$uniqueUsers' } } },\n\t\t\t])\n\t\t})\n\n\t\ttest('min/max produce $min/$max accumulators', () => {\n\t\t\tconst spec: AggregateSpec = {\n\t\t\t\taggregates: [\n\t\t\t\t\t{ fn: 'min', field: 'price', alias: 'lowest' },\n\t\t\t\t\t{ fn: 'max', field: 'price', alias: 'highest' },\n\t\t\t\t],\n\t\t\t\tgroupBy: [],\n\t\t\t}\n\t\t\texpect(compileMongoAggregate(spec, '_id')).toEqual([\n\t\t\t\t{\n\t\t\t\t\t$group: {\n\t\t\t\t\t\t_id: null,\n\t\t\t\t\t\tlowest: { $min: '$price' },\n\t\t\t\t\t\thighest: { $max: '$price' },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ $project: { _id: 0, lowest: 1, highest: 1 } },\n\t\t\t])\n\t\t})\n\n\t\ttest('field-name mapping: id field maps to _id when primaryKey is _id', () => {\n\t\t\tconst spec: AggregateSpec = {\n\t\t\t\twhere: FilterGroup.create().eq('id', 'abc'),\n\t\t\t\taggregates: [{ fn: 'count', alias: 'total' }],\n\t\t\t\tgroupBy: ['id'],\n\t\t\t}\n\t\t\texpect(compileMongoAggregate(spec, '_id')).toEqual([\n\t\t\t\t{ $match: { _id: { $eq: 'abc' } } },\n\t\t\t\t{ $group: { _id: { id: '$_id' }, total: { $sum: 1 } } },\n\t\t\t\t{ $project: { _id: 0, id: '$_id.id', total: 1 } },\n\t\t\t])\n\t\t})\n\n\t\ttest('countDistinct with groupBy combines $addToSet, groupBy lift, and $size', () => {\n\t\t\tconst spec: AggregateSpec = {\n\t\t\t\taggregates: [{ fn: 'countDistinct', field: 'category', alias: 'uniqueCats' }],\n\t\t\t\tgroupBy: ['region'],\n\t\t\t}\n\t\t\texpect(compileMongoAggregate(spec, '_id')).toEqual([\n\t\t\t\t{\n\t\t\t\t\t$group: {\n\t\t\t\t\t\t_id: { region: '$region' },\n\t\t\t\t\t\tuniqueCats: { $addToSet: '$category' },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$project: {\n\t\t\t\t\t\t_id: 0,\n\t\t\t\t\t\tregion: '$_id.region',\n\t\t\t\t\t\tuniqueCats: { $size: '$uniqueCats' },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t])\n\t\t})\n\n\t\ttest('all six aggregators in a single pipeline', () => {\n\t\t\tconst spec: AggregateSpec = {\n\t\t\t\taggregates: [\n\t\t\t\t\t{ fn: 'count', alias: 'total' },\n\t\t\t\t\t{ fn: 'countDistinct', field: 'status', alias: 'uniqueStatuses' },\n\t\t\t\t\t{ fn: 'sum', field: 'amount', alias: 'totalAmount' },\n\t\t\t\t\t{ fn: 'avg', field: 'amount', alias: 'avgAmount' },\n\t\t\t\t\t{ fn: 'min', field: 'amount', alias: 'minAmount' },\n\t\t\t\t\t{ fn: 'max', field: 'amount', alias: 'maxAmount' },\n\t\t\t\t],\n\t\t\t\tgroupBy: ['region'],\n\t\t\t}\n\t\t\tconst pipeline = compileMongoAggregate(spec, '_id')\n\t\t\texpect(pipeline).toEqual([\n\t\t\t\t{\n\t\t\t\t\t$group: {\n\t\t\t\t\t\t_id: { region: '$region' },\n\t\t\t\t\t\ttotal: { $sum: 1 },\n\t\t\t\t\t\tuniqueStatuses: { $addToSet: '$status' },\n\t\t\t\t\t\ttotalAmount: { $sum: '$amount' },\n\t\t\t\t\t\tavgAmount: { $avg: '$amount' },\n\t\t\t\t\t\tminAmount: { $min: '$amount' },\n\t\t\t\t\t\tmaxAmount: { $max: '$amount' },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t$project: {\n\t\t\t\t\t\t_id: 0,\n\t\t\t\t\t\tregion: '$_id.region',\n\t\t\t\t\t\ttotal: 1,\n\t\t\t\t\t\tuniqueStatuses: { $size: '$uniqueStatuses' },\n\t\t\t\t\t\ttotalAmount: 1,\n\t\t\t\t\t\tavgAmount: 1,\n\t\t\t\t\t\tminAmount: 1,\n\t\t\t\t\t\tmaxAmount: 1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t])\n\t\t})\n\n\t\ttest('empty where filter is omitted from pipeline', () => {\n\t\t\tconst spec: AggregateSpec = {\n\t\t\t\twhere: FilterGroup.create(),\n\t\t\t\taggregates: [{ fn: 'count', alias: 'total' }],\n\t\t\t\tgroupBy: [],\n\t\t\t}\n\t\t\texpect(compileMongoAggregate(spec, '_id')).toEqual([\n\t\t\t\t{ $group: { _id: null, total: { $sum: 1 } } },\n\t\t\t\t{ $project: { _id: 0, total: 1 } },\n\t\t\t])\n\t\t})\n\t})\n}\n"],"mappings":"yTAAA,OAAS,qBAAAA,MAAyB,cAElC,OAAS,eAAAC,MAA+F,UACxG,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A,EAAO,KAAK,IAAIA,EAAO,GAAG,KAAK,GAAG,CAAC,OAClE,MAAMC,EAAG,WAAWD,EAAO,KAAK,EAAE,YAAYE,EAAQ,CAAE,OAAQF,EAAO,QAAU,GAAO,KAAAI,CAAK,CAAC,CAC/F,CAEA,MAAM,eAAeJ,EAAwC,CAC5D,IAAMC,EAAK,KAAK,OAAO,GAAG,EACpBI,EAAc,MAAMJ,EAAG,gBAAgB,EAAE,QAAQ,EACvD,QAAWK,KAAOD,EAEjB,IADgB,MAAMJ,EAAG,WAAWK,EAAI,IAAI,EAAE,YAAY,EAAE,QAAQ,GACxD,KAAMC,GAAQA,EAAI,OAASP,EAAO,IAAI,EAAG,CACpD,MAAMC,EAAG,WAAWK,EAAI,IAAI,EAAE,UAAUN,EAAO,IAAI,EACnD,MACD,CAEF,CAEA,MAAM,YAA0C,CAC/C,IAAMC,EAAK,KAAK,OAAO,GAAG,EACpBI,EAAc,MAAMJ,EAAG,gBAAgB,EAAE,QAAQ,EACjDO,EAA8B,CAAC,EACrC,QAAWF,KAAOD,EAAa,CAC9B,GAAIC,EAAI,OAASpD,EAA8B,SAE/C,IAAMuD,GADa,MAAMR,EAAG,WAAWK,EAAI,IAAI,EAAE,YAAY,EAAE,QAAQ,GAErE,OAAQC,GAAQA,EAAI,OAAS,MAAM,EACnC,IAAKA,IAAS,CACd,KAAMA,EAAI,KACV,GAAI,OAAO,KAAKA,EAAI,GAA8B,EAClD,OAAQ,CAAC,CAAEA,EAAI,MAChB,EAAE,EACHC,EAAQ,KAAK,CACZ,KAAMF,EAAI,KACV,GAAI,OACJ,OAAQ,CAAC,EACT,QAAAG,EACA,YAAa,CAAC,CACf,CAAC,CACF,CACA,OAAOD,CACR,CACD","names":["AsyncLocalStorage","MongoClient","v","compileMongoFilter","group","primaryKey","clauses","child","compiled","compileChild","compileMongoQuery","options","mongoFilter","orderBys","sort","o","mapField","selects","projection","f","field","compileFilter","Filter","FilterGroup","compileGroup","c","compileMongoUpdate","data","$set","$inc","$mul","$min","$max","$unset","$push","$pull","key","value","IncOp","MulOp","MinOp","MaxOp","UnsetOp","PushOp","PullOp","PatchOp","patchVal","subKey","subVal","result","compileMongoOps","ops","flattenOps","compileMongoAggregate","spec","pipeline","match","groupId","accumulators","agg","fieldRef","project","havingMatch","mongoSchemaConfigPipe","v","mongoConnectionPipe","MIGRATION_TRACKER_COLLECTION","MongoDbAdapter","configurable","OrmAdapter","#sessionStore","AsyncLocalStorage","config","options","MongoClient","#getCollection","schemaCfg","error","EquippedError","schema","pk","pkName","_schema","data","collection","docs","d","ops","update","compileMongoOps","pipeline","spec","compileMongoAggregate","filter","mongoFilter","sort","limit","skip","projection","compileMongoQuery","cursor","compileMongoFilter","row","session","ids","idFilter","compileMongoUpdate","create","updateDoc","fn","id","appliedAt","change","db","fields","f","name","collections","col","idx","schemas","indexes"]}