@orion-js/mongodb 4.0.30 → 4.0.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1187,6 +1187,7 @@ var generateId_default = getIdGenerator;
1187
1187
 
1188
1188
  // src/createCollection/createIndexes.ts
1189
1189
  var import_mongodb2 = require("mongodb");
1190
+ var import_logger2 = require("@orion-js/logger");
1190
1191
  function matchingDefinition(defIndex, curIndex) {
1191
1192
  if (defIndex.options && defIndex.options.name === curIndex.name) return true;
1192
1193
  const defIndexName = Object.keys(defIndex.keys).map((key) => `${key}_${defIndex.keys[key]}`).join("_");
@@ -1204,7 +1205,7 @@ async function checkIndexes(collection) {
1204
1205
  (index) => index.name !== "_id_" && !collection.indexes.find((definitionIndex) => matchingDefinition(definitionIndex, index))
1205
1206
  ) : currentIndexes;
1206
1207
  if (indexesToDelete.length > 0) {
1207
- console.warn(
1208
+ import_logger2.logger.warn(
1208
1209
  `${indexesToDelete.length} unexpected indexes found in collection "${collection.name}": ${indexesToDelete.map((i) => i.name).join(", ")} | Delete the index or fix the collection definition`
1209
1210
  );
1210
1211
  }
@@ -1276,7 +1277,7 @@ function getSchema(options) {
1276
1277
  }
1277
1278
 
1278
1279
  // src/createCollection/wrapMethods.ts
1279
- var import_logger2 = require("@orion-js/logger");
1280
+ var import_logger3 = require("@orion-js/logger");
1280
1281
  function wrapMethods(collection) {
1281
1282
  const methodsWithPromises = [
1282
1283
  "findOne",
@@ -1312,7 +1313,7 @@ function wrapMethods(collection) {
1312
1313
  collection[methodName2] = (...args) => {
1313
1314
  collection.startConnection();
1314
1315
  if (!collection.rawCollection) {
1315
- import_logger2.logger.error("Method called before connection was initialized", {
1316
+ import_logger3.logger.error("Method called before connection was initialized", {
1316
1317
  collectionName: collection.name,
1317
1318
  connectionName: collection.connectionName,
1318
1319
  methodName: methodName2
@@ -1448,7 +1449,7 @@ function MongoCollection(options) {
1448
1449
  }
1449
1450
 
1450
1451
  // src/encrypted/getOrCreateEncryptionKey.ts
1451
- var import_logger3 = require("@orion-js/logger");
1452
+ var import_logger4 = require("@orion-js/logger");
1452
1453
  var import_mongodb3 = require("mongodb");
1453
1454
  async function getOrCreateEncryptionKey({
1454
1455
  keyAltName,
@@ -1460,7 +1461,7 @@ async function getOrCreateEncryptionKey({
1460
1461
  kmsProviders
1461
1462
  }) {
1462
1463
  const keyVaultNamespace = `${keyVaultDatabase}.${keyVaultCollection}`;
1463
- import_logger3.logger.info("Connecting to database to get or create the encryption key", {
1464
+ import_logger4.logger.info("Connecting to database to get or create the encryption key", {
1464
1465
  keyVaultNamespace,
1465
1466
  keyAltName
1466
1467
  });
@@ -1478,14 +1479,14 @@ async function getOrCreateEncryptionKey({
1478
1479
  });
1479
1480
  const key = await clientEncryption.getKeyByAltName(keyAltName);
1480
1481
  if (key) {
1481
- import_logger3.logger.info("Key found on the key vault", {
1482
+ import_logger4.logger.info("Key found on the key vault", {
1482
1483
  keyVaultNamespace,
1483
1484
  keyAltName,
1484
1485
  UUID: key._id
1485
1486
  });
1486
1487
  return { key: key._id, keyVaultNamespace };
1487
1488
  }
1488
- import_logger3.logger.info("Key not found on the key vault, creating a new one", {
1489
+ import_logger4.logger.info("Key not found on the key vault, creating a new one", {
1489
1490
  keyVaultNamespace,
1490
1491
  keyAltName
1491
1492
  });
@@ -1493,7 +1494,7 @@ async function getOrCreateEncryptionKey({
1493
1494
  keyAltNames: [keyAltName],
1494
1495
  ...masterKey ? { masterKey } : {}
1495
1496
  });
1496
- import_logger3.logger.info("New encryption key created", {
1497
+ import_logger4.logger.info("New encryption key created", {
1497
1498
  keyVaultNamespace,
1498
1499
  keyAltName,
1499
1500
  UUID: newKey
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/connect/connections.ts","../src/connect/getDBName.ts","../src/connect/getMongoURLFromEnv.ts","../src/connect/getMongoConnection.ts","../src/types/index.ts","../src/service/index.ts","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/isArray.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/isInteger.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/createPath.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/equals.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isType.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/compare.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/includes.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/omit.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/flatten.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isEmpty.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isNil.js","../src/createCollection/getMethods/getSelector.ts","../src/createCollection/getMethods/find.ts","../src/createCollection/getMethods/findOne.ts","../src/createCollection/getMethods/validateModifier/validatePush.ts","../src/helpers/fromDot.ts","../src/helpers/toDot.ts","../src/createCollection/getMethods/validateModifier/validateUnset.ts","../src/createCollection/getMethods/validateModifier/validateInc.ts","../src/createCollection/getMethods/validateModifier/validateSet.ts","../src/createCollection/getMethods/validateModifier/validateOperator.ts","../src/createCollection/getMethods/validateModifier/index.ts","../src/createCollection/getMethods/validateModifier/validateUpsert.ts","../src/createCollection/getMethods/cleanModifier.ts","../src/createCollection/getMethods/wrapErrors.ts","../src/createCollection/getMethods/upsert.ts","../src/createCollection/getMethods/findOneAndUpdate.ts","../src/createCollection/getMethods/updateOne.ts","../src/createCollection/getMethods/updateMany.ts","../src/createCollection/getMethods/updateAndFind.ts","../src/createCollection/getMethods/deleteOne.ts","../src/createCollection/getMethods/deleteMany.ts","../src/createCollection/getMethods/insertOne.ts","../src/createCollection/getMethods/insertMany.ts","../src/createCollection/getMethods/updateItem.ts","../src/createCollection/getMethods/countDocuments.ts","../src/createCollection/getMethods/estimatedDocumentCount.ts","../src/createCollection/getMethods/insertAndFind.ts","../src/createCollection/getMethods/dataLoader/loadById.ts","../src/createCollection/getMethods/dataLoader/loadMany.ts","../src/createCollection/getMethods/dataLoader/loadOne.ts","../src/createCollection/getMethods/dataLoader/loadData.ts","../src/createCollection/getMethods/dataLoader/dataLoad/getDataLoader.ts","../src/createCollection/getMethods/dataLoader/dataLoad/index.ts","../src/createCollection/generateId.ts","../src/createCollection/createIndexes.ts","../src/createCollection/getSchemaAndModel.ts","../src/createCollection/wrapMethods.ts","../src/createCollection/index.ts","../src/encrypted/getOrCreateEncryptionKey.ts"],"sourcesContent":["export * from './connect'\nexport * from './types'\nexport * from './service'\nexport * from './createCollection'\nexport * from './encrypted/getOrCreateEncryptionKey'\n","import {EventEmitter} from 'node:events'\nimport {MongoClient, Db, MongoClientOptions} from 'mongodb'\nimport getDBName from './getDBName'\nimport {nextTick} from 'node:process'\nimport {logger} from '@orion-js/logger'\nimport {sleep} from '@orion-js/helpers'\nimport {getMongoURLFromEnv} from './getMongoURLFromEnv'\n\nexport interface OrionMongoClient {\n client: MongoClient\n db: Db\n uri: string\n dbName: string\n /**\n * @deprecated Use startConnection() instead. This property is not guaranteed to be resolved if the connection is not started.\n * When using async calls startConnection or connectionPromise is no longer needed. Orion will automatically start the connection if it is not already started.\n * Kept for backwards compatibility. startConnection does not re-start the connection if it is already started, so it is safe to use.\n */\n connectionPromise: Promise<MongoClient>\n connectionName: string\n encrypted: {client: MongoClient; db: Db}\n /**\n * Starts the connection if it is not already started.\n * If the connection is already started, it resolves immediately.\n */\n startConnection: () => Promise<MongoClient>\n closeConnection: () => Promise<void>\n}\n\n// globalThis.myModuleMap ??= {}\nexport const connectionWrappers: {[key: string]: OrionMongoDatabaseWrapper} = {} //globalThis.myModuleMap\n\nclass OrionMongoDatabaseWrapper implements OrionMongoClient {\n uri: string\n dbName: string\n connectionName: string\n connectionPromise: Promise<MongoClient>\n private mongoOptions: MongoClientOptions\n private connectionEvent: EventEmitter = new EventEmitter()\n private state: 'disconnected' | 'connecting' | 'connected' | 'disconnecting' = 'disconnected'\n client: MongoClient\n db: Db\n configured = false\n readonly encrypted: {client: MongoClient; db: Db} = {client: null, db: null}\n readonly configTimeout: NodeJS.Timeout\n\n constructor(connectionName: string) {\n this.connectionName = connectionName\n logger.info('New connection requested', {\n connectionName,\n })\n\n this.connectionEvent.setMaxListeners(Number.POSITIVE_INFINITY)\n this.connectionPromise = new Promise((resolve, reject) => {\n if (this.state === 'connected') {\n resolve(this.client)\n }\n this.connectionEvent.once('connected', resolve)\n this.connectionEvent.once('error', reject)\n })\n this.configTimeout = setTimeout(() => {\n logger.error(\n 'Connection was required but never configured, call configureConnection() or unset the env variable MONGO_EXPLICIT_SETUP',\n {\n connectionName,\n },\n )\n this.connectionEvent.emit('error', new Error('Connection was required but never configured'))\n }, 30 * 1000)\n }\n\n config(mongoURL: string, mongoOptions: MongoClientOptions) {\n this.uri = mongoURL\n this.mongoOptions = mongoOptions\n this.configured = true\n if (this.mongoOptions?.autoEncryption) {\n this.encrypted.client = new MongoClient(mongoURL, {\n retryReads: true,\n ...this.mongoOptions,\n })\n this.encrypted.db = this.encrypted.client.db(getDBName(this.uri))\n }\n this.client = new MongoClient(mongoURL, {\n retryReads: true,\n ...this.mongoOptions,\n autoEncryption: null,\n })\n this.db = this.client.db(getDBName(this.uri))\n clearTimeout(this.configTimeout)\n }\n\n async awaitConnection() {\n if (this.state === 'connected') return this\n if (this.state === 'connecting' || !this.configured) {\n // Wait for the connection to be configured and established\n await this.connectionPromise\n return this\n }\n this.state = 'connecting'\n const censoredURI = this.uri.replace(/\\/\\/.*:.*@/, '//') // remove user and password from URL\n logger.info('Connecting to mongo', {\n uri: censoredURI,\n connectionName: this.connectionName,\n })\n if (this.encrypted.client) {\n await this.connectWithRetry(this.encrypted.client)\n logger.info('Successfully connected to encrypted mongo', {\n uri: censoredURI,\n connectionName: this.connectionName,\n })\n }\n await this.connectWithRetry(this.client)\n this.state = 'connected'\n this.connectionEvent.emit('connected', this.client)\n logger.info('Successfully connected to mongo', {\n uri: censoredURI,\n connectionName: this.connectionName,\n })\n nextTick(() => {\n this.connectionEvent.removeAllListeners()\n this.connectionEvent = null\n })\n return this\n }\n\n async connectWithRetry(client: MongoClient) {\n try {\n return await client.connect()\n } catch (error) {\n logger.error('Error connecting to mongo. Will retry in 5s', {\n error,\n connectionName: this.connectionName,\n })\n await sleep(5000)\n return this.connectWithRetry(client)\n }\n }\n\n async startConnection() {\n return this.awaitConnection().then(() => this.client)\n }\n\n async closeConnection() {\n if (this.state === 'disconnected' || this.state === 'disconnecting') return\n this.state = 'disconnecting'\n await this.client?.close()\n await this.encrypted?.client?.close()\n this.state = 'disconnected'\n }\n}\n\nexport function configureConnection(connectionName: string, mongoOptions: MongoClientOptions) {\n connectionWrappers[connectionName] =\n connectionWrappers[connectionName] || new OrionMongoDatabaseWrapper(connectionName)\n const connectionWrapper = connectionWrappers[connectionName]\n if (connectionWrapper.configured) {\n throw new Error('Connection already configured')\n }\n connectionWrapper.config(getMongoURLFromEnv(connectionName), mongoOptions)\n return connectionWrapper.awaitConnection()\n}\n\nexport function getExistingConnection(connectionName: string) {\n connectionWrappers[connectionName] =\n connectionWrappers[connectionName] || new OrionMongoDatabaseWrapper(connectionName)\n\n return connectionWrappers[connectionName]\n}\n\nexport const connections = connectionWrappers\n","export default function getDBName(url: string): string {\n let dbName = 'admin'\n let connectionPart = ''\n\n const startConnectionPart = url.indexOf('//') + 2\n\n if (url.indexOf('?') !== -1) {\n connectionPart = url.substring(startConnectionPart, url.indexOf('?'))\n } else {\n connectionPart = url.substring(startConnectionPart)\n }\n\n if (connectionPart.indexOf('.sock') !== -1) {\n if (connectionPart.indexOf('.sock/') !== -1) {\n dbName = connectionPart.split('.sock/')[1]\n }\n } else if (connectionPart.indexOf('/') !== -1) {\n dbName = connectionPart.split('/')[1]\n }\n\n return dbName\n}\n","import {internalGetEnv} from '@orion-js/env'\n\nexport const getMongoURLFromEnv = (connectionName: string): string => {\n if (connectionName === 'main') {\n if (!internalGetEnv('mongo_url', 'MONGO_URL')) {\n throw new Error('MONGO_URL is required')\n }\n return internalGetEnv('mongo_url', 'MONGO_URL')\n }\n\n const envName = `mongo_url_${connectionName.toLowerCase()}`\n const processEnvName = `MONGO_URL_${connectionName.toUpperCase()}`\n const uri = internalGetEnv(envName, processEnvName)\n if (!uri) {\n throw new Error(\n `To use the connection \"${connectionName}\" you must initialize it first calling getMongoConnection({name: \"${connectionName}\", uri: \"MONGOURI\"}) or setting the environment variable ${processEnvName}.`,\n )\n }\n\n return uri\n}\n\nexport const requiresExplicitSetup = (connectionName: string): boolean => {\n if (connectionName === 'main') {\n const value = internalGetEnv('mongo_explicit_setup', 'MONGO_EXPLICIT_SETUP')\n return typeof value === 'boolean' ? value : value === 'true'\n }\n\n const envName = `mongo_explicit_setup_${connectionName.toLowerCase()}`\n const processEnvName = `MONGO_EXPLICIT_SETUP_${connectionName.toUpperCase()}`\n const value = internalGetEnv(envName, processEnvName)\n return typeof value === 'boolean' ? value : value === 'true'\n}\n","import {getExistingConnection} from './connections'\nimport type {OrionMongoClient} from './connections'\nimport {getMongoURLFromEnv, requiresExplicitSetup} from './getMongoURLFromEnv'\nexport const allConnectionPromises = []\n\ninterface MongoConnectOptions {\n name: string\n uri?: string\n}\n\nexport const getMongoConnection = ({name, uri}: MongoConnectOptions): OrionMongoClient => {\n uri = uri || getMongoURLFromEnv(name)\n const connection = getExistingConnection(name)\n\n if (!connection.configured && !requiresExplicitSetup(name)) {\n connection.config(uri, {})\n }\n allConnectionPromises.push(connection.connectionPromise)\n return connection\n}\n","import * as MongoDB from 'mongodb'\nimport {\n FieldType,\n fieldTypes,\n InferSchemaType,\n Schema,\n SchemaInAnyOrionForm,\n StrictInferSchemaType,\n TypedSchemaOnSchema,\n} from '@orion-js/schema'\nimport {OrionMongoClient} from '../connect/connections'\nimport {EnhancedOmit} from 'mongodb'\n\nexport {MongoDB}\n\nexport type OptionalId<T> = MongoDB.OptionalId<T>\n\nexport declare type InferIdType<TSchema> = TSchema extends {\n _id: infer IdType\n}\n ? Record<any, never> extends IdType\n ? never\n : IdType\n : TSchema extends {\n _id?: infer IdType\n }\n ? unknown extends IdType\n ? string\n : IdType\n : string\n\nexport type DocumentWithId<TSchema> = EnhancedOmit<TSchema, '_id'> & {\n _id: InferIdType<TSchema>\n}\n\nexport type ModelClassBase = DocumentWithId<MongoDB.Document>\n\nexport interface CollectionIndex {\n keys: MongoDB.IndexSpecification\n options?: MongoDB.CreateIndexesOptions\n}\n\nexport namespace DataLoader {\n interface LoadDataOptionsBase<ModelClass extends ModelClassBase> {\n key: keyof ModelClass\n match?: MongoFilter<ModelClass>\n sort?: MongoDB.Sort\n project?: MongoDB.Document\n timeout?: number\n debug?: boolean\n }\n\n export interface LoadDataOptions<ModelClass extends ModelClassBase>\n extends LoadDataOptionsBase<ModelClass> {\n value?: any\n values?: Array<any>\n }\n\n export interface LoadOneOptions<ModelClass extends ModelClassBase>\n extends LoadDataOptionsBase<ModelClass> {\n value: any\n }\n\n export type LoadData<ModelClass extends ModelClassBase> = (\n options: LoadDataOptions<ModelClass>,\n ) => Promise<Array<ModelClass>>\n export type LoadOne<ModelClass extends ModelClassBase> = (\n options: LoadOneOptions<ModelClass>,\n ) => Promise<ModelClass>\n export type LoadMany<ModelClass extends ModelClassBase> = (\n options: LoadDataOptions<ModelClass>,\n ) => Promise<Array<ModelClass>>\n export type LoadById<ModelClass extends ModelClassBase> = (\n id: ModelClass['_id'],\n ) => Promise<ModelClass>\n}\n\nexport type MongoFilter<ModelClass extends ModelClassBase = ModelClassBase> =\n MongoDB.Filter<ModelClass>\n\nexport type MongoSelector<ModelClass extends ModelClassBase = ModelClassBase> =\n | ModelClass['_id']\n | MongoFilter<ModelClass>\n\nexport interface FindCursor<ModelClass> extends MongoDB.FindCursor {\n toArray: () => Promise<Array<ModelClass>>\n}\n\nexport interface UpdateOptions {\n clean?: boolean\n validate?: boolean\n mongoOptions?: MongoDB.UpdateOptions\n}\n\nexport interface FindOneAndUpdateUpdateOptions {\n clean?: boolean\n validate?: boolean\n mongoOptions?: MongoDB.FindOneAndUpdateOptions\n}\n\nexport interface InsertOptions {\n clean?: boolean\n validate?: boolean\n mongoOptions?: MongoDB.InsertOneOptions\n}\n\nexport interface InsertManyOptions {\n clean?: boolean\n validate?: boolean\n mongoOptions?: MongoDB.BulkWriteOptions\n}\n\nexport type InitItem<ModelClass extends ModelClassBase> = (doc: any) => ModelClass\n\nexport type ModelToMongoSelector<ModelClass extends ModelClassBase> =\n | MongoDB.Filter<ModelClass>\n | DocumentWithId<ModelClass>['_id']\n\nexport type FindOne<ModelClass extends ModelClassBase> = (\n selector?: ModelToMongoSelector<ModelClass>,\n options?: MongoDB.FindOptions<ModelClass>,\n) => Promise<ModelClass>\n\nexport type Find<ModelClass extends ModelClassBase> = (\n selector?: ModelToMongoSelector<ModelClass>,\n options?: MongoDB.FindOptions<ModelClass>,\n) => FindCursor<ModelClass>\n\nexport type FindOneAndUpdate<ModelClass extends ModelClassBase> = <\n TSelector extends ModelToMongoSelector<ModelClass>,\n TFilter extends MongoDB.UpdateFilter<ModelClass>,\n TOptions extends FindOneAndUpdateUpdateOptions,\n>(\n selector: TSelector,\n modifier: TFilter,\n options?: TOptions,\n) => ReturnType<MongoDB.Collection<ModelClass>['findOneAndUpdate']>\n\nexport type UpdateAndFind<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n modifier: MongoDB.UpdateFilter<ModelClass>,\n options?: FindOneAndUpdateUpdateOptions,\n) => Promise<ModelClass>\n\nexport type UpdateItem<ModelClass extends ModelClassBase> = (\n item: ModelClass,\n modifier: MongoDB.UpdateFilter<ModelClass>,\n options?: FindOneAndUpdateUpdateOptions,\n) => Promise<void>\n\nexport type InsertOne<ModelClass extends ModelClassBase> = (\n doc: MongoDB.OptionalId<ModelClass>,\n options?: InsertOptions,\n) => Promise<ModelClass['_id']>\n\nexport type InsertMany<ModelClass extends ModelClassBase> = (\n doc: Array<MongoDB.OptionalId<ModelClass>>,\n options?: InsertManyOptions,\n) => Promise<Array<ModelClass['_id']>>\n\nexport type InsertAndFind<ModelClass extends ModelClassBase> = (\n doc: MongoDB.OptionalId<ModelClass>,\n options?: InsertOptions,\n) => Promise<ModelClass>\n\nexport type DeleteMany<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n options?: MongoDB.DeleteOptions,\n) => Promise<MongoDB.DeleteResult>\n\nexport type DeleteOne<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n options?: MongoDB.DeleteOptions,\n) => Promise<MongoDB.DeleteResult>\n\nexport type UpdateOne<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n modifier: MongoDB.UpdateFilter<ModelClass>,\n options?: UpdateOptions,\n) => Promise<MongoDB.UpdateResult>\n\nexport type UpdateMany<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n modifier: MongoDB.UpdateFilter<ModelClass>,\n options?: UpdateOptions,\n) => Promise<MongoDB.UpdateResult | MongoDB.Document>\n\nexport type Upsert<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n modifier: MongoDB.UpdateFilter<ModelClass>,\n options?: UpdateOptions,\n) => Promise<MongoDB.UpdateResult>\n\nexport interface CreateCollectionOptions<ModelClass extends ModelClassBase = ModelClassBase> {\n /**\n * The name of the collection on the Mongo Database\n */\n name: string\n /**\n * The name of the connection to use. The Mongo URL of this connection will be search on env variables.\n * If not found, the connection url will be `env.mongo_url`\n * If defined, the connection url will be `env.mongo_url_${name}`\n */\n connectionName?: string\n /**\n * The schema used for cleaning and validation of the documents\n */\n schema?: SchemaInAnyOrionForm\n /**\n * The indexes to use\n */\n indexes?: Array<CollectionIndex>\n /**\n * Select between random id generation o mongo (time based) id generation\n */\n idGeneration?: 'mongo' | 'random' | 'uuid'\n /**\n * ID prefix. idGeneration will be forced to random. Recommended for type checking\n */\n idPrefix?: ModelClass['_id']\n}\n\nexport type EstimatedDocumentCount<_ModelClass extends ModelClassBase> = (\n options?: MongoDB.EstimatedDocumentCountOptions,\n) => Promise<number>\n\nexport type CountDocuments<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n options?: MongoDB.CountDocumentsOptions,\n) => Promise<number>\n\nexport type SchemaWithRequiredId = Schema & {_id: {type: any}}\n\nexport type InferSchemaTypeWithId<TSchema extends SchemaWithRequiredId> = DocumentWithId<\n StrictInferSchemaType<TSchema>\n>\n\nexport type CreateCollectionOptionsWithSchemaType<T extends SchemaWithRequiredId> = {\n schema: T\n} & Omit<CreateCollectionOptions<InferSchemaTypeWithId<T>>, 'schema'>\n\nexport type CreateCollectionOptionsWithTypedSchema<\n T extends TypedSchemaOnSchema & {prototype: {_id: string}},\n> = {\n schema: T\n} & Omit<CreateCollectionOptions<InferSchemaType<T>>, 'schema'>\n\nexport class BaseCollection<ModelClass extends ModelClassBase = ModelClassBase> {\n name: string\n connectionName?: string\n schema?: Schema\n generateId: () => ModelClass['_id']\n getSchema: () => Schema\n\n db: MongoDB.Db\n client: OrionMongoClient\n /**\n * @deprecated Use getRawCollection() instead. This property is not guaranteed to be defined if the connection has not been started.\n */\n rawCollection: MongoDB.Collection<ModelClass>\n getRawCollection: () => Promise<MongoDB.Collection<ModelClass>>\n\n findOne: FindOne<ModelClass>\n find: Find<ModelClass>\n\n insertOne: InsertOne<ModelClass>\n insertMany: InsertMany<ModelClass>\n insertAndFind: InsertAndFind<ModelClass>\n\n deleteMany: DeleteMany<ModelClass>\n deleteOne: DeleteOne<ModelClass>\n\n updateOne: UpdateOne<ModelClass>\n updateMany: UpdateMany<ModelClass>\n\n upsert: Upsert<ModelClass>\n findOneAndUpdate: FindOneAndUpdate<ModelClass>\n\n /**\n * Updates a document and returns the updated document with the changes\n */\n updateAndFind: UpdateAndFind<ModelClass>\n updateItem: UpdateItem<ModelClass>\n\n estimatedDocumentCount: EstimatedDocumentCount<ModelClass>\n countDocuments: CountDocuments<ModelClass>\n\n aggregate: <T = MongoDB.Document>(\n pipeline?: MongoDB.Document[],\n options?: MongoDB.AggregateOptions,\n ) => MongoDB.AggregationCursor<T>\n watch: <T = MongoDB.Document>(\n pipeline?: MongoDB.Document[],\n options?: MongoDB.ChangeStreamOptions,\n ) => MongoDB.ChangeStream<T>\n\n loadData: DataLoader.LoadData<ModelClass>\n loadOne: DataLoader.LoadOne<ModelClass>\n loadMany: DataLoader.LoadMany<ModelClass>\n loadById: DataLoader.LoadById<ModelClass>\n\n /**\n * Use this function if you are using tests and you pass the\n * env var DONT_CREATE_INDEXES_AUTOMATICALLY and you need to\n * create the indexes for this collection\n */\n createIndexes: () => Promise<string[]>\n createIndexesPromise: Promise<string[]>\n /**\n * @deprecated Use startConnection() instead. This property is not guaranteed to be resolved if the connection is not started.\n * When using async calls startConnection or connectionPromise is no longer needed. Orion will automatically start the connection if it is not already started.\n * Kept for backwards compatibility. startConnection does not re-start the connection if it is already started, so it is safe to use.\n */\n connectionPromise: Promise<MongoDB.MongoClient>\n startConnection: () => Promise<MongoDB.MongoClient>\n}\n\nexport class Collection<\n ModelClass extends ModelClassBase = ModelClassBase,\n> extends BaseCollection<ModelClass> {\n indexes: Array<CollectionIndex>\n encrypted?: BaseCollection<ModelClass>\n}\n\nexport type DistinctDocumentId<DistinctId extends string> = string & {\n __TYPE__: `DistinctDocumentId<${DistinctId}>`\n}\n\nexport type TypedId<TPrefix extends string> = `${TPrefix}-${string}`\n\n/**\n * Use this function to create unique types for the ids of mongodb documents.\n * You should set it as the type of the _id field in your schema.\n *\n * @example\n * ```ts\n * type UserId = TypedId<'user'>\n *\n * const userSchema = {\n * _id: {\n * type: TypedId('user'),\n * },\n * }\n *\n * ```\n */\nexport function typedId<const TPrefix extends string>(\n prefix: TPrefix,\n): FieldType<TypedId<TPrefix>> {\n return {\n ...fieldTypes.string,\n name: `typedId:${prefix}`,\n toSerializedType: async () => 'string',\n } as any\n}\n","import {Service} from '@orion-js/services'\nimport {createCollection} from '../createCollection'\nimport {CreateCollectionOptions, ModelClassBase} from '../types'\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string}>()\n\nexport function Repository() {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n\n context.addInitializer(function (this) {\n serviceMetadata.set(this, {_serviceType: 'repo'})\n })\n }\n}\n\nexport function MongoCollection<ModelClass extends ModelClassBase = ModelClassBase>(\n options: CreateCollectionOptions<ModelClass>,\n) {\n return (_target: any, context: ClassFieldDecoratorContext) => {\n const propertyKey = String(context.name)\n context.addInitializer(function (this) {\n const repo = serviceMetadata.get(this.constructor)\n if (!repo || repo._serviceType !== 'repo') {\n throw new Error(\n 'You must pass a class decorated with @Repository if you want to use @MongoCollection',\n )\n }\n\n const collection = createCollection(options)\n this[propertyKey] = collection\n })\n }\n}\n","export function type(input){\n if (input === null){\n return 'Null'\n } else if (input === undefined){\n return 'Undefined'\n } else if (Number.isNaN(input)){\n return 'NaN'\n }\n const typeResult = Object.prototype.toString.call(input).slice(8, -1)\n\n return typeResult === 'AsyncFunction' ? 'Promise' : typeResult\n}\n","export const { isArray } = Array\n","function _isInteger(n){\n return n << 0 === n\n}\n\nexport const isInteger = Number.isInteger || _isInteger\n\n/**\n * Check if `index` is integer even if it is a string.\n */\nexport const isIndexInteger = index => Number.isInteger(Number(index))\n","import { isInteger } from './isInteger.js'\n\nexport function createPath(path, delimiter = '.'){\n return typeof path === 'string' ?\n path.split(delimiter).map(x => isInteger(x) ? Number(x) : x) :\n path\n}\n","import { isArray } from './_internals/isArray.js'\nimport { type } from './type.js'\n\nexport function _lastIndexOf(valueToFind, list){\n if (!isArray(list))\n throw new Error(`Cannot read property 'indexOf' of ${ list }`)\n\n const typeOfValue = type(valueToFind)\n if (![ 'Array', 'NaN', 'Object', 'RegExp' ].includes(typeOfValue))\n return list.lastIndexOf(valueToFind)\n\n const { length } = list\n let index = length\n let foundIndex = -1\n\n while (--index > -1 && foundIndex === -1)\n if (equals(list[ index ], valueToFind))\n foundIndex = index\n\n return foundIndex\n}\n\nexport function _indexOf(valueToFind, list){\n if (!isArray(list))\n throw new Error(`Cannot read property 'indexOf' of ${ list }`)\n\n const typeOfValue = type(valueToFind)\n if (![ 'Array', 'NaN', 'Object', 'RegExp' ].includes(typeOfValue))\n return list.indexOf(valueToFind)\n\n let index = -1\n let foundIndex = -1\n const { length } = list\n\n while (++index < length && foundIndex === -1)\n if (equals(list[ index ], valueToFind))\n foundIndex = index\n\n return foundIndex\n}\n\nfunction _arrayFromIterator(iter){\n const list = []\n let next\n while (!(next = iter.next()).done)\n list.push(next.value)\n\n return list\n}\n\nfunction _compareSets(a, b){\n if (a.size !== b.size)\n return false\n\n const aList = _arrayFromIterator(a.values())\n const bList = _arrayFromIterator(b.values())\n\n const filtered = aList.filter(aInstance => _indexOf(aInstance, bList) === -1)\n\n return filtered.length === 0\n}\n\nfunction compareErrors(a, b){\n if (a.message !== b.message) return false\n if (a.toString !== b.toString) return false\n\n return a.toString() === b.toString()\n}\n\nfunction parseDate(maybeDate){\n if (!maybeDate.toDateString) return [ false ]\n\n return [ true, maybeDate.getTime() ]\n}\n\nfunction parseRegex(maybeRegex){\n if (maybeRegex.constructor !== RegExp) return [ false ]\n\n return [ true, maybeRegex.toString() ]\n}\n\nexport function equals(a, b){\n if (arguments.length === 1) return _b => equals(a, _b)\n\n if (Object.is(a, b)) return true\n\n const aType = type(a)\n\n if (aType !== type(b)) return false\n if (aType === 'Function')\n return a.name === undefined ? false : a.name === b.name\n\n if ([ 'NaN', 'Null', 'Undefined' ].includes(aType)) return true\n\n if ([ 'BigInt', 'Number' ].includes(aType)){\n if (Object.is(-0, a) !== Object.is(-0, b)) return false\n\n return a.toString() === b.toString()\n }\n\n if ([ 'Boolean', 'String' ].includes(aType))\n return a.toString() === b.toString()\n\n if (aType === 'Array'){\n const aClone = Array.from(a)\n const bClone = Array.from(b)\n\n if (aClone.toString() !== bClone.toString())\n return false\n\n let loopArrayFlag = true\n aClone.forEach((aCloneInstance, aCloneIndex) => {\n if (loopArrayFlag)\n if (\n aCloneInstance !== bClone[ aCloneIndex ] &&\n !equals(aCloneInstance, bClone[ aCloneIndex ])\n )\n loopArrayFlag = false\n\n })\n\n return loopArrayFlag\n }\n\n const aRegex = parseRegex(a)\n const bRegex = parseRegex(b)\n\n if (aRegex[ 0 ])\n return bRegex[ 0 ] ? aRegex[ 1 ] === bRegex[ 1 ] : false\n else if (bRegex[ 0 ]) return false\n\n const aDate = parseDate(a)\n const bDate = parseDate(b)\n\n if (aDate[ 0 ])\n return bDate[ 0 ] ? aDate[ 1 ] === bDate[ 1 ] : false\n else if (bDate[ 0 ]) return false\n\n if (a instanceof Error){\n if (!(b instanceof Error)) return false\n\n return compareErrors(a, b)\n }\n\n if (aType === 'Set')\n return _compareSets(a, b)\n\n if (aType === 'Object'){\n const aKeys = Object.keys(a)\n\n if (aKeys.length !== Object.keys(b).length)\n return false\n\n let loopObjectFlag = true\n aKeys.forEach(aKeyInstance => {\n if (loopObjectFlag){\n const aValue = a[ aKeyInstance ]\n const bValue = b[ aKeyInstance ]\n\n if (aValue !== bValue && !equals(aValue, bValue))\n loopObjectFlag = false\n\n }\n })\n\n return loopObjectFlag\n }\n\n return false\n}\n","import { type } from './type.js'\n\nexport function isType(xType, x){\n if (arguments.length === 1){\n return xHolder => isType(xType, xHolder)\n }\n\n return type(x) === xType\n}\n","export function compare(a, b){\n return String(a) === String(b)\n}\n","import { compare } from './compare.js'\n\nexport function includes(a, list){\n let index = -1\n const { length } = list\n\n while (++index < length)\n if (compare(list[ index ], a))\n return true\n\n return false\n}\n","import { createPath } from './_internals/createPath.js'\nimport { includes } from './_internals/includes.js'\n\nexport function omit(propsToOmit, obj){\n if (arguments.length === 1) return _obj => omit(propsToOmit, _obj)\n\n if (obj === null || obj === undefined)\n return undefined\n\n const propsToOmitValue = createPath(propsToOmit, ',')\n const willReturn = {}\n\n for (const key in obj)\n if (!includes(key, propsToOmitValue))\n willReturn[ key ] = obj[ key ]\n\n return willReturn\n}\n","import { isArray } from './_internals/isArray.js'\n\nexport function flatten(list, input){\n const willReturn = input === undefined ? [] : input\n\n for (let i = 0; i < list.length; i++){\n if (isArray(list[ i ])){\n flatten(list[ i ], willReturn)\n } else {\n willReturn.push(list[ i ])\n }\n }\n\n return willReturn\n}\n","import { type } from './type.js'\n\nexport function isEmpty(input){\n const inputType = type(input)\n if ([ 'Undefined', 'NaN', 'Number', 'Null' ].includes(inputType))\n return false\n if (!input) return true\n\n if (inputType === 'Object'){\n return Object.keys(input).length === 0\n }\n\n if (inputType === 'Array'){\n return input.length === 0\n }\n\n return false\n}\n","export function isNil(x){\n return x === undefined || x === null\n}\n","import {type} from 'rambdax'\nimport {Filter} from 'mongodb'\nimport {ModelClassBase, ModelToMongoSelector} from '../../types'\n\nexport default function getSelector<ModelClass extends ModelClassBase>(\n args: IArguments | any[],\n): Filter<ModelClass> {\n if (args.length === 0) return {}\n\n const selector = args[0] as ModelToMongoSelector<ModelClass>\n\n if (typeof selector === 'string') {\n return {_id: selector} as Filter<ModelClass>\n }\n\n if (type(selector) === 'Object') {\n return selector as Filter<ModelClass>\n }\n\n return {\n _id: 'shouldReturnNull',\n } as Filter<ModelClass>\n}\n","import {Collection, Find, ModelClassBase} from '../../types'\nimport getSelector from './getSelector'\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const find: Find<DocumentType> = (...args: any[]) => {\n const selector = getSelector(args)\n const options = args[1]\n\n return collection.rawCollection.find(selector, options) as any\n }\n\n return find\n}\n","import getSelector from './getSelector'\nimport {Collection, FindOne, ModelClassBase} from '../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const findOne: FindOne<DocumentType> = async (...args: any[]) => {\n const options = args[1]\n await collection.connectionPromise\n const selector = getSelector<DocumentType>(args)\n const item = (await collection.rawCollection.findOne(selector, options)) as DocumentType\n\n if (!item) return item\n return item\n }\n\n return findOne\n}\n","import {validate} from '@orion-js/schema'\nimport fromDot from '../../../helpers/fromDot'\n\n/**\n * Validates $push and $addToSet\n */\nexport default async function ({schema, operationDoc, operation}) {\n for (const key of Object.keys(operationDoc)) {\n const value = operationDoc[key]\n let toValidate = null\n if (operation === '$push' || operation === '$addToSet') {\n if (typeof value === 'object' && '$each' in value) {\n toValidate = value.$each\n } else {\n toValidate = [value]\n }\n }\n const validationObject = fromDot({[key]: toValidate})\n await validate(schema, validationObject, {omitRequired: true})\n }\n}\n","import dot from 'dot-object'\nimport toDot from './toDot'\n\nexport default function fromDot(doc: any): any {\n doc = toDot(doc)\n return dot.object(doc)\n}\n","import Dot from 'dot-object'\n\nvar dot = new Dot('.', false, true, false)\n\nexport default function (doc) {\n return dot.dot(doc)\n}\n","import {validateKey, ValidationError} from '@orion-js/schema'\n\n/**\n * Validates $unset\n */\nexport default async function ({schema, operationDoc}) {\n const errors = {}\n for (const key of Object.keys(operationDoc)) {\n const error = await validateKey(schema, key, null)\n if (error) {\n errors[key] = error\n }\n }\n if (Object.keys(errors).length) {\n throw new ValidationError(errors)\n }\n}\n","import {validateKey, ValidationError} from '@orion-js/schema'\n\n/**\n * Validates $inc\n */\nexport default async function ({schema, operationDoc}) {\n const errors = {}\n for (const key of Object.keys(operationDoc)) {\n const value = operationDoc[key]\n const error = await validateKey(schema, key, value)\n if (error) {\n errors[key] = error\n }\n }\n if (Object.keys(errors).length) {\n throw new ValidationError(errors)\n }\n}\n","import {validate} from '@orion-js/schema'\nimport fromDot from '../../../helpers/fromDot'\nimport toDot from '../../../helpers/toDot'\n\n/**\n * Validates $set\n */\nexport default async function ({schema, operationDoc}) {\n let cleaned = toDot(operationDoc)\n\n const transformedObj = {}\n Object.keys(cleaned).map(key => {\n const newKey = key.replace('$.', '0.')\n transformedObj[newKey] = cleaned[key]\n })\n\n cleaned = fromDot(transformedObj)\n\n await validate(schema, cleaned, {omitRequired: true})\n}\n","import validatePush from './validatePush'\nimport validateUnset from './validateUnset'\nimport validateInc from './validateInc'\nimport validateSet from './validateSet'\n\nconst shouldCheck = function (key: string): boolean {\n if (key === '$pushAll') throw new Error('$pushAll is not supported, use $push + $each')\n return ['$pull', '$pullAll', '$pop', '$slice'].indexOf(key) === -1\n}\n\nexport default async function ({schema, operationDoc, operation}) {\n if (!shouldCheck(operation)) return\n\n if (operation === '$set') {\n await validateSet({schema, operationDoc})\n } else if (operation === '$unset') {\n await validateUnset({schema, operationDoc})\n } else if (operation === '$inc') {\n await validateInc({schema, operationDoc})\n } else if (operation === '$push' || operation === '$addToSet') {\n await validatePush({schema, operationDoc, operation})\n } else {\n throw new Error(operation + ' operation is not supported yet')\n }\n}\n","// inspired by https://github.com/aldeed/simple-schema-js\nimport validateOperator from './validateOperator'\n\nexport default async function validateModifier(schema, modifier) {\n for (const operation of Object.keys(modifier)) {\n const operationDoc = modifier[operation]\n // If non-operators are mixed in, throw error\n if (operation.slice(0, 1) !== '$') {\n throw new Error(`Expected '${operation}' to be a modifier operator like '$set'`)\n }\n\n await validateOperator({schema, operationDoc, operation})\n }\n}\n","import validateModifier from './index'\nimport {validate} from '@orion-js/schema'\nimport {omit} from 'rambdax'\nimport fromDot from '../../../helpers/fromDot'\n\nconst getPushSimulation = $push => {\n if (!$push) return {}\n const simulation = {}\n for (const key of Object.keys($push)) {\n const value = $push[key]\n if (typeof value === 'object' && '$each' in value) {\n simulation[key] = value.$each\n } else {\n simulation[key] = [value]\n }\n }\n return simulation\n}\n\nconst simulateNewDoc = (selector, modifier) =>\n fromDot({\n ...selector,\n ...modifier.$set,\n ...modifier.$inc,\n ...getPushSimulation(modifier.$push),\n ...getPushSimulation(modifier.$addToSet),\n ...modifier.$setOnInsert,\n })\n\nconst validateNewDoc = async (schema, selector, modifier) => {\n const doc = simulateNewDoc(selector, modifier)\n await validate(schema, doc)\n}\n\nexport default async function (schema, selector, modifier) {\n await validateNewDoc(schema, selector, modifier)\n await validateModifier(schema, omit(['$setOnInsert'], modifier))\n}\n","import {cleanKey, clean} from '@orion-js/schema'\nimport {isEmpty, isNil, equals} from 'rambdax'\nimport * as MongoDB from 'mongodb'\nimport fromDot from '../../helpers/fromDot'\nimport {ModelClassBase} from '../../types'\n\nconst shouldCheck = key => {\n if (key === '$pushAll') throw new Error('$pushAll is not supported; use $push + $each')\n return ['$pull', '$pullAll', '$pop', '$slice'].indexOf(key) === -1\n}\n\nexport default async function cleanModifier<\n ModelClass extends ModelClassBase,\n TFilter extends MongoDB.UpdateFilter<ModelClass>,\n>(schema, modifier: TFilter, {isUpsert} = {isUpsert: false}) {\n const cleanedModifier: MongoDB.UpdateFilter<MongoDB.Document> = {}\n for (const operation of Object.keys(modifier)) {\n const operationDoc = modifier[operation]\n cleanedModifier[operation] = {}\n // If non-operators are mixed in, throw error\n if (operation.slice(0, 1) !== '$') {\n throw new Error(`Expected '${operation}' to be a modifier operator like '$set'`)\n }\n if (!shouldCheck(operation)) {\n cleanedModifier[operation] = operationDoc\n continue\n }\n\n for (const key of Object.keys(operationDoc)) {\n const value = operationDoc[key]\n const cleanOptions = {forceDoc: operationDoc}\n\n let cleaned = null\n if (operation === '$push' || operation === '$addToSet') {\n if (typeof value === 'object' && '$each' in value) {\n const $each = await cleanKey(schema, key, value.$each, cleanOptions)\n cleaned = {...value, $each}\n } else {\n cleaned = await cleanKey(schema, `${key}.0`, value, cleanOptions)\n }\n }\n\n if (operation === '$set') {\n cleaned = await cleanKey(schema, key, value, cleanOptions)\n }\n\n if (operation === '$setOnInsert') {\n cleaned = await cleanKey(schema, key, value, cleanOptions)\n }\n\n if (operation === '$inc') {\n cleaned = await cleanKey(schema, key, value, cleanOptions)\n }\n\n if (operation === '$unset') {\n const isPresent = await cleanKey(schema, key, 'anyvalue', cleanOptions)\n cleaned = !isNil(isPresent) ? '' : null\n }\n\n if (cleaned !== undefined) {\n cleanedModifier[operation][key] = cleaned\n }\n }\n\n if (isEmpty(cleanedModifier[operation])) {\n delete cleanedModifier[operation]\n }\n }\n\n if (isUpsert) {\n const cleanedSetOnInsert = await clean(schema, fromDot(cleanedModifier.$setOnInsert || {}))\n\n if (!isEmpty(cleanedSetOnInsert)) {\n cleanedModifier.$setOnInsert = cleanedSetOnInsert\n }\n }\n\n if (equals(cleanedModifier, {})) {\n throw new Error('After cleaning your modifier is empty')\n }\n\n return cleanedModifier as TFilter\n}\n","import {ValidationError} from '@orion-js/schema'\n\nexport const wrapErrors = async <TFunc extends () => Promise<any>>(\n operation: TFunc,\n): Promise<ReturnType<TFunc>> => {\n try {\n return await operation()\n } catch (error) {\n if (error.code === 11000) {\n const regex = /index: (?:.*\\.)?\\$?(?:([_a-z0-9]*)(?:_\\d*)|([_a-z0-9]*))\\s*dup key/i\n const match = error.message.match(regex)\n\n if (!match) {\n throw new ValidationError({\n unknownKey: 'notUnique',\n })\n }\n\n const indexNameText = match[1] || match[2]\n const names = indexNameText.split(/_[_a-z0-9]_/)\n const errors = {}\n for (const name of names) {\n errors[name] = 'notUnique'\n }\n\n throw new ValidationError(errors)\n }\n\n throw error\n }\n}\n","import getSelector from './getSelector'\nimport validateUpsert from './validateModifier/validateUpsert'\nimport cleanModifier from './cleanModifier'\nimport {Collection, ModelClassBase, Upsert} from '../../types'\nimport {wrapErrors} from './wrapErrors'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const upsert: Upsert<DocumentType> = async function (selectorArg, modifierArg, options = {}) {\n await collection.connectionPromise\n let modifier = modifierArg as any\n let selector = getSelector(arguments)\n\n modifier.$setOnInsert = {...modifier.$setOnInsert, _id: collection.generateId()}\n\n if (collection.schema) {\n const schema = collection.getSchema()\n\n if (options.clean !== false) {\n selector = (await cleanModifier(schema, {$set: selector})).$set\n modifier = await cleanModifier(schema, modifier, {isUpsert: true})\n }\n if (options.validate !== false) await validateUpsert(schema, selector, modifier)\n }\n\n const result = await wrapErrors(() => {\n return collection.rawCollection.updateOne(selector, modifier, {\n ...options.mongoOptions,\n upsert: true,\n })\n })\n\n return result\n }\n\n return upsert\n}\n","import getSelector from './getSelector'\nimport validateModifier from './validateModifier'\nimport cleanModifier from './cleanModifier'\nimport {Collection, FindOneAndUpdate, ModelClassBase} from '../../types'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const findOneAndUpdate: FindOneAndUpdate<DocumentType> = async (selector, modifier, options) => {\n await collection.connectionPromise\n const finalSelector = getSelector<DocumentType>([selector])\n\n if (!modifier) {\n throw new Error('Modifier is required when making an update')\n }\n\n if (collection.schema) {\n const schema = collection.getSchema()\n modifier = options?.clean !== false ? await cleanModifier(schema, modifier) : modifier\n if (options?.validate !== false) await validateModifier(schema, modifier)\n }\n\n const result = await collection.rawCollection.findOneAndUpdate(\n finalSelector,\n modifier,\n options?.mongoOptions,\n )\n\n if (!result) return null\n return result\n }\n\n return findOneAndUpdate\n}\n","import getSelector from './getSelector'\nimport {Collection, ModelClassBase, UpdateOne} from '../../types'\nimport cleanModifier from './cleanModifier'\nimport validateModifier from './validateModifier'\nimport {wrapErrors} from './wrapErrors'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const updateOne: UpdateOne<DocumentType> = async function (\n selectorArg,\n modifierArg,\n options = {},\n ) {\n await collection.connectionPromise\n let modifier = modifierArg as any\n const selector = getSelector(arguments)\n\n if (!modifier) {\n throw new Error('Modifier is required when making an update')\n }\n\n if (collection.schema) {\n const schema = collection.getSchema()\n modifier = options.clean !== false ? await cleanModifier(schema, modifier) : modifier\n if (options.validate !== false) await validateModifier(schema, modifier)\n }\n\n const result = await wrapErrors(() => {\n return collection.rawCollection.updateOne(selector, modifier, options.mongoOptions)\n })\n\n return result\n }\n\n return updateOne\n}\n","import getSelector from './getSelector'\nimport {Collection, ModelClassBase, UpdateMany} from '../../types'\nimport cleanModifier from './cleanModifier'\nimport validateModifier from './validateModifier'\nimport {wrapErrors} from './wrapErrors'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const updateMany: UpdateMany<DocumentType> = async function (\n selectorArg,\n modifierArg,\n options = {},\n ) {\n await collection.connectionPromise\n let modifier = modifierArg as any\n const selector = getSelector(arguments)\n\n if (!modifier) {\n throw new Error('Modifier is required when making an update')\n }\n\n if (collection.schema) {\n const schema = collection.getSchema()\n modifier = options.clean !== false ? await cleanModifier(schema, modifier) : modifier\n if (options.validate !== false) await validateModifier(schema, modifier)\n }\n\n const result = await wrapErrors(() => {\n return collection.rawCollection.updateMany(selector, modifier, options.mongoOptions)\n })\n\n return result\n }\n\n return updateMany\n}\n","import {Collection, ModelClassBase, UpdateAndFind} from '../../types'\nimport getSelector from './getSelector'\nimport {wrapErrors} from './wrapErrors'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const updateAndFind: UpdateAndFind<DocumentType> = async function (\n selector,\n modifier,\n options = {},\n ) {\n await collection.connectionPromise\n return await wrapErrors(async () => {\n return await collection.findOneAndUpdate(selector, modifier, {\n ...options,\n mongoOptions: {\n ...options.mongoOptions,\n returnDocument: 'after',\n },\n })\n })\n }\n return updateAndFind\n}\n","import getSelector from './getSelector'\nimport {Collection, DeleteOne, ModelClassBase} from '../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const func: DeleteOne<DocumentType> = async function (selectorArg, options) {\n await collection.connectionPromise\n const selector = getSelector(arguments)\n const result = await collection.rawCollection.deleteOne(selector, options)\n\n return result\n }\n\n return func\n}\n","import getSelector from './getSelector'\nimport {Collection, DeleteMany, ModelClassBase} from '../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const func: DeleteMany<DocumentType> = async function (selectorArg, options) {\n await collection.connectionPromise\n const selector = getSelector(arguments)\n const result = await collection.rawCollection.deleteMany(selector, options)\n\n return result\n }\n\n return func\n}\n","import {Collection, InsertOne, ModelClassBase} from '../../types'\nimport fromDot from '../../helpers/fromDot'\nimport {clean, validate} from '@orion-js/schema'\nimport {wrapErrors} from './wrapErrors'\nimport {isType} from 'rambdax'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const insertOne: InsertOne<DocumentType> = async (insertDoc, options = {}) => {\n await collection.connectionPromise\n let doc = insertDoc as DocumentType\n if (!doc || !isType('Object', doc)) {\n throw new Error('Insert must receive a document')\n }\n\n if (!doc._id) {\n doc._id = collection.generateId()\n }\n\n if (collection.schema) {\n const schema = collection.getSchema()\n doc = await clean(schema, fromDot(doc))\n await validate(schema, doc)\n }\n\n await wrapErrors(async () => {\n await collection.rawCollection.insertOne(doc, options.mongoOptions)\n })\n\n return doc._id\n }\n\n return insertOne\n}\n","import {type} from 'rambdax'\nimport {clone} from '@orion-js/helpers'\nimport {Collection, InsertMany, ModelClassBase} from '../../types'\nimport * as MongoDB from 'mongodb'\nimport fromDot from '../../helpers/fromDot'\nimport {clean, validate} from '@orion-js/schema'\nimport {wrapErrors} from './wrapErrors'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const insertMany: InsertMany<DocumentType> = async (docs, options = {}) => {\n await collection.connectionPromise\n for (let index = 0; index < docs.length; index++) {\n let doc = clone(docs[index]) as any\n\n if (!doc || type(doc) !== 'Object') {\n throw new Error(`Item at index ${index} is not a document`)\n }\n\n if (!doc._id) {\n doc._id = collection.generateId()\n }\n\n if (collection.schema) {\n const schema = collection.getSchema()\n doc = await clean(schema, fromDot(doc))\n await validate(schema, doc)\n }\n\n docs[index] = doc\n }\n const {insertedIds} = await wrapErrors(() => {\n return collection.rawCollection.insertMany(docs as any, options.mongoOptions)\n })\n\n const ids: Array<MongoDB.ObjectId> = Object.values(insertedIds)\n\n return ids.map(id => id.toString())\n }\n\n return insertMany\n}\n","import {Collection, ModelClassBase, UpdateItem} from '../../types'\nimport {wrapErrors} from './wrapErrors'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const updateItem: UpdateItem<DocumentType> = async function (item, modifier, options = {}) {\n await collection.connectionPromise\n const updated = await wrapErrors(async () => {\n return await collection.updateAndFind(item._id, modifier, options)\n })\n\n for (const key in item) {\n delete item[key]\n }\n\n for (const key in updated) {\n item[key] = updated[key]\n }\n }\n return updateItem\n}\n","import getSelector from './getSelector'\nimport {Collection, CountDocuments, DeleteOne, ModelClassBase} from '../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const func: CountDocuments<DocumentType> = async function (selectorArg, options) {\n await collection.connectionPromise\n const selector = getSelector(arguments)\n const result = await collection.rawCollection.countDocuments(selector, options)\n\n return result\n }\n\n return func\n}\n","import {Collection, EstimatedDocumentCount, ModelClassBase} from '../../types'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const func: EstimatedDocumentCount<DocumentType> = async function (options) {\n await collection.connectionPromise\n const result = await collection.rawCollection.estimatedDocumentCount(options)\n return result\n }\n\n return func\n}\n","import {type} from 'rambdax'\nimport {Collection, InsertAndFind, ModelClassBase} from '../../types'\nimport fromDot from '../../helpers/fromDot'\nimport {clean, validate} from '@orion-js/schema'\nimport {wrapErrors} from './wrapErrors'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const insertAndFind: InsertAndFind<DocumentType> = async (insertDoc, options = {}) => {\n await collection.connectionPromise\n let doc = insertDoc as any\n if (!doc || type(doc) !== 'Object') {\n throw new Error('Insert must receive a document')\n }\n\n if (!doc._id) {\n doc._id = collection.generateId()\n }\n\n if (collection.schema) {\n const schema = collection.getSchema()\n doc = await clean(schema, fromDot(doc))\n await validate(schema, doc)\n }\n\n await wrapErrors(async () => {\n await collection.rawCollection.insertOne(doc, options.mongoOptions)\n })\n\n return doc\n }\n\n return insertAndFind\n}\n","import {Collection, DataLoader, ModelClassBase} from '../../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const loadById: DataLoader.LoadById<DocumentType> = async id => {\n const result = await collection.loadOne({\n key: '_id',\n value: id,\n })\n\n return result\n }\n\n return loadById\n}\n","import {Collection, DataLoader, ModelClassBase} from '../../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const loadMany: DataLoader.LoadMany<DocumentType> = async options => {\n const results = await collection.loadData(options)\n return results\n }\n\n return loadMany\n}\n","import {Collection, DataLoader, ModelClassBase} from '../../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const loadOne: DataLoader.LoadOne<DocumentType> = async options => {\n const [result] = await collection.loadData(options)\n return result\n }\n\n return loadOne\n}\n","import {createMapArray, clone} from '@orion-js/helpers'\nimport {DataLoader, Collection, ModelClassBase, ModelToMongoSelector} from '../../../types'\nimport dataLoad from './dataLoad'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const loadData: DataLoader.LoadData<DocumentType> = async options => {\n await collection.connectionPromise\n\n const result = await dataLoad({\n loaderKey: {\n key: options.key,\n match: options.match,\n sort: options.sort,\n project: options.project,\n collectionName: collection.name,\n },\n id: options.value,\n ids: options.values,\n timeout: options.timeout,\n load: async values => {\n const query = {\n ...clone(options.match),\n [options.key]: {$in: values},\n } as ModelToMongoSelector<DocumentType>\n\n const cursor = collection.find(query)\n\n if (options.sort) {\n cursor.sort(options.sort)\n }\n\n if (options.project) {\n cursor.project(options.project)\n }\n\n if (options.debug) {\n console.info(`Will execute data loading query now on ${collection.name}: `, query)\n }\n\n const items = await cursor.toArray()\n\n const itemsMap = createMapArray(items, options.key as string)\n return values.map(value => {\n return itemsMap[value] || []\n })\n },\n })\n\n return result\n }\n\n return loadData\n}\n","import DataLoader from 'dataloader'\n\nexport const cache = new Map()\n\ninterface Options {\n key: string\n func: (ids: Array<string>) => Promise<any>\n timeout: number\n}\n\nexport const getDataLoader = (params: Options): DataLoader<any, any> => {\n const {key, func, timeout} = params\n\n const existing = cache.get(key)\n if (existing) return existing\n\n const load = async (ids: Array<string>) => {\n cache.delete(key)\n return await func(ids)\n }\n\n const options = {\n batchScheduleFn: callback => setTimeout(callback, timeout),\n }\n\n const dataLoader = new DataLoader(load, options)\n\n cache.set(key, dataLoader)\n\n return dataLoader\n}\n","import {getDataLoader} from './getDataLoader'\nimport {flatten} from 'rambdax'\nimport {hashObject} from '@orion-js/helpers'\n\ninterface Options {\n loaderKey: any\n load: (values: Array<string>) => Promise<any>\n timeout?: number\n ids?: Array<string>\n id?: string\n}\n\nconst dataLoad = async (options: Options) => {\n const dataLoader = getDataLoader({\n key: hashObject(options.loaderKey),\n func: options.load,\n timeout: options.timeout || 5,\n })\n\n if (options.ids) {\n const resultArray = await dataLoader.loadMany(options.ids)\n return flatten(resultArray)\n }\n\n return await dataLoader.load(options.id)\n}\n\nexport default dataLoad\n","import {generateId, generateUUID} from '@orion-js/helpers'\nimport {ObjectId} from 'bson'\nimport {CreateCollectionOptions, ModelClassBase} from '..'\nimport {FieldType} from '@orion-js/schema'\n\nconst getIdGenerator = <DocumentType extends ModelClassBase>(\n options: CreateCollectionOptions,\n): (() => DocumentType['_id']) => {\n if (!options.idPrefix && options?.schema?._id) {\n const idField = options.schema._id.type as FieldType\n if (idField.name?.startsWith('typedId:')) {\n return () => {\n const prefix = idField.name.split(':')[1]\n const random = generateUUID()\n return `${prefix}-${random}`\n }\n }\n }\n\n if (options.idPrefix || options.idGeneration === 'uuid') {\n return () => {\n const prefix = options.idPrefix || ''\n const random = generateUUID()\n return `${prefix}${random}`\n }\n }\n\n if (options.idGeneration === 'random') {\n return () => {\n const prefix = options.idPrefix || ''\n const random = generateId()\n return `${prefix}${random}`\n }\n }\n\n return () => {\n const id = new ObjectId()\n\n return id.toString()\n }\n}\n\nexport default getIdGenerator\n","import {MongoExpiredSessionError, MongoNotConnectedError} from 'mongodb'\nimport {Collection, ModelClassBase} from '..'\n\nfunction matchingDefinition(defIndex, curIndex) {\n if (defIndex.options && defIndex.options.name === curIndex.name) return true\n const defIndexName = Object.keys(defIndex.keys)\n .map(key => `${key}_${defIndex.keys[key]}`)\n .join('_')\n return defIndexName === curIndex.name\n}\n\nexport async function checkIndexes<DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n await collection.connectionPromise\n\n let currentIndexes = []\n try {\n currentIndexes = await collection.rawCollection.indexes()\n } catch (error) {\n if (error.codeName !== 'NamespaceNotFound') throw error\n }\n\n const indexesToDelete = collection.indexes\n ? currentIndexes.filter(\n index =>\n index.name !== '_id_' &&\n !collection.indexes.find(definitionIndex => matchingDefinition(definitionIndex, index)),\n )\n : currentIndexes\n\n if (indexesToDelete.length > 0) {\n console.warn(\n `${indexesToDelete.length} unexpected indexes found in collection \"${\n collection.name\n }\": ${indexesToDelete\n .map(i => i.name)\n .join(', ')} | Delete the index or fix the collection definition`,\n )\n }\n}\nexport async function loadIndexes<DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n): Promise<string[]> {\n if (!collection.indexes) return\n if (!collection.indexes.length) return\n\n await collection.connectionPromise\n\n const results = Promise.all(\n collection.indexes.map(async ({keys, options}) => {\n try {\n return await collection.rawCollection.createIndex(keys, options)\n } catch (error) {\n if (error.code === 85 || error.code === 86) {\n console.info('Will delete index to create the new version')\n const indexName = (() => {\n const message = error.errorResponse.errmsg\n const indexName = message.split('name: \"')[1].split('\"')[0]\n return indexName\n })()\n await collection.rawCollection.dropIndex(indexName)\n console.info('Index was deleted, creating new index')\n const result = await collection.rawCollection.createIndex(keys, options)\n console.info('Index updated correctly')\n return result\n }\n if (error instanceof MongoExpiredSessionError || error instanceof MongoNotConnectedError) {\n // this errors is thrown when we are on tests environment\n // but it's not a problem never, index will be created on the next connection\n } else {\n console.error(`Error creating index for collection ${collection.name}: ${error.message}`)\n console.error(error)\n return error.message\n }\n }\n }),\n )\n\n await checkIndexes(collection)\n\n return results\n}\n","import {Schema} from '@orion-js/schema'\nimport {type} from 'rambdax'\nimport {clone} from '@orion-js/helpers'\nimport {CreateCollectionOptions} from '../types'\n\n// @ts-ignore polyfill for Symbol.metadata // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#decorator-metadata\nSymbol.metadata ??= Symbol('Symbol.metadata')\n\nexport function prepareShema(schema: Schema): Schema {\n if (!schema._id) {\n schema._id = {\n type: String,\n }\n }\n return schema\n}\n\nexport function getSchema(options: CreateCollectionOptions): Schema {\n if (!options.schema) return\n\n if (options.schema[Symbol.metadata]?._getModel) {\n return options.schema[Symbol.metadata]._getModel().getSchema()\n }\n\n // schema is a model\n if (options.schema.getSchema) {\n const schema = options.schema.getSchema()\n return prepareShema(schema)\n }\n\n // schema is a typed model\n if (options.schema.getModel) {\n const model = options.schema.getModel()\n const schema = model ? clone(model.getSchema()) : {}\n return prepareShema(schema)\n }\n\n if (type(options.schema) === 'Object') {\n return prepareShema(options.schema)\n }\n}\n","import {Collection} from '../types'\nimport {logger} from '@orion-js/logger'\n\nexport function wrapMethods(collection: Partial<Collection>) {\n // Wrap all collection methods to ensure connection is started\n const methodsWithPromises = [\n 'findOne',\n 'findOneAndUpdate',\n 'insertOne',\n 'insertMany',\n 'insertAndFind',\n 'updateOne',\n 'updateMany',\n 'deleteMany',\n 'deleteOne',\n 'upsert',\n 'estimatedDocumentCount',\n 'countDocuments',\n 'updateAndFind',\n 'updateItem',\n 'loadData',\n 'loadById',\n 'loadOne',\n 'loadMany',\n ]\n\n const methodsWithoutPromises = ['aggregate', 'find', 'watch']\n\n const originalMethods = {...collection}\n\n for (const methodName of methodsWithPromises) {\n if (typeof collection[methodName] === 'function') {\n collection[methodName] = async (...args: any[]) => {\n await collection.startConnection()\n return originalMethods[methodName](...args)\n }\n }\n\n for (const methodName of methodsWithoutPromises) {\n if (typeof collection[methodName] === 'function') {\n collection[methodName] = (...args: any[]) => {\n collection.startConnection()\n if (!collection.rawCollection) {\n logger.error('Method called before connection was initialized', {\n collectionName: collection.name,\n connectionName: collection.connectionName,\n methodName,\n })\n throw new Error('Method called before connection was initialized')\n }\n return originalMethods[methodName](...args)\n }\n }\n }\n }\n}\n","import {\n BaseCollection,\n Collection,\n CreateCollectionOptions,\n CreateCollectionOptionsWithSchemaType,\n CreateCollectionOptionsWithTypedSchema,\n InferSchemaTypeWithId,\n ModelClassBase,\n SchemaWithRequiredId,\n} from '../types'\nimport {\n countDocuments,\n deleteMany,\n deleteOne,\n estimatedDocumentCount,\n find,\n findOne,\n findOneAndUpdate,\n insertMany,\n insertOne,\n updateAndFind,\n updateItem,\n updateMany,\n updateOne,\n upsert,\n insertAndFind,\n} from './getMethods'\nimport {loadById, loadOne, loadMany, loadData} from './getMethods/dataLoader'\nimport getIdGenerator from './generateId'\nimport {loadIndexes} from './createIndexes'\nimport {getMongoConnection} from '..'\nimport {getSchema} from './getSchemaAndModel'\nimport {wrapMethods} from './wrapMethods'\nimport {InferSchemaType, TypedSchemaOnSchema} from '@orion-js/schema'\nimport {MongoClient} from 'mongodb'\n\nexport const createIndexesPromises = []\n\nexport function createCollection<T extends SchemaWithRequiredId>(\n options: CreateCollectionOptionsWithSchemaType<T>,\n): Collection<InferSchemaTypeWithId<T>>\n\nexport function createCollection<T extends TypedSchemaOnSchema & {prototype: {_id: string}}>(\n options: CreateCollectionOptionsWithTypedSchema<T>,\n): Collection<InferSchemaType<T>>\n\nexport function createCollection<T extends ModelClassBase>(\n options: CreateCollectionOptions<T>,\n): Collection<T>\n\nexport function createCollection(options: CreateCollectionOptions) {\n const connectionName = options.connectionName || 'main'\n\n const orionConnection = getMongoConnection({name: connectionName})\n if (!orionConnection) {\n throw new Error(`The connection to MongoDB \"${connectionName}\" was not found`)\n }\n\n const schema = getSchema(options)\n\n let resolveCollectionPromise: (MongoClient) => void\n const collectionPromise = new Promise<MongoClient>(resolve => {\n resolveCollectionPromise = resolve\n })\n\n const baseCollection: Partial<Collection<any>> = {\n name: options.name,\n connectionName,\n schema,\n indexes: options.indexes || [],\n client: orionConnection,\n connectionPromise: collectionPromise,\n startConnection: () => orionConnection.startConnection(),\n generateId: getIdGenerator(options),\n getRawCollection: async () => {\n await orionConnection.startConnection()\n return orionConnection.db.collection(options.name)\n },\n getSchema: () => schema,\n }\n\n const encryptedCollection: Partial<Collection<any>> = {\n ...baseCollection,\n getRawCollection: async () => {\n await orionConnection.startConnection()\n return orionConnection.encrypted.db.collection(options.name)\n },\n }\n\n const mainCollection: Partial<Collection<any>> = {\n ...baseCollection,\n encrypted: encryptedCollection as BaseCollection<ModelClassBase>,\n }\n\n const defineCollectionProperties = () => {\n if (orionConnection.db) {\n mainCollection.db = orionConnection.db\n mainCollection.rawCollection = orionConnection.db.collection(options.name)\n }\n\n if (orionConnection.encrypted.db) {\n encryptedCollection.db = orionConnection.encrypted.db\n encryptedCollection.rawCollection = orionConnection.encrypted.db.collection(options.name)\n }\n }\n\n defineCollectionProperties()\n\n orionConnection.connectionPromise.then(() => {\n defineCollectionProperties()\n resolveCollectionPromise(orionConnection.client)\n })\n\n const collections = [mainCollection, encryptedCollection]\n\n for (const collection of collections) {\n // modified orion methods\n collection.findOne = findOne(collection)\n collection.find = find(collection)\n collection.findOneAndUpdate = findOneAndUpdate(collection)\n collection.insertOne = insertOne(collection)\n collection.insertMany = insertMany(collection)\n collection.insertAndFind = insertAndFind(collection)\n collection.updateOne = updateOne(collection)\n collection.updateMany = updateMany(collection)\n collection.deleteMany = deleteMany(collection)\n collection.deleteOne = deleteOne(collection)\n collection.upsert = upsert(collection)\n\n // counts\n collection.estimatedDocumentCount = estimatedDocumentCount(collection)\n collection.countDocuments = countDocuments(collection)\n\n // update and find\n collection.updateAndFind = updateAndFind(collection)\n collection.updateItem = updateItem(collection)\n\n // plain passed methods\n collection.aggregate = (pipeline, options) =>\n collection.rawCollection.aggregate(pipeline, options)\n collection.watch = (pipeline, options) => collection.rawCollection.watch(pipeline, options)\n\n // data loader\n collection.loadData = loadData(collection)\n collection.loadById = loadById(collection)\n collection.loadOne = loadOne(collection)\n collection.loadMany = loadMany(collection)\n collection.createIndexes = async () => []\n }\n\n const createIndexes = async () => {\n await orionConnection.startConnection()\n const createIndexPromise = loadIndexes(mainCollection)\n createIndexesPromises.push(createIndexPromise)\n mainCollection.createIndexesPromise = createIndexPromise\n return createIndexPromise\n }\n\n mainCollection.createIndexes = createIndexes\n\n if (!process.env.DONT_CREATE_INDEXES_AUTOMATICALLY) {\n createIndexes()\n }\n\n wrapMethods(mainCollection as any)\n wrapMethods(encryptedCollection as any)\n\n return mainCollection as Collection<ModelClassBase>\n}\n","import {logger} from '@orion-js/logger'\nimport {AWSEncryptionKeyOptions, ClientEncryption, KMSProviders, MongoClient, UUID} from 'mongodb'\nimport {getMongoURLFromEnv} from '../connect/getMongoURLFromEnv'\n\nexport async function getOrCreateEncryptionKey({\n keyAltName,\n kmsProvider,\n masterKey,\n connectionName = 'main',\n keyVaultDatabase = 'encryption',\n keyVaultCollection = '__keyVault',\n kmsProviders,\n}: {\n keyAltName: string\n kmsProvider: keyof KMSProviders\n masterKey?: AWSEncryptionKeyOptions\n connectionName?: string\n keyVaultDatabase?: string\n keyVaultCollection?: string\n kmsProviders: KMSProviders\n}): Promise<{key: UUID; keyVaultNamespace: string}> {\n const keyVaultNamespace = `${keyVaultDatabase}.${keyVaultCollection}`\n\n logger.info('Connecting to database to get or create the encryption key', {\n keyVaultNamespace,\n keyAltName,\n })\n const client = new MongoClient(getMongoURLFromEnv(connectionName))\n await client.connect()\n const db = client.db(keyVaultDatabase)\n const collection = db.collection(keyVaultCollection)\n await collection.createIndex(\n {keyAltName: 1},\n {unique: true, partialFilterExpression: {keyAltName: {$exists: true}}},\n )\n const clientEncryption = new ClientEncryption(client, {\n keyVaultNamespace,\n kmsProviders,\n })\n\n const key = await clientEncryption.getKeyByAltName(keyAltName)\n if (key) {\n logger.info('Key found on the key vault', {\n keyVaultNamespace,\n keyAltName,\n UUID: key._id,\n })\n return {key: key._id, keyVaultNamespace}\n }\n\n logger.info('Key not found on the key vault, creating a new one', {\n keyVaultNamespace,\n keyAltName,\n })\n\n const newKey = await clientEncryption.createDataKey(kmsProvider, {\n keyAltNames: [keyAltName],\n ...(masterKey ? {masterKey} : {}),\n })\n\n logger.info('New encryption key created', {\n keyVaultNamespace,\n keyAltName,\n UUID: newKey,\n })\n\n return {key: newKey, keyVaultNamespace}\n}\n\nexport const ENCRYPTION_ALGORITHMS = {\n DETERMINISTIC: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic',\n RANDOM: 'AEAD_AES_256_CBC_HMAC_SHA_512-Random',\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAA2B;AAC3B,qBAAkD;;;ACDnC,SAAR,UAA2B,KAAqB;AACrD,MAAI,SAAS;AACb,MAAI,iBAAiB;AAErB,QAAM,sBAAsB,IAAI,QAAQ,IAAI,IAAI;AAEhD,MAAI,IAAI,QAAQ,GAAG,MAAM,IAAI;AAC3B,qBAAiB,IAAI,UAAU,qBAAqB,IAAI,QAAQ,GAAG,CAAC;AAAA,EACtE,OAAO;AACL,qBAAiB,IAAI,UAAU,mBAAmB;AAAA,EACpD;AAEA,MAAI,eAAe,QAAQ,OAAO,MAAM,IAAI;AAC1C,QAAI,eAAe,QAAQ,QAAQ,MAAM,IAAI;AAC3C,eAAS,eAAe,MAAM,QAAQ,EAAE,CAAC;AAAA,IAC3C;AAAA,EACF,WAAW,eAAe,QAAQ,GAAG,MAAM,IAAI;AAC7C,aAAS,eAAe,MAAM,GAAG,EAAE,CAAC;AAAA,EACtC;AAEA,SAAO;AACT;;;ADlBA,0BAA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AAgB;AACrC,QAAM,aAAa,GAAG,WAAW,kBAAkB;AACnD,QAAM,WAAW;AAAA,IACf,EAAC,YAAY,EAAC;AAAA,IACd,EAAC,QAAQ,MAAM,yBAAyB,EAAC,YAAY,EAAC,SAAS,KAAI,EAAC,EAAC;AAAA,EACvE;AACA,QAAM,mBAAmB,IAAI,iCAAiB,QAAQ;AAAA,IACpD;AAAA,IACA;AAAA,EACF,CAAC;AAED,QAAM,MAAM,MAAM,iBAAiB,gBAAgB,UAAU;AAC7D,MAAI,KAAK;AACP,0BAAO,KAAK,8BAA8B;AAAA,MACxC;AAAA,MACA;AAAA,MACA,MAAM,IAAI;AAAA,IACZ,CAAC;AACD,WAAO,EAAC,KAAK,IAAI,KAAK,kBAAiB;AAAA,EACzC;AAEA,wBAAO,KAAK,sDAAsD;AAAA,IAChE;AAAA,IACA;AAAA,EACF,CAAC;AAED,QAAM,SAAS,MAAM,iBAAiB,cAAc,aAAa;AAAA,IAC/D,aAAa,CAAC,UAAU;AAAA,IACxB,GAAI,YAAY,EAAC,UAAS,IAAI,CAAC;AAAA,EACjC,CAAC;AAED,wBAAO,KAAK,8BAA8B;AAAA,IACxC;AAAA,IACA;AAAA,IACA,MAAM;AAAA,EACR,CAAC;AAED,SAAO,EAAC,KAAK,QAAQ,kBAAiB;AACxC;AAEO,IAAM,wBAAwB;AAAA,EACnC,eAAe;AAAA,EACf,QAAQ;AACV;","names":["value","import_schema","import_dot_object","Dot","dot","import_schema","import_schema","import_schema","import_schema","import_schema","shouldCheck","import_schema","import_schema","import_helpers","import_schema","import_schema","import_helpers","DataLoader","import_helpers","import_helpers","import_mongodb","indexName","import_helpers","import_logger","methodName","options","import_logger","import_mongodb"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/connect/connections.ts","../src/connect/getDBName.ts","../src/connect/getMongoURLFromEnv.ts","../src/connect/getMongoConnection.ts","../src/types/index.ts","../src/service/index.ts","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/isArray.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/isInteger.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/createPath.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/equals.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isType.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/compare.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/includes.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/omit.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/flatten.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isEmpty.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isNil.js","../src/createCollection/getMethods/getSelector.ts","../src/createCollection/getMethods/find.ts","../src/createCollection/getMethods/findOne.ts","../src/createCollection/getMethods/validateModifier/validatePush.ts","../src/helpers/fromDot.ts","../src/helpers/toDot.ts","../src/createCollection/getMethods/validateModifier/validateUnset.ts","../src/createCollection/getMethods/validateModifier/validateInc.ts","../src/createCollection/getMethods/validateModifier/validateSet.ts","../src/createCollection/getMethods/validateModifier/validateOperator.ts","../src/createCollection/getMethods/validateModifier/index.ts","../src/createCollection/getMethods/validateModifier/validateUpsert.ts","../src/createCollection/getMethods/cleanModifier.ts","../src/createCollection/getMethods/wrapErrors.ts","../src/createCollection/getMethods/upsert.ts","../src/createCollection/getMethods/findOneAndUpdate.ts","../src/createCollection/getMethods/updateOne.ts","../src/createCollection/getMethods/updateMany.ts","../src/createCollection/getMethods/updateAndFind.ts","../src/createCollection/getMethods/deleteOne.ts","../src/createCollection/getMethods/deleteMany.ts","../src/createCollection/getMethods/insertOne.ts","../src/createCollection/getMethods/insertMany.ts","../src/createCollection/getMethods/updateItem.ts","../src/createCollection/getMethods/countDocuments.ts","../src/createCollection/getMethods/estimatedDocumentCount.ts","../src/createCollection/getMethods/insertAndFind.ts","../src/createCollection/getMethods/dataLoader/loadById.ts","../src/createCollection/getMethods/dataLoader/loadMany.ts","../src/createCollection/getMethods/dataLoader/loadOne.ts","../src/createCollection/getMethods/dataLoader/loadData.ts","../src/createCollection/getMethods/dataLoader/dataLoad/getDataLoader.ts","../src/createCollection/getMethods/dataLoader/dataLoad/index.ts","../src/createCollection/generateId.ts","../src/createCollection/createIndexes.ts","../src/createCollection/getSchemaAndModel.ts","../src/createCollection/wrapMethods.ts","../src/createCollection/index.ts","../src/encrypted/getOrCreateEncryptionKey.ts"],"sourcesContent":["export * from './connect'\nexport * from './types'\nexport * from './service'\nexport * from './createCollection'\nexport * from './encrypted/getOrCreateEncryptionKey'\n","import {EventEmitter} from 'node:events'\nimport {MongoClient, Db, MongoClientOptions} from 'mongodb'\nimport getDBName from './getDBName'\nimport {nextTick} from 'node:process'\nimport {logger} from '@orion-js/logger'\nimport {sleep} from '@orion-js/helpers'\nimport {getMongoURLFromEnv} from './getMongoURLFromEnv'\n\nexport interface OrionMongoClient {\n client: MongoClient\n db: Db\n uri: string\n dbName: string\n /**\n * @deprecated Use startConnection() instead. This property is not guaranteed to be resolved if the connection is not started.\n * When using async calls startConnection or connectionPromise is no longer needed. Orion will automatically start the connection if it is not already started.\n * Kept for backwards compatibility. startConnection does not re-start the connection if it is already started, so it is safe to use.\n */\n connectionPromise: Promise<MongoClient>\n connectionName: string\n encrypted: {client: MongoClient; db: Db}\n /**\n * Starts the connection if it is not already started.\n * If the connection is already started, it resolves immediately.\n */\n startConnection: () => Promise<MongoClient>\n closeConnection: () => Promise<void>\n}\n\n// globalThis.myModuleMap ??= {}\nexport const connectionWrappers: {[key: string]: OrionMongoDatabaseWrapper} = {} //globalThis.myModuleMap\n\nclass OrionMongoDatabaseWrapper implements OrionMongoClient {\n uri: string\n dbName: string\n connectionName: string\n connectionPromise: Promise<MongoClient>\n private mongoOptions: MongoClientOptions\n private connectionEvent: EventEmitter = new EventEmitter()\n private state: 'disconnected' | 'connecting' | 'connected' | 'disconnecting' = 'disconnected'\n client: MongoClient\n db: Db\n configured = false\n readonly encrypted: {client: MongoClient; db: Db} = {client: null, db: null}\n readonly configTimeout: NodeJS.Timeout\n\n constructor(connectionName: string) {\n this.connectionName = connectionName\n logger.info('New connection requested', {\n connectionName,\n })\n\n this.connectionEvent.setMaxListeners(Number.POSITIVE_INFINITY)\n this.connectionPromise = new Promise((resolve, reject) => {\n if (this.state === 'connected') {\n resolve(this.client)\n }\n this.connectionEvent.once('connected', resolve)\n this.connectionEvent.once('error', reject)\n })\n this.configTimeout = setTimeout(() => {\n logger.error(\n 'Connection was required but never configured, call configureConnection() or unset the env variable MONGO_EXPLICIT_SETUP',\n {\n connectionName,\n },\n )\n this.connectionEvent.emit('error', new Error('Connection was required but never configured'))\n }, 30 * 1000)\n }\n\n config(mongoURL: string, mongoOptions: MongoClientOptions) {\n this.uri = mongoURL\n this.mongoOptions = mongoOptions\n this.configured = true\n if (this.mongoOptions?.autoEncryption) {\n this.encrypted.client = new MongoClient(mongoURL, {\n retryReads: true,\n ...this.mongoOptions,\n })\n this.encrypted.db = this.encrypted.client.db(getDBName(this.uri))\n }\n this.client = new MongoClient(mongoURL, {\n retryReads: true,\n ...this.mongoOptions,\n autoEncryption: null,\n })\n this.db = this.client.db(getDBName(this.uri))\n clearTimeout(this.configTimeout)\n }\n\n async awaitConnection() {\n if (this.state === 'connected') return this\n if (this.state === 'connecting' || !this.configured) {\n // Wait for the connection to be configured and established\n await this.connectionPromise\n return this\n }\n this.state = 'connecting'\n const censoredURI = this.uri.replace(/\\/\\/.*:.*@/, '//') // remove user and password from URL\n logger.info('Connecting to mongo', {\n uri: censoredURI,\n connectionName: this.connectionName,\n })\n if (this.encrypted.client) {\n await this.connectWithRetry(this.encrypted.client)\n logger.info('Successfully connected to encrypted mongo', {\n uri: censoredURI,\n connectionName: this.connectionName,\n })\n }\n await this.connectWithRetry(this.client)\n this.state = 'connected'\n this.connectionEvent.emit('connected', this.client)\n logger.info('Successfully connected to mongo', {\n uri: censoredURI,\n connectionName: this.connectionName,\n })\n nextTick(() => {\n this.connectionEvent.removeAllListeners()\n this.connectionEvent = null\n })\n return this\n }\n\n async connectWithRetry(client: MongoClient) {\n try {\n return await client.connect()\n } catch (error) {\n logger.error('Error connecting to mongo. Will retry in 5s', {\n error,\n connectionName: this.connectionName,\n })\n await sleep(5000)\n return this.connectWithRetry(client)\n }\n }\n\n async startConnection() {\n return this.awaitConnection().then(() => this.client)\n }\n\n async closeConnection() {\n if (this.state === 'disconnected' || this.state === 'disconnecting') return\n this.state = 'disconnecting'\n await this.client?.close()\n await this.encrypted?.client?.close()\n this.state = 'disconnected'\n }\n}\n\nexport function configureConnection(connectionName: string, mongoOptions: MongoClientOptions) {\n connectionWrappers[connectionName] =\n connectionWrappers[connectionName] || new OrionMongoDatabaseWrapper(connectionName)\n const connectionWrapper = connectionWrappers[connectionName]\n if (connectionWrapper.configured) {\n throw new Error('Connection already configured')\n }\n connectionWrapper.config(getMongoURLFromEnv(connectionName), mongoOptions)\n return connectionWrapper.awaitConnection()\n}\n\nexport function getExistingConnection(connectionName: string) {\n connectionWrappers[connectionName] =\n connectionWrappers[connectionName] || new OrionMongoDatabaseWrapper(connectionName)\n\n return connectionWrappers[connectionName]\n}\n\nexport const connections = connectionWrappers\n","export default function getDBName(url: string): string {\n let dbName = 'admin'\n let connectionPart = ''\n\n const startConnectionPart = url.indexOf('//') + 2\n\n if (url.indexOf('?') !== -1) {\n connectionPart = url.substring(startConnectionPart, url.indexOf('?'))\n } else {\n connectionPart = url.substring(startConnectionPart)\n }\n\n if (connectionPart.indexOf('.sock') !== -1) {\n if (connectionPart.indexOf('.sock/') !== -1) {\n dbName = connectionPart.split('.sock/')[1]\n }\n } else if (connectionPart.indexOf('/') !== -1) {\n dbName = connectionPart.split('/')[1]\n }\n\n return dbName\n}\n","import {internalGetEnv} from '@orion-js/env'\n\nexport const getMongoURLFromEnv = (connectionName: string): string => {\n if (connectionName === 'main') {\n if (!internalGetEnv('mongo_url', 'MONGO_URL')) {\n throw new Error('MONGO_URL is required')\n }\n return internalGetEnv('mongo_url', 'MONGO_URL')\n }\n\n const envName = `mongo_url_${connectionName.toLowerCase()}`\n const processEnvName = `MONGO_URL_${connectionName.toUpperCase()}`\n const uri = internalGetEnv(envName, processEnvName)\n if (!uri) {\n throw new Error(\n `To use the connection \"${connectionName}\" you must initialize it first calling getMongoConnection({name: \"${connectionName}\", uri: \"MONGOURI\"}) or setting the environment variable ${processEnvName}.`,\n )\n }\n\n return uri\n}\n\nexport const requiresExplicitSetup = (connectionName: string): boolean => {\n if (connectionName === 'main') {\n const value = internalGetEnv('mongo_explicit_setup', 'MONGO_EXPLICIT_SETUP')\n return typeof value === 'boolean' ? value : value === 'true'\n }\n\n const envName = `mongo_explicit_setup_${connectionName.toLowerCase()}`\n const processEnvName = `MONGO_EXPLICIT_SETUP_${connectionName.toUpperCase()}`\n const value = internalGetEnv(envName, processEnvName)\n return typeof value === 'boolean' ? value : value === 'true'\n}\n","import {getExistingConnection} from './connections'\nimport type {OrionMongoClient} from './connections'\nimport {getMongoURLFromEnv, requiresExplicitSetup} from './getMongoURLFromEnv'\nexport const allConnectionPromises = []\n\ninterface MongoConnectOptions {\n name: string\n uri?: string\n}\n\nexport const getMongoConnection = ({name, uri}: MongoConnectOptions): OrionMongoClient => {\n uri = uri || getMongoURLFromEnv(name)\n const connection = getExistingConnection(name)\n\n if (!connection.configured && !requiresExplicitSetup(name)) {\n connection.config(uri, {})\n }\n allConnectionPromises.push(connection.connectionPromise)\n return connection\n}\n","import * as MongoDB from 'mongodb'\nimport {\n FieldType,\n fieldTypes,\n InferSchemaType,\n Schema,\n SchemaInAnyOrionForm,\n StrictInferSchemaType,\n TypedSchemaOnSchema,\n} from '@orion-js/schema'\nimport {OrionMongoClient} from '../connect/connections'\nimport {EnhancedOmit} from 'mongodb'\n\nexport {MongoDB}\n\nexport type OptionalId<T> = MongoDB.OptionalId<T>\n\nexport declare type InferIdType<TSchema> = TSchema extends {\n _id: infer IdType\n}\n ? Record<any, never> extends IdType\n ? never\n : IdType\n : TSchema extends {\n _id?: infer IdType\n }\n ? unknown extends IdType\n ? string\n : IdType\n : string\n\nexport type DocumentWithId<TSchema> = EnhancedOmit<TSchema, '_id'> & {\n _id: InferIdType<TSchema>\n}\n\nexport type ModelClassBase = DocumentWithId<MongoDB.Document>\n\nexport interface CollectionIndex {\n keys: MongoDB.IndexSpecification\n options?: MongoDB.CreateIndexesOptions\n}\n\nexport namespace DataLoader {\n interface LoadDataOptionsBase<ModelClass extends ModelClassBase> {\n key: keyof ModelClass\n match?: MongoFilter<ModelClass>\n sort?: MongoDB.Sort\n project?: MongoDB.Document\n timeout?: number\n debug?: boolean\n }\n\n export interface LoadDataOptions<ModelClass extends ModelClassBase>\n extends LoadDataOptionsBase<ModelClass> {\n value?: any\n values?: Array<any>\n }\n\n export interface LoadOneOptions<ModelClass extends ModelClassBase>\n extends LoadDataOptionsBase<ModelClass> {\n value: any\n }\n\n export type LoadData<ModelClass extends ModelClassBase> = (\n options: LoadDataOptions<ModelClass>,\n ) => Promise<Array<ModelClass>>\n export type LoadOne<ModelClass extends ModelClassBase> = (\n options: LoadOneOptions<ModelClass>,\n ) => Promise<ModelClass>\n export type LoadMany<ModelClass extends ModelClassBase> = (\n options: LoadDataOptions<ModelClass>,\n ) => Promise<Array<ModelClass>>\n export type LoadById<ModelClass extends ModelClassBase> = (\n id: ModelClass['_id'],\n ) => Promise<ModelClass>\n}\n\nexport type MongoFilter<ModelClass extends ModelClassBase = ModelClassBase> =\n MongoDB.Filter<ModelClass>\n\nexport type MongoSelector<ModelClass extends ModelClassBase = ModelClassBase> =\n | ModelClass['_id']\n | MongoFilter<ModelClass>\n\nexport interface FindCursor<ModelClass> extends MongoDB.FindCursor {\n toArray: () => Promise<Array<ModelClass>>\n}\n\nexport interface UpdateOptions {\n clean?: boolean\n validate?: boolean\n mongoOptions?: MongoDB.UpdateOptions\n}\n\nexport interface FindOneAndUpdateUpdateOptions {\n clean?: boolean\n validate?: boolean\n mongoOptions?: MongoDB.FindOneAndUpdateOptions\n}\n\nexport interface InsertOptions {\n clean?: boolean\n validate?: boolean\n mongoOptions?: MongoDB.InsertOneOptions\n}\n\nexport interface InsertManyOptions {\n clean?: boolean\n validate?: boolean\n mongoOptions?: MongoDB.BulkWriteOptions\n}\n\nexport type InitItem<ModelClass extends ModelClassBase> = (doc: any) => ModelClass\n\nexport type ModelToMongoSelector<ModelClass extends ModelClassBase> =\n | MongoDB.Filter<ModelClass>\n | DocumentWithId<ModelClass>['_id']\n\nexport type FindOne<ModelClass extends ModelClassBase> = (\n selector?: ModelToMongoSelector<ModelClass>,\n options?: MongoDB.FindOptions<ModelClass>,\n) => Promise<ModelClass>\n\nexport type Find<ModelClass extends ModelClassBase> = (\n selector?: ModelToMongoSelector<ModelClass>,\n options?: MongoDB.FindOptions<ModelClass>,\n) => FindCursor<ModelClass>\n\nexport type FindOneAndUpdate<ModelClass extends ModelClassBase> = <\n TSelector extends ModelToMongoSelector<ModelClass>,\n TFilter extends MongoDB.UpdateFilter<ModelClass>,\n TOptions extends FindOneAndUpdateUpdateOptions,\n>(\n selector: TSelector,\n modifier: TFilter,\n options?: TOptions,\n) => ReturnType<MongoDB.Collection<ModelClass>['findOneAndUpdate']>\n\nexport type UpdateAndFind<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n modifier: MongoDB.UpdateFilter<ModelClass>,\n options?: FindOneAndUpdateUpdateOptions,\n) => Promise<ModelClass>\n\nexport type UpdateItem<ModelClass extends ModelClassBase> = (\n item: ModelClass,\n modifier: MongoDB.UpdateFilter<ModelClass>,\n options?: FindOneAndUpdateUpdateOptions,\n) => Promise<void>\n\nexport type InsertOne<ModelClass extends ModelClassBase> = (\n doc: MongoDB.OptionalId<ModelClass>,\n options?: InsertOptions,\n) => Promise<ModelClass['_id']>\n\nexport type InsertMany<ModelClass extends ModelClassBase> = (\n doc: Array<MongoDB.OptionalId<ModelClass>>,\n options?: InsertManyOptions,\n) => Promise<Array<ModelClass['_id']>>\n\nexport type InsertAndFind<ModelClass extends ModelClassBase> = (\n doc: MongoDB.OptionalId<ModelClass>,\n options?: InsertOptions,\n) => Promise<ModelClass>\n\nexport type DeleteMany<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n options?: MongoDB.DeleteOptions,\n) => Promise<MongoDB.DeleteResult>\n\nexport type DeleteOne<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n options?: MongoDB.DeleteOptions,\n) => Promise<MongoDB.DeleteResult>\n\nexport type UpdateOne<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n modifier: MongoDB.UpdateFilter<ModelClass>,\n options?: UpdateOptions,\n) => Promise<MongoDB.UpdateResult>\n\nexport type UpdateMany<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n modifier: MongoDB.UpdateFilter<ModelClass>,\n options?: UpdateOptions,\n) => Promise<MongoDB.UpdateResult | MongoDB.Document>\n\nexport type Upsert<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n modifier: MongoDB.UpdateFilter<ModelClass>,\n options?: UpdateOptions,\n) => Promise<MongoDB.UpdateResult>\n\nexport interface CreateCollectionOptions<ModelClass extends ModelClassBase = ModelClassBase> {\n /**\n * The name of the collection on the Mongo Database\n */\n name: string\n /**\n * The name of the connection to use. The Mongo URL of this connection will be search on env variables.\n * If not found, the connection url will be `env.mongo_url`\n * If defined, the connection url will be `env.mongo_url_${name}`\n */\n connectionName?: string\n /**\n * The schema used for cleaning and validation of the documents\n */\n schema?: SchemaInAnyOrionForm\n /**\n * The indexes to use\n */\n indexes?: Array<CollectionIndex>\n /**\n * Select between random id generation o mongo (time based) id generation\n */\n idGeneration?: 'mongo' | 'random' | 'uuid'\n /**\n * ID prefix. idGeneration will be forced to random. Recommended for type checking\n */\n idPrefix?: ModelClass['_id']\n}\n\nexport type EstimatedDocumentCount<_ModelClass extends ModelClassBase> = (\n options?: MongoDB.EstimatedDocumentCountOptions,\n) => Promise<number>\n\nexport type CountDocuments<ModelClass extends ModelClassBase> = (\n selector: ModelToMongoSelector<ModelClass>,\n options?: MongoDB.CountDocumentsOptions,\n) => Promise<number>\n\nexport type SchemaWithRequiredId = Schema & {_id: {type: any}}\n\nexport type InferSchemaTypeWithId<TSchema extends SchemaWithRequiredId> = DocumentWithId<\n StrictInferSchemaType<TSchema>\n>\n\nexport type CreateCollectionOptionsWithSchemaType<T extends SchemaWithRequiredId> = {\n schema: T\n} & Omit<CreateCollectionOptions<InferSchemaTypeWithId<T>>, 'schema'>\n\nexport type CreateCollectionOptionsWithTypedSchema<\n T extends TypedSchemaOnSchema & {prototype: {_id: string}},\n> = {\n schema: T\n} & Omit<CreateCollectionOptions<InferSchemaType<T>>, 'schema'>\n\nexport class BaseCollection<ModelClass extends ModelClassBase = ModelClassBase> {\n name: string\n connectionName?: string\n schema?: Schema\n generateId: () => ModelClass['_id']\n getSchema: () => Schema\n\n db: MongoDB.Db\n client: OrionMongoClient\n /**\n * @deprecated Use getRawCollection() instead. This property is not guaranteed to be defined if the connection has not been started.\n */\n rawCollection: MongoDB.Collection<ModelClass>\n getRawCollection: () => Promise<MongoDB.Collection<ModelClass>>\n\n findOne: FindOne<ModelClass>\n find: Find<ModelClass>\n\n insertOne: InsertOne<ModelClass>\n insertMany: InsertMany<ModelClass>\n insertAndFind: InsertAndFind<ModelClass>\n\n deleteMany: DeleteMany<ModelClass>\n deleteOne: DeleteOne<ModelClass>\n\n updateOne: UpdateOne<ModelClass>\n updateMany: UpdateMany<ModelClass>\n\n upsert: Upsert<ModelClass>\n findOneAndUpdate: FindOneAndUpdate<ModelClass>\n\n /**\n * Updates a document and returns the updated document with the changes\n */\n updateAndFind: UpdateAndFind<ModelClass>\n updateItem: UpdateItem<ModelClass>\n\n estimatedDocumentCount: EstimatedDocumentCount<ModelClass>\n countDocuments: CountDocuments<ModelClass>\n\n aggregate: <T = MongoDB.Document>(\n pipeline?: MongoDB.Document[],\n options?: MongoDB.AggregateOptions,\n ) => MongoDB.AggregationCursor<T>\n watch: <T = MongoDB.Document>(\n pipeline?: MongoDB.Document[],\n options?: MongoDB.ChangeStreamOptions,\n ) => MongoDB.ChangeStream<T>\n\n loadData: DataLoader.LoadData<ModelClass>\n loadOne: DataLoader.LoadOne<ModelClass>\n loadMany: DataLoader.LoadMany<ModelClass>\n loadById: DataLoader.LoadById<ModelClass>\n\n /**\n * Use this function if you are using tests and you pass the\n * env var DONT_CREATE_INDEXES_AUTOMATICALLY and you need to\n * create the indexes for this collection\n */\n createIndexes: () => Promise<string[]>\n createIndexesPromise: Promise<string[]>\n /**\n * @deprecated Use startConnection() instead. This property is not guaranteed to be resolved if the connection is not started.\n * When using async calls startConnection or connectionPromise is no longer needed. Orion will automatically start the connection if it is not already started.\n * Kept for backwards compatibility. startConnection does not re-start the connection if it is already started, so it is safe to use.\n */\n connectionPromise: Promise<MongoDB.MongoClient>\n startConnection: () => Promise<MongoDB.MongoClient>\n}\n\nexport class Collection<\n ModelClass extends ModelClassBase = ModelClassBase,\n> extends BaseCollection<ModelClass> {\n indexes: Array<CollectionIndex>\n encrypted?: BaseCollection<ModelClass>\n}\n\nexport type DistinctDocumentId<DistinctId extends string> = string & {\n __TYPE__: `DistinctDocumentId<${DistinctId}>`\n}\n\nexport type TypedId<TPrefix extends string> = `${TPrefix}-${string}`\n\n/**\n * Use this function to create unique types for the ids of mongodb documents.\n * You should set it as the type of the _id field in your schema.\n *\n * @example\n * ```ts\n * type UserId = TypedId<'user'>\n *\n * const userSchema = {\n * _id: {\n * type: TypedId('user'),\n * },\n * }\n *\n * ```\n */\nexport function typedId<const TPrefix extends string>(\n prefix: TPrefix,\n): FieldType<TypedId<TPrefix>> {\n return {\n ...fieldTypes.string,\n name: `typedId:${prefix}`,\n toSerializedType: async () => 'string',\n } as any\n}\n","import {Service} from '@orion-js/services'\nimport {createCollection} from '../createCollection'\nimport {CreateCollectionOptions, ModelClassBase} from '../types'\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string}>()\n\nexport function Repository() {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n\n context.addInitializer(function (this) {\n serviceMetadata.set(this, {_serviceType: 'repo'})\n })\n }\n}\n\nexport function MongoCollection<ModelClass extends ModelClassBase = ModelClassBase>(\n options: CreateCollectionOptions<ModelClass>,\n) {\n return (_target: any, context: ClassFieldDecoratorContext) => {\n const propertyKey = String(context.name)\n context.addInitializer(function (this) {\n const repo = serviceMetadata.get(this.constructor)\n if (!repo || repo._serviceType !== 'repo') {\n throw new Error(\n 'You must pass a class decorated with @Repository if you want to use @MongoCollection',\n )\n }\n\n const collection = createCollection(options)\n this[propertyKey] = collection\n })\n }\n}\n","export function type(input){\n if (input === null){\n return 'Null'\n } else if (input === undefined){\n return 'Undefined'\n } else if (Number.isNaN(input)){\n return 'NaN'\n }\n const typeResult = Object.prototype.toString.call(input).slice(8, -1)\n\n return typeResult === 'AsyncFunction' ? 'Promise' : typeResult\n}\n","export const { isArray } = Array\n","function _isInteger(n){\n return n << 0 === n\n}\n\nexport const isInteger = Number.isInteger || _isInteger\n\n/**\n * Check if `index` is integer even if it is a string.\n */\nexport const isIndexInteger = index => Number.isInteger(Number(index))\n","import { isInteger } from './isInteger.js'\n\nexport function createPath(path, delimiter = '.'){\n return typeof path === 'string' ?\n path.split(delimiter).map(x => isInteger(x) ? Number(x) : x) :\n path\n}\n","import { isArray } from './_internals/isArray.js'\nimport { type } from './type.js'\n\nexport function _lastIndexOf(valueToFind, list){\n if (!isArray(list))\n throw new Error(`Cannot read property 'indexOf' of ${ list }`)\n\n const typeOfValue = type(valueToFind)\n if (![ 'Array', 'NaN', 'Object', 'RegExp' ].includes(typeOfValue))\n return list.lastIndexOf(valueToFind)\n\n const { length } = list\n let index = length\n let foundIndex = -1\n\n while (--index > -1 && foundIndex === -1)\n if (equals(list[ index ], valueToFind))\n foundIndex = index\n\n return foundIndex\n}\n\nexport function _indexOf(valueToFind, list){\n if (!isArray(list))\n throw new Error(`Cannot read property 'indexOf' of ${ list }`)\n\n const typeOfValue = type(valueToFind)\n if (![ 'Array', 'NaN', 'Object', 'RegExp' ].includes(typeOfValue))\n return list.indexOf(valueToFind)\n\n let index = -1\n let foundIndex = -1\n const { length } = list\n\n while (++index < length && foundIndex === -1)\n if (equals(list[ index ], valueToFind))\n foundIndex = index\n\n return foundIndex\n}\n\nfunction _arrayFromIterator(iter){\n const list = []\n let next\n while (!(next = iter.next()).done)\n list.push(next.value)\n\n return list\n}\n\nfunction _compareSets(a, b){\n if (a.size !== b.size)\n return false\n\n const aList = _arrayFromIterator(a.values())\n const bList = _arrayFromIterator(b.values())\n\n const filtered = aList.filter(aInstance => _indexOf(aInstance, bList) === -1)\n\n return filtered.length === 0\n}\n\nfunction compareErrors(a, b){\n if (a.message !== b.message) return false\n if (a.toString !== b.toString) return false\n\n return a.toString() === b.toString()\n}\n\nfunction parseDate(maybeDate){\n if (!maybeDate.toDateString) return [ false ]\n\n return [ true, maybeDate.getTime() ]\n}\n\nfunction parseRegex(maybeRegex){\n if (maybeRegex.constructor !== RegExp) return [ false ]\n\n return [ true, maybeRegex.toString() ]\n}\n\nexport function equals(a, b){\n if (arguments.length === 1) return _b => equals(a, _b)\n\n if (Object.is(a, b)) return true\n\n const aType = type(a)\n\n if (aType !== type(b)) return false\n if (aType === 'Function')\n return a.name === undefined ? false : a.name === b.name\n\n if ([ 'NaN', 'Null', 'Undefined' ].includes(aType)) return true\n\n if ([ 'BigInt', 'Number' ].includes(aType)){\n if (Object.is(-0, a) !== Object.is(-0, b)) return false\n\n return a.toString() === b.toString()\n }\n\n if ([ 'Boolean', 'String' ].includes(aType))\n return a.toString() === b.toString()\n\n if (aType === 'Array'){\n const aClone = Array.from(a)\n const bClone = Array.from(b)\n\n if (aClone.toString() !== bClone.toString())\n return false\n\n let loopArrayFlag = true\n aClone.forEach((aCloneInstance, aCloneIndex) => {\n if (loopArrayFlag)\n if (\n aCloneInstance !== bClone[ aCloneIndex ] &&\n !equals(aCloneInstance, bClone[ aCloneIndex ])\n )\n loopArrayFlag = false\n\n })\n\n return loopArrayFlag\n }\n\n const aRegex = parseRegex(a)\n const bRegex = parseRegex(b)\n\n if (aRegex[ 0 ])\n return bRegex[ 0 ] ? aRegex[ 1 ] === bRegex[ 1 ] : false\n else if (bRegex[ 0 ]) return false\n\n const aDate = parseDate(a)\n const bDate = parseDate(b)\n\n if (aDate[ 0 ])\n return bDate[ 0 ] ? aDate[ 1 ] === bDate[ 1 ] : false\n else if (bDate[ 0 ]) return false\n\n if (a instanceof Error){\n if (!(b instanceof Error)) return false\n\n return compareErrors(a, b)\n }\n\n if (aType === 'Set')\n return _compareSets(a, b)\n\n if (aType === 'Object'){\n const aKeys = Object.keys(a)\n\n if (aKeys.length !== Object.keys(b).length)\n return false\n\n let loopObjectFlag = true\n aKeys.forEach(aKeyInstance => {\n if (loopObjectFlag){\n const aValue = a[ aKeyInstance ]\n const bValue = b[ aKeyInstance ]\n\n if (aValue !== bValue && !equals(aValue, bValue))\n loopObjectFlag = false\n\n }\n })\n\n return loopObjectFlag\n }\n\n return false\n}\n","import { type } from './type.js'\n\nexport function isType(xType, x){\n if (arguments.length === 1){\n return xHolder => isType(xType, xHolder)\n }\n\n return type(x) === xType\n}\n","export function compare(a, b){\n return String(a) === String(b)\n}\n","import { compare } from './compare.js'\n\nexport function includes(a, list){\n let index = -1\n const { length } = list\n\n while (++index < length)\n if (compare(list[ index ], a))\n return true\n\n return false\n}\n","import { createPath } from './_internals/createPath.js'\nimport { includes } from './_internals/includes.js'\n\nexport function omit(propsToOmit, obj){\n if (arguments.length === 1) return _obj => omit(propsToOmit, _obj)\n\n if (obj === null || obj === undefined)\n return undefined\n\n const propsToOmitValue = createPath(propsToOmit, ',')\n const willReturn = {}\n\n for (const key in obj)\n if (!includes(key, propsToOmitValue))\n willReturn[ key ] = obj[ key ]\n\n return willReturn\n}\n","import { isArray } from './_internals/isArray.js'\n\nexport function flatten(list, input){\n const willReturn = input === undefined ? [] : input\n\n for (let i = 0; i < list.length; i++){\n if (isArray(list[ i ])){\n flatten(list[ i ], willReturn)\n } else {\n willReturn.push(list[ i ])\n }\n }\n\n return willReturn\n}\n","import { type } from './type.js'\n\nexport function isEmpty(input){\n const inputType = type(input)\n if ([ 'Undefined', 'NaN', 'Number', 'Null' ].includes(inputType))\n return false\n if (!input) return true\n\n if (inputType === 'Object'){\n return Object.keys(input).length === 0\n }\n\n if (inputType === 'Array'){\n return input.length === 0\n }\n\n return false\n}\n","export function isNil(x){\n return x === undefined || x === null\n}\n","import {type} from 'rambdax'\nimport {Filter} from 'mongodb'\nimport {ModelClassBase, ModelToMongoSelector} from '../../types'\n\nexport default function getSelector<ModelClass extends ModelClassBase>(\n args: IArguments | any[],\n): Filter<ModelClass> {\n if (args.length === 0) return {}\n\n const selector = args[0] as ModelToMongoSelector<ModelClass>\n\n if (typeof selector === 'string') {\n return {_id: selector} as Filter<ModelClass>\n }\n\n if (type(selector) === 'Object') {\n return selector as Filter<ModelClass>\n }\n\n return {\n _id: 'shouldReturnNull',\n } as Filter<ModelClass>\n}\n","import {Collection, Find, ModelClassBase} from '../../types'\nimport getSelector from './getSelector'\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const find: Find<DocumentType> = (...args: any[]) => {\n const selector = getSelector(args)\n const options = args[1]\n\n return collection.rawCollection.find(selector, options) as any\n }\n\n return find\n}\n","import getSelector from './getSelector'\nimport {Collection, FindOne, ModelClassBase} from '../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const findOne: FindOne<DocumentType> = async (...args: any[]) => {\n const options = args[1]\n await collection.connectionPromise\n const selector = getSelector<DocumentType>(args)\n const item = (await collection.rawCollection.findOne(selector, options)) as DocumentType\n\n if (!item) return item\n return item\n }\n\n return findOne\n}\n","import {validate} from '@orion-js/schema'\nimport fromDot from '../../../helpers/fromDot'\n\n/**\n * Validates $push and $addToSet\n */\nexport default async function ({schema, operationDoc, operation}) {\n for (const key of Object.keys(operationDoc)) {\n const value = operationDoc[key]\n let toValidate = null\n if (operation === '$push' || operation === '$addToSet') {\n if (typeof value === 'object' && '$each' in value) {\n toValidate = value.$each\n } else {\n toValidate = [value]\n }\n }\n const validationObject = fromDot({[key]: toValidate})\n await validate(schema, validationObject, {omitRequired: true})\n }\n}\n","import dot from 'dot-object'\nimport toDot from './toDot'\n\nexport default function fromDot(doc: any): any {\n doc = toDot(doc)\n return dot.object(doc)\n}\n","import Dot from 'dot-object'\n\nvar dot = new Dot('.', false, true, false)\n\nexport default function (doc) {\n return dot.dot(doc)\n}\n","import {validateKey, ValidationError} from '@orion-js/schema'\n\n/**\n * Validates $unset\n */\nexport default async function ({schema, operationDoc}) {\n const errors = {}\n for (const key of Object.keys(operationDoc)) {\n const error = await validateKey(schema, key, null)\n if (error) {\n errors[key] = error\n }\n }\n if (Object.keys(errors).length) {\n throw new ValidationError(errors)\n }\n}\n","import {validateKey, ValidationError} from '@orion-js/schema'\n\n/**\n * Validates $inc\n */\nexport default async function ({schema, operationDoc}) {\n const errors = {}\n for (const key of Object.keys(operationDoc)) {\n const value = operationDoc[key]\n const error = await validateKey(schema, key, value)\n if (error) {\n errors[key] = error\n }\n }\n if (Object.keys(errors).length) {\n throw new ValidationError(errors)\n }\n}\n","import {validate} from '@orion-js/schema'\nimport fromDot from '../../../helpers/fromDot'\nimport toDot from '../../../helpers/toDot'\n\n/**\n * Validates $set\n */\nexport default async function ({schema, operationDoc}) {\n let cleaned = toDot(operationDoc)\n\n const transformedObj = {}\n Object.keys(cleaned).map(key => {\n const newKey = key.replace('$.', '0.')\n transformedObj[newKey] = cleaned[key]\n })\n\n cleaned = fromDot(transformedObj)\n\n await validate(schema, cleaned, {omitRequired: true})\n}\n","import validatePush from './validatePush'\nimport validateUnset from './validateUnset'\nimport validateInc from './validateInc'\nimport validateSet from './validateSet'\n\nconst shouldCheck = function (key: string): boolean {\n if (key === '$pushAll') throw new Error('$pushAll is not supported, use $push + $each')\n return ['$pull', '$pullAll', '$pop', '$slice'].indexOf(key) === -1\n}\n\nexport default async function ({schema, operationDoc, operation}) {\n if (!shouldCheck(operation)) return\n\n if (operation === '$set') {\n await validateSet({schema, operationDoc})\n } else if (operation === '$unset') {\n await validateUnset({schema, operationDoc})\n } else if (operation === '$inc') {\n await validateInc({schema, operationDoc})\n } else if (operation === '$push' || operation === '$addToSet') {\n await validatePush({schema, operationDoc, operation})\n } else {\n throw new Error(operation + ' operation is not supported yet')\n }\n}\n","// inspired by https://github.com/aldeed/simple-schema-js\nimport validateOperator from './validateOperator'\n\nexport default async function validateModifier(schema, modifier) {\n for (const operation of Object.keys(modifier)) {\n const operationDoc = modifier[operation]\n // If non-operators are mixed in, throw error\n if (operation.slice(0, 1) !== '$') {\n throw new Error(`Expected '${operation}' to be a modifier operator like '$set'`)\n }\n\n await validateOperator({schema, operationDoc, operation})\n }\n}\n","import validateModifier from './index'\nimport {validate} from '@orion-js/schema'\nimport {omit} from 'rambdax'\nimport fromDot from '../../../helpers/fromDot'\n\nconst getPushSimulation = $push => {\n if (!$push) return {}\n const simulation = {}\n for (const key of Object.keys($push)) {\n const value = $push[key]\n if (typeof value === 'object' && '$each' in value) {\n simulation[key] = value.$each\n } else {\n simulation[key] = [value]\n }\n }\n return simulation\n}\n\nconst simulateNewDoc = (selector, modifier) =>\n fromDot({\n ...selector,\n ...modifier.$set,\n ...modifier.$inc,\n ...getPushSimulation(modifier.$push),\n ...getPushSimulation(modifier.$addToSet),\n ...modifier.$setOnInsert,\n })\n\nconst validateNewDoc = async (schema, selector, modifier) => {\n const doc = simulateNewDoc(selector, modifier)\n await validate(schema, doc)\n}\n\nexport default async function (schema, selector, modifier) {\n await validateNewDoc(schema, selector, modifier)\n await validateModifier(schema, omit(['$setOnInsert'], modifier))\n}\n","import {cleanKey, clean} from '@orion-js/schema'\nimport {isEmpty, isNil, equals} from 'rambdax'\nimport * as MongoDB from 'mongodb'\nimport fromDot from '../../helpers/fromDot'\nimport {ModelClassBase} from '../../types'\n\nconst shouldCheck = key => {\n if (key === '$pushAll') throw new Error('$pushAll is not supported; use $push + $each')\n return ['$pull', '$pullAll', '$pop', '$slice'].indexOf(key) === -1\n}\n\nexport default async function cleanModifier<\n ModelClass extends ModelClassBase,\n TFilter extends MongoDB.UpdateFilter<ModelClass>,\n>(schema, modifier: TFilter, {isUpsert} = {isUpsert: false}) {\n const cleanedModifier: MongoDB.UpdateFilter<MongoDB.Document> = {}\n for (const operation of Object.keys(modifier)) {\n const operationDoc = modifier[operation]\n cleanedModifier[operation] = {}\n // If non-operators are mixed in, throw error\n if (operation.slice(0, 1) !== '$') {\n throw new Error(`Expected '${operation}' to be a modifier operator like '$set'`)\n }\n if (!shouldCheck(operation)) {\n cleanedModifier[operation] = operationDoc\n continue\n }\n\n for (const key of Object.keys(operationDoc)) {\n const value = operationDoc[key]\n const cleanOptions = {forceDoc: operationDoc}\n\n let cleaned = null\n if (operation === '$push' || operation === '$addToSet') {\n if (typeof value === 'object' && '$each' in value) {\n const $each = await cleanKey(schema, key, value.$each, cleanOptions)\n cleaned = {...value, $each}\n } else {\n cleaned = await cleanKey(schema, `${key}.0`, value, cleanOptions)\n }\n }\n\n if (operation === '$set') {\n cleaned = await cleanKey(schema, key, value, cleanOptions)\n }\n\n if (operation === '$setOnInsert') {\n cleaned = await cleanKey(schema, key, value, cleanOptions)\n }\n\n if (operation === '$inc') {\n cleaned = await cleanKey(schema, key, value, cleanOptions)\n }\n\n if (operation === '$unset') {\n const isPresent = await cleanKey(schema, key, 'anyvalue', cleanOptions)\n cleaned = !isNil(isPresent) ? '' : null\n }\n\n if (cleaned !== undefined) {\n cleanedModifier[operation][key] = cleaned\n }\n }\n\n if (isEmpty(cleanedModifier[operation])) {\n delete cleanedModifier[operation]\n }\n }\n\n if (isUpsert) {\n const cleanedSetOnInsert = await clean(schema, fromDot(cleanedModifier.$setOnInsert || {}))\n\n if (!isEmpty(cleanedSetOnInsert)) {\n cleanedModifier.$setOnInsert = cleanedSetOnInsert\n }\n }\n\n if (equals(cleanedModifier, {})) {\n throw new Error('After cleaning your modifier is empty')\n }\n\n return cleanedModifier as TFilter\n}\n","import {ValidationError} from '@orion-js/schema'\n\nexport const wrapErrors = async <TFunc extends () => Promise<any>>(\n operation: TFunc,\n): Promise<ReturnType<TFunc>> => {\n try {\n return await operation()\n } catch (error) {\n if (error.code === 11000) {\n const regex = /index: (?:.*\\.)?\\$?(?:([_a-z0-9]*)(?:_\\d*)|([_a-z0-9]*))\\s*dup key/i\n const match = error.message.match(regex)\n\n if (!match) {\n throw new ValidationError({\n unknownKey: 'notUnique',\n })\n }\n\n const indexNameText = match[1] || match[2]\n const names = indexNameText.split(/_[_a-z0-9]_/)\n const errors = {}\n for (const name of names) {\n errors[name] = 'notUnique'\n }\n\n throw new ValidationError(errors)\n }\n\n throw error\n }\n}\n","import getSelector from './getSelector'\nimport validateUpsert from './validateModifier/validateUpsert'\nimport cleanModifier from './cleanModifier'\nimport {Collection, ModelClassBase, Upsert} from '../../types'\nimport {wrapErrors} from './wrapErrors'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const upsert: Upsert<DocumentType> = async function (selectorArg, modifierArg, options = {}) {\n await collection.connectionPromise\n let modifier = modifierArg as any\n let selector = getSelector(arguments)\n\n modifier.$setOnInsert = {...modifier.$setOnInsert, _id: collection.generateId()}\n\n if (collection.schema) {\n const schema = collection.getSchema()\n\n if (options.clean !== false) {\n selector = (await cleanModifier(schema, {$set: selector})).$set\n modifier = await cleanModifier(schema, modifier, {isUpsert: true})\n }\n if (options.validate !== false) await validateUpsert(schema, selector, modifier)\n }\n\n const result = await wrapErrors(() => {\n return collection.rawCollection.updateOne(selector, modifier, {\n ...options.mongoOptions,\n upsert: true,\n })\n })\n\n return result\n }\n\n return upsert\n}\n","import getSelector from './getSelector'\nimport validateModifier from './validateModifier'\nimport cleanModifier from './cleanModifier'\nimport {Collection, FindOneAndUpdate, ModelClassBase} from '../../types'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const findOneAndUpdate: FindOneAndUpdate<DocumentType> = async (selector, modifier, options) => {\n await collection.connectionPromise\n const finalSelector = getSelector<DocumentType>([selector])\n\n if (!modifier) {\n throw new Error('Modifier is required when making an update')\n }\n\n if (collection.schema) {\n const schema = collection.getSchema()\n modifier = options?.clean !== false ? await cleanModifier(schema, modifier) : modifier\n if (options?.validate !== false) await validateModifier(schema, modifier)\n }\n\n const result = await collection.rawCollection.findOneAndUpdate(\n finalSelector,\n modifier,\n options?.mongoOptions,\n )\n\n if (!result) return null\n return result\n }\n\n return findOneAndUpdate\n}\n","import getSelector from './getSelector'\nimport {Collection, ModelClassBase, UpdateOne} from '../../types'\nimport cleanModifier from './cleanModifier'\nimport validateModifier from './validateModifier'\nimport {wrapErrors} from './wrapErrors'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const updateOne: UpdateOne<DocumentType> = async function (\n selectorArg,\n modifierArg,\n options = {},\n ) {\n await collection.connectionPromise\n let modifier = modifierArg as any\n const selector = getSelector(arguments)\n\n if (!modifier) {\n throw new Error('Modifier is required when making an update')\n }\n\n if (collection.schema) {\n const schema = collection.getSchema()\n modifier = options.clean !== false ? await cleanModifier(schema, modifier) : modifier\n if (options.validate !== false) await validateModifier(schema, modifier)\n }\n\n const result = await wrapErrors(() => {\n return collection.rawCollection.updateOne(selector, modifier, options.mongoOptions)\n })\n\n return result\n }\n\n return updateOne\n}\n","import getSelector from './getSelector'\nimport {Collection, ModelClassBase, UpdateMany} from '../../types'\nimport cleanModifier from './cleanModifier'\nimport validateModifier from './validateModifier'\nimport {wrapErrors} from './wrapErrors'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const updateMany: UpdateMany<DocumentType> = async function (\n selectorArg,\n modifierArg,\n options = {},\n ) {\n await collection.connectionPromise\n let modifier = modifierArg as any\n const selector = getSelector(arguments)\n\n if (!modifier) {\n throw new Error('Modifier is required when making an update')\n }\n\n if (collection.schema) {\n const schema = collection.getSchema()\n modifier = options.clean !== false ? await cleanModifier(schema, modifier) : modifier\n if (options.validate !== false) await validateModifier(schema, modifier)\n }\n\n const result = await wrapErrors(() => {\n return collection.rawCollection.updateMany(selector, modifier, options.mongoOptions)\n })\n\n return result\n }\n\n return updateMany\n}\n","import {Collection, ModelClassBase, UpdateAndFind} from '../../types'\nimport getSelector from './getSelector'\nimport {wrapErrors} from './wrapErrors'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const updateAndFind: UpdateAndFind<DocumentType> = async function (\n selector,\n modifier,\n options = {},\n ) {\n await collection.connectionPromise\n return await wrapErrors(async () => {\n return await collection.findOneAndUpdate(selector, modifier, {\n ...options,\n mongoOptions: {\n ...options.mongoOptions,\n returnDocument: 'after',\n },\n })\n })\n }\n return updateAndFind\n}\n","import getSelector from './getSelector'\nimport {Collection, DeleteOne, ModelClassBase} from '../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const func: DeleteOne<DocumentType> = async function (selectorArg, options) {\n await collection.connectionPromise\n const selector = getSelector(arguments)\n const result = await collection.rawCollection.deleteOne(selector, options)\n\n return result\n }\n\n return func\n}\n","import getSelector from './getSelector'\nimport {Collection, DeleteMany, ModelClassBase} from '../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const func: DeleteMany<DocumentType> = async function (selectorArg, options) {\n await collection.connectionPromise\n const selector = getSelector(arguments)\n const result = await collection.rawCollection.deleteMany(selector, options)\n\n return result\n }\n\n return func\n}\n","import {Collection, InsertOne, ModelClassBase} from '../../types'\nimport fromDot from '../../helpers/fromDot'\nimport {clean, validate} from '@orion-js/schema'\nimport {wrapErrors} from './wrapErrors'\nimport {isType} from 'rambdax'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const insertOne: InsertOne<DocumentType> = async (insertDoc, options = {}) => {\n await collection.connectionPromise\n let doc = insertDoc as DocumentType\n if (!doc || !isType('Object', doc)) {\n throw new Error('Insert must receive a document')\n }\n\n if (!doc._id) {\n doc._id = collection.generateId()\n }\n\n if (collection.schema) {\n const schema = collection.getSchema()\n doc = await clean(schema, fromDot(doc))\n await validate(schema, doc)\n }\n\n await wrapErrors(async () => {\n await collection.rawCollection.insertOne(doc, options.mongoOptions)\n })\n\n return doc._id\n }\n\n return insertOne\n}\n","import {type} from 'rambdax'\nimport {clone} from '@orion-js/helpers'\nimport {Collection, InsertMany, ModelClassBase} from '../../types'\nimport * as MongoDB from 'mongodb'\nimport fromDot from '../../helpers/fromDot'\nimport {clean, validate} from '@orion-js/schema'\nimport {wrapErrors} from './wrapErrors'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const insertMany: InsertMany<DocumentType> = async (docs, options = {}) => {\n await collection.connectionPromise\n for (let index = 0; index < docs.length; index++) {\n let doc = clone(docs[index]) as any\n\n if (!doc || type(doc) !== 'Object') {\n throw new Error(`Item at index ${index} is not a document`)\n }\n\n if (!doc._id) {\n doc._id = collection.generateId()\n }\n\n if (collection.schema) {\n const schema = collection.getSchema()\n doc = await clean(schema, fromDot(doc))\n await validate(schema, doc)\n }\n\n docs[index] = doc\n }\n const {insertedIds} = await wrapErrors(() => {\n return collection.rawCollection.insertMany(docs as any, options.mongoOptions)\n })\n\n const ids: Array<MongoDB.ObjectId> = Object.values(insertedIds)\n\n return ids.map(id => id.toString())\n }\n\n return insertMany\n}\n","import {Collection, ModelClassBase, UpdateItem} from '../../types'\nimport {wrapErrors} from './wrapErrors'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const updateItem: UpdateItem<DocumentType> = async function (item, modifier, options = {}) {\n await collection.connectionPromise\n const updated = await wrapErrors(async () => {\n return await collection.updateAndFind(item._id, modifier, options)\n })\n\n for (const key in item) {\n delete item[key]\n }\n\n for (const key in updated) {\n item[key] = updated[key]\n }\n }\n return updateItem\n}\n","import getSelector from './getSelector'\nimport {Collection, CountDocuments, DeleteOne, ModelClassBase} from '../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const func: CountDocuments<DocumentType> = async function (selectorArg, options) {\n await collection.connectionPromise\n const selector = getSelector(arguments)\n const result = await collection.rawCollection.countDocuments(selector, options)\n\n return result\n }\n\n return func\n}\n","import {Collection, EstimatedDocumentCount, ModelClassBase} from '../../types'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const func: EstimatedDocumentCount<DocumentType> = async function (options) {\n await collection.connectionPromise\n const result = await collection.rawCollection.estimatedDocumentCount(options)\n return result\n }\n\n return func\n}\n","import {type} from 'rambdax'\nimport {Collection, InsertAndFind, ModelClassBase} from '../../types'\nimport fromDot from '../../helpers/fromDot'\nimport {clean, validate} from '@orion-js/schema'\nimport {wrapErrors} from './wrapErrors'\n\nexport default <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) => {\n const insertAndFind: InsertAndFind<DocumentType> = async (insertDoc, options = {}) => {\n await collection.connectionPromise\n let doc = insertDoc as any\n if (!doc || type(doc) !== 'Object') {\n throw new Error('Insert must receive a document')\n }\n\n if (!doc._id) {\n doc._id = collection.generateId()\n }\n\n if (collection.schema) {\n const schema = collection.getSchema()\n doc = await clean(schema, fromDot(doc))\n await validate(schema, doc)\n }\n\n await wrapErrors(async () => {\n await collection.rawCollection.insertOne(doc, options.mongoOptions)\n })\n\n return doc\n }\n\n return insertAndFind\n}\n","import {Collection, DataLoader, ModelClassBase} from '../../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const loadById: DataLoader.LoadById<DocumentType> = async id => {\n const result = await collection.loadOne({\n key: '_id',\n value: id,\n })\n\n return result\n }\n\n return loadById\n}\n","import {Collection, DataLoader, ModelClassBase} from '../../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const loadMany: DataLoader.LoadMany<DocumentType> = async options => {\n const results = await collection.loadData(options)\n return results\n }\n\n return loadMany\n}\n","import {Collection, DataLoader, ModelClassBase} from '../../../types'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const loadOne: DataLoader.LoadOne<DocumentType> = async options => {\n const [result] = await collection.loadData(options)\n return result\n }\n\n return loadOne\n}\n","import {createMapArray, clone} from '@orion-js/helpers'\nimport {DataLoader, Collection, ModelClassBase, ModelToMongoSelector} from '../../../types'\nimport dataLoad from './dataLoad'\n\nexport default function <DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n const loadData: DataLoader.LoadData<DocumentType> = async options => {\n await collection.connectionPromise\n\n const result = await dataLoad({\n loaderKey: {\n key: options.key,\n match: options.match,\n sort: options.sort,\n project: options.project,\n collectionName: collection.name,\n },\n id: options.value,\n ids: options.values,\n timeout: options.timeout,\n load: async values => {\n const query = {\n ...clone(options.match),\n [options.key]: {$in: values},\n } as ModelToMongoSelector<DocumentType>\n\n const cursor = collection.find(query)\n\n if (options.sort) {\n cursor.sort(options.sort)\n }\n\n if (options.project) {\n cursor.project(options.project)\n }\n\n if (options.debug) {\n console.info(`Will execute data loading query now on ${collection.name}: `, query)\n }\n\n const items = await cursor.toArray()\n\n const itemsMap = createMapArray(items, options.key as string)\n return values.map(value => {\n return itemsMap[value] || []\n })\n },\n })\n\n return result\n }\n\n return loadData\n}\n","import DataLoader from 'dataloader'\n\nexport const cache = new Map()\n\ninterface Options {\n key: string\n func: (ids: Array<string>) => Promise<any>\n timeout: number\n}\n\nexport const getDataLoader = (params: Options): DataLoader<any, any> => {\n const {key, func, timeout} = params\n\n const existing = cache.get(key)\n if (existing) return existing\n\n const load = async (ids: Array<string>) => {\n cache.delete(key)\n return await func(ids)\n }\n\n const options = {\n batchScheduleFn: callback => setTimeout(callback, timeout),\n }\n\n const dataLoader = new DataLoader(load, options)\n\n cache.set(key, dataLoader)\n\n return dataLoader\n}\n","import {getDataLoader} from './getDataLoader'\nimport {flatten} from 'rambdax'\nimport {hashObject} from '@orion-js/helpers'\n\ninterface Options {\n loaderKey: any\n load: (values: Array<string>) => Promise<any>\n timeout?: number\n ids?: Array<string>\n id?: string\n}\n\nconst dataLoad = async (options: Options) => {\n const dataLoader = getDataLoader({\n key: hashObject(options.loaderKey),\n func: options.load,\n timeout: options.timeout || 5,\n })\n\n if (options.ids) {\n const resultArray = await dataLoader.loadMany(options.ids)\n return flatten(resultArray)\n }\n\n return await dataLoader.load(options.id)\n}\n\nexport default dataLoad\n","import {generateId, generateUUID} from '@orion-js/helpers'\nimport {ObjectId} from 'bson'\nimport {CreateCollectionOptions, ModelClassBase} from '..'\nimport {FieldType} from '@orion-js/schema'\n\nconst getIdGenerator = <DocumentType extends ModelClassBase>(\n options: CreateCollectionOptions,\n): (() => DocumentType['_id']) => {\n if (!options.idPrefix && options?.schema?._id) {\n const idField = options.schema._id.type as FieldType\n if (idField.name?.startsWith('typedId:')) {\n return () => {\n const prefix = idField.name.split(':')[1]\n const random = generateUUID()\n return `${prefix}-${random}`\n }\n }\n }\n\n if (options.idPrefix || options.idGeneration === 'uuid') {\n return () => {\n const prefix = options.idPrefix || ''\n const random = generateUUID()\n return `${prefix}${random}`\n }\n }\n\n if (options.idGeneration === 'random') {\n return () => {\n const prefix = options.idPrefix || ''\n const random = generateId()\n return `${prefix}${random}`\n }\n }\n\n return () => {\n const id = new ObjectId()\n\n return id.toString()\n }\n}\n\nexport default getIdGenerator\n","import {MongoExpiredSessionError, MongoNotConnectedError} from 'mongodb'\nimport {Collection, ModelClassBase} from '..'\nimport {logger} from '@orion-js/logger'\n\nfunction matchingDefinition(defIndex, curIndex) {\n if (defIndex.options && defIndex.options.name === curIndex.name) return true\n const defIndexName = Object.keys(defIndex.keys)\n .map(key => `${key}_${defIndex.keys[key]}`)\n .join('_')\n return defIndexName === curIndex.name\n}\n\nexport async function checkIndexes<DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n) {\n await collection.connectionPromise\n\n let currentIndexes = []\n try {\n currentIndexes = await collection.rawCollection.indexes()\n } catch (error) {\n if (error.codeName !== 'NamespaceNotFound') throw error\n }\n\n const indexesToDelete = collection.indexes\n ? currentIndexes.filter(\n index =>\n index.name !== '_id_' &&\n !collection.indexes.find(definitionIndex => matchingDefinition(definitionIndex, index)),\n )\n : currentIndexes\n\n if (indexesToDelete.length > 0) {\n logger.warn(\n `${indexesToDelete.length} unexpected indexes found in collection \"${\n collection.name\n }\": ${indexesToDelete\n .map(i => i.name)\n .join(', ')} | Delete the index or fix the collection definition`,\n )\n }\n}\nexport async function loadIndexes<DocumentType extends ModelClassBase>(\n collection: Partial<Collection<DocumentType>>,\n): Promise<string[]> {\n if (!collection.indexes) return\n if (!collection.indexes.length) return\n\n await collection.connectionPromise\n\n const results = Promise.all(\n collection.indexes.map(async ({keys, options}) => {\n try {\n return await collection.rawCollection.createIndex(keys, options)\n } catch (error) {\n if (error.code === 85 || error.code === 86) {\n console.info('Will delete index to create the new version')\n const indexName = (() => {\n const message = error.errorResponse.errmsg\n const indexName = message.split('name: \"')[1].split('\"')[0]\n return indexName\n })()\n await collection.rawCollection.dropIndex(indexName)\n console.info('Index was deleted, creating new index')\n const result = await collection.rawCollection.createIndex(keys, options)\n console.info('Index updated correctly')\n return result\n }\n if (error instanceof MongoExpiredSessionError || error instanceof MongoNotConnectedError) {\n // this errors is thrown when we are on tests environment\n // but it's not a problem never, index will be created on the next connection\n } else {\n console.error(`Error creating index for collection ${collection.name}: ${error.message}`)\n console.error(error)\n return error.message\n }\n }\n }),\n )\n\n await checkIndexes(collection)\n\n return results\n}\n","import {Schema} from '@orion-js/schema'\nimport {type} from 'rambdax'\nimport {clone} from '@orion-js/helpers'\nimport {CreateCollectionOptions} from '../types'\n\n// @ts-ignore polyfill for Symbol.metadata // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#decorator-metadata\nSymbol.metadata ??= Symbol('Symbol.metadata')\n\nexport function prepareShema(schema: Schema): Schema {\n if (!schema._id) {\n schema._id = {\n type: String,\n }\n }\n return schema\n}\n\nexport function getSchema(options: CreateCollectionOptions): Schema {\n if (!options.schema) return\n\n if (options.schema[Symbol.metadata]?._getModel) {\n return options.schema[Symbol.metadata]._getModel().getSchema()\n }\n\n // schema is a model\n if (options.schema.getSchema) {\n const schema = options.schema.getSchema()\n return prepareShema(schema)\n }\n\n // schema is a typed model\n if (options.schema.getModel) {\n const model = options.schema.getModel()\n const schema = model ? clone(model.getSchema()) : {}\n return prepareShema(schema)\n }\n\n if (type(options.schema) === 'Object') {\n return prepareShema(options.schema)\n }\n}\n","import {Collection} from '../types'\nimport {logger} from '@orion-js/logger'\n\nexport function wrapMethods(collection: Partial<Collection>) {\n // Wrap all collection methods to ensure connection is started\n const methodsWithPromises = [\n 'findOne',\n 'findOneAndUpdate',\n 'insertOne',\n 'insertMany',\n 'insertAndFind',\n 'updateOne',\n 'updateMany',\n 'deleteMany',\n 'deleteOne',\n 'upsert',\n 'estimatedDocumentCount',\n 'countDocuments',\n 'updateAndFind',\n 'updateItem',\n 'loadData',\n 'loadById',\n 'loadOne',\n 'loadMany',\n ]\n\n const methodsWithoutPromises = ['aggregate', 'find', 'watch']\n\n const originalMethods = {...collection}\n\n for (const methodName of methodsWithPromises) {\n if (typeof collection[methodName] === 'function') {\n collection[methodName] = async (...args: any[]) => {\n await collection.startConnection()\n return originalMethods[methodName](...args)\n }\n }\n\n for (const methodName of methodsWithoutPromises) {\n if (typeof collection[methodName] === 'function') {\n collection[methodName] = (...args: any[]) => {\n collection.startConnection()\n if (!collection.rawCollection) {\n logger.error('Method called before connection was initialized', {\n collectionName: collection.name,\n connectionName: collection.connectionName,\n methodName,\n })\n throw new Error('Method called before connection was initialized')\n }\n return originalMethods[methodName](...args)\n }\n }\n }\n }\n}\n","import {\n BaseCollection,\n Collection,\n CreateCollectionOptions,\n CreateCollectionOptionsWithSchemaType,\n CreateCollectionOptionsWithTypedSchema,\n InferSchemaTypeWithId,\n ModelClassBase,\n SchemaWithRequiredId,\n} from '../types'\nimport {\n countDocuments,\n deleteMany,\n deleteOne,\n estimatedDocumentCount,\n find,\n findOne,\n findOneAndUpdate,\n insertMany,\n insertOne,\n updateAndFind,\n updateItem,\n updateMany,\n updateOne,\n upsert,\n insertAndFind,\n} from './getMethods'\nimport {loadById, loadOne, loadMany, loadData} from './getMethods/dataLoader'\nimport getIdGenerator from './generateId'\nimport {loadIndexes} from './createIndexes'\nimport {getMongoConnection} from '..'\nimport {getSchema} from './getSchemaAndModel'\nimport {wrapMethods} from './wrapMethods'\nimport {InferSchemaType, TypedSchemaOnSchema} from '@orion-js/schema'\nimport {MongoClient} from 'mongodb'\n\nexport const createIndexesPromises = []\n\nexport function createCollection<T extends SchemaWithRequiredId>(\n options: CreateCollectionOptionsWithSchemaType<T>,\n): Collection<InferSchemaTypeWithId<T>>\n\nexport function createCollection<T extends TypedSchemaOnSchema & {prototype: {_id: string}}>(\n options: CreateCollectionOptionsWithTypedSchema<T>,\n): Collection<InferSchemaType<T>>\n\nexport function createCollection<T extends ModelClassBase>(\n options: CreateCollectionOptions<T>,\n): Collection<T>\n\nexport function createCollection(options: CreateCollectionOptions) {\n const connectionName = options.connectionName || 'main'\n\n const orionConnection = getMongoConnection({name: connectionName})\n if (!orionConnection) {\n throw new Error(`The connection to MongoDB \"${connectionName}\" was not found`)\n }\n\n const schema = getSchema(options)\n\n let resolveCollectionPromise: (MongoClient) => void\n const collectionPromise = new Promise<MongoClient>(resolve => {\n resolveCollectionPromise = resolve\n })\n\n const baseCollection: Partial<Collection<any>> = {\n name: options.name,\n connectionName,\n schema,\n indexes: options.indexes || [],\n client: orionConnection,\n connectionPromise: collectionPromise,\n startConnection: () => orionConnection.startConnection(),\n generateId: getIdGenerator(options),\n getRawCollection: async () => {\n await orionConnection.startConnection()\n return orionConnection.db.collection(options.name)\n },\n getSchema: () => schema,\n }\n\n const encryptedCollection: Partial<Collection<any>> = {\n ...baseCollection,\n getRawCollection: async () => {\n await orionConnection.startConnection()\n return orionConnection.encrypted.db.collection(options.name)\n },\n }\n\n const mainCollection: Partial<Collection<any>> = {\n ...baseCollection,\n encrypted: encryptedCollection as BaseCollection<ModelClassBase>,\n }\n\n const defineCollectionProperties = () => {\n if (orionConnection.db) {\n mainCollection.db = orionConnection.db\n mainCollection.rawCollection = orionConnection.db.collection(options.name)\n }\n\n if (orionConnection.encrypted.db) {\n encryptedCollection.db = orionConnection.encrypted.db\n encryptedCollection.rawCollection = orionConnection.encrypted.db.collection(options.name)\n }\n }\n\n defineCollectionProperties()\n\n orionConnection.connectionPromise.then(() => {\n defineCollectionProperties()\n resolveCollectionPromise(orionConnection.client)\n })\n\n const collections = [mainCollection, encryptedCollection]\n\n for (const collection of collections) {\n // modified orion methods\n collection.findOne = findOne(collection)\n collection.find = find(collection)\n collection.findOneAndUpdate = findOneAndUpdate(collection)\n collection.insertOne = insertOne(collection)\n collection.insertMany = insertMany(collection)\n collection.insertAndFind = insertAndFind(collection)\n collection.updateOne = updateOne(collection)\n collection.updateMany = updateMany(collection)\n collection.deleteMany = deleteMany(collection)\n collection.deleteOne = deleteOne(collection)\n collection.upsert = upsert(collection)\n\n // counts\n collection.estimatedDocumentCount = estimatedDocumentCount(collection)\n collection.countDocuments = countDocuments(collection)\n\n // update and find\n collection.updateAndFind = updateAndFind(collection)\n collection.updateItem = updateItem(collection)\n\n // plain passed methods\n collection.aggregate = (pipeline, options) =>\n collection.rawCollection.aggregate(pipeline, options)\n collection.watch = (pipeline, options) => collection.rawCollection.watch(pipeline, options)\n\n // data loader\n collection.loadData = loadData(collection)\n collection.loadById = loadById(collection)\n collection.loadOne = loadOne(collection)\n collection.loadMany = loadMany(collection)\n collection.createIndexes = async () => []\n }\n\n const createIndexes = async () => {\n await orionConnection.startConnection()\n const createIndexPromise = loadIndexes(mainCollection)\n createIndexesPromises.push(createIndexPromise)\n mainCollection.createIndexesPromise = createIndexPromise\n return createIndexPromise\n }\n\n mainCollection.createIndexes = createIndexes\n\n if (!process.env.DONT_CREATE_INDEXES_AUTOMATICALLY) {\n createIndexes()\n }\n\n wrapMethods(mainCollection as any)\n wrapMethods(encryptedCollection as any)\n\n return mainCollection as Collection<ModelClassBase>\n}\n","import {logger} from '@orion-js/logger'\nimport {AWSEncryptionKeyOptions, ClientEncryption, KMSProviders, MongoClient, UUID} from 'mongodb'\nimport {getMongoURLFromEnv} from '../connect/getMongoURLFromEnv'\n\nexport async function getOrCreateEncryptionKey({\n keyAltName,\n kmsProvider,\n masterKey,\n connectionName = 'main',\n keyVaultDatabase = 'encryption',\n keyVaultCollection = '__keyVault',\n kmsProviders,\n}: {\n keyAltName: string\n kmsProvider: keyof KMSProviders\n masterKey?: AWSEncryptionKeyOptions\n connectionName?: string\n keyVaultDatabase?: string\n keyVaultCollection?: string\n kmsProviders: KMSProviders\n}): Promise<{key: UUID; keyVaultNamespace: string}> {\n const keyVaultNamespace = `${keyVaultDatabase}.${keyVaultCollection}`\n\n logger.info('Connecting to database to get or create the encryption key', {\n keyVaultNamespace,\n keyAltName,\n })\n const client = new MongoClient(getMongoURLFromEnv(connectionName))\n await client.connect()\n const db = client.db(keyVaultDatabase)\n const collection = db.collection(keyVaultCollection)\n await collection.createIndex(\n {keyAltName: 1},\n {unique: true, partialFilterExpression: {keyAltName: {$exists: true}}},\n )\n const clientEncryption = new ClientEncryption(client, {\n keyVaultNamespace,\n kmsProviders,\n })\n\n const key = await clientEncryption.getKeyByAltName(keyAltName)\n if (key) {\n logger.info('Key found on the key vault', {\n keyVaultNamespace,\n keyAltName,\n UUID: key._id,\n })\n return {key: key._id, keyVaultNamespace}\n }\n\n logger.info('Key not found on the key vault, creating a new one', {\n keyVaultNamespace,\n keyAltName,\n })\n\n const newKey = await clientEncryption.createDataKey(kmsProvider, {\n keyAltNames: [keyAltName],\n ...(masterKey ? {masterKey} : {}),\n })\n\n logger.info('New encryption key created', {\n keyVaultNamespace,\n keyAltName,\n UUID: newKey,\n })\n\n return {key: newKey, keyVaultNamespace}\n}\n\nexport const ENCRYPTION_ALGORITHMS = {\n DETERMINISTIC: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic',\n RANDOM: 'AEAD_AES_256_CBC_HMAC_SHA_512-Random',\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAA2B;AAC3B,qBAAkD;;;ACDnC,SAAR,UAA2B,KAAqB;AACrD,MAAI,SAAS;AACb,MAAI,iBAAiB;AAErB,QAAM,sBAAsB,IAAI,QAAQ,IAAI,IAAI;AAEhD,MAAI,IAAI,QAAQ,GAAG,MAAM,IAAI;AAC3B,qBAAiB,IAAI,UAAU,qBAAqB,IAAI,QAAQ,GAAG,CAAC;AAAA,EACtE,OAAO;AACL,qBAAiB,IAAI,UAAU,mBAAmB;AAAA,EACpD;AAEA,MAAI,eAAe,QAAQ,OAAO,MAAM,IAAI;AAC1C,QAAI,eAAe,QAAQ,QAAQ,MAAM,IAAI;AAC3C,eAAS,eAAe,MAAM,QAAQ,EAAE,CAAC;AAAA,IAC3C;AAAA,EACF,WAAW,eAAe,QAAQ,GAAG,MAAM,IAAI;AAC7C,aAAS,eAAe,MAAM,GAAG,EAAE,CAAC;AAAA,EACtC;AAEA,SAAO;AACT;;;ADlBA,0BAAu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,KAAK,OAAO,GAAG,gBAAgB;AACrC,QAAM,aAAa,GAAG,WAAW,kBAAkB;AACnD,QAAM,WAAW;AAAA,IACf,EAAC,YAAY,EAAC;AAAA,IACd,EAAC,QAAQ,MAAM,yBAAyB,EAAC,YAAY,EAAC,SAAS,KAAI,EAAC,EAAC;AAAA,EACvE;AACA,QAAM,mBAAmB,IAAI,iCAAiB,QAAQ;AAAA,IACpD;AAAA,IACA;AAAA,EACF,CAAC;AAED,QAAM,MAAM,MAAM,iBAAiB,gBAAgB,UAAU;AAC7D,MAAI,KAAK;AACP,0BAAO,KAAK,8BAA8B;AAAA,MACxC;AAAA,MACA;AAAA,MACA,MAAM,IAAI;AAAA,IACZ,CAAC;AACD,WAAO,EAAC,KAAK,IAAI,KAAK,kBAAiB;AAAA,EACzC;AAEA,wBAAO,KAAK,sDAAsD;AAAA,IAChE;AAAA,IACA;AAAA,EACF,CAAC;AAED,QAAM,SAAS,MAAM,iBAAiB,cAAc,aAAa;AAAA,IAC/D,aAAa,CAAC,UAAU;AAAA,IACxB,GAAI,YAAY,EAAC,UAAS,IAAI,CAAC;AAAA,EACjC,CAAC;AAED,wBAAO,KAAK,8BAA8B;AAAA,IACxC;AAAA,IACA;AAAA,IACA,MAAM;AAAA,EACR,CAAC;AAED,SAAO,EAAC,KAAK,QAAQ,kBAAiB;AACxC;AAEO,IAAM,wBAAwB;AAAA,EACnC,eAAe;AAAA,EACf,QAAQ;AACV;","names":["value","import_schema","import_dot_object","Dot","dot","import_schema","import_schema","import_schema","import_schema","import_schema","shouldCheck","import_schema","import_schema","import_helpers","import_schema","import_schema","import_helpers","DataLoader","import_helpers","import_helpers","import_mongodb","import_logger","indexName","import_helpers","import_logger","methodName","options","import_logger","import_mongodb"]}