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D,KAC1D,CACR,CACF,CAWA,UAAM,SACE,KAAK,OACX,MAAM,QAAmB,eAAe,OAAO,KAAK,CAAE,UAAW,IAEjE,OADK,EAAW,QAAQ,KAAK,IAAI,mCAAmC,QAC7D,EAAW,KAAK,IACrB,KAAK,KACH,IAAc,MAAX,EAAE,MAAgB,UAAY,YAAuB,MAAX,EAAE,MAAgB,QAAU,OACzE,IAAI,EAAE,YAED,EAAE,WAEb,EAKF,SAAS,aAAa,GACpB,GAAI,GAAuB,UAAd,EAAM,KACjB,MAAM,IAAI,eAAe,qCAAqC,EAAM,QAExE,CAGA,OAAO,QAAU","file":"/npm/migrate-mongoose-weblium-public@4.0.3/src/lib.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/migrate-mongoose-weblium-public@4.0.3/src/lib.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","const fs = require('fs');\nconst path = require('path');\n\nrequire('colors')\nconst _ = require('lodash');\nconst ask = require('inquirer');\nconst mkdirp = require('mkdirp');\nconst mongoose = require('mongoose');\nconst Promise = require('bluebird');\n\nconst MigrationModelFactory = require('./db');\nlet MigrationModel;\n\nPromise.config({\n  warnings: false\n});\n\nconst migrationTemplate =`/**\n * Make any changes you need to make to the database here\n */\nasync function up () {\n  // Write migration here\n}\n\n/**\n * Make any changes that UNDO the up function side effects here (if possible)\n */\nasync function down () {\n  // Write migration here\n}\n\nmodule.exports = { up, down };\n`;\n\nclass Migrator {\n  constructor({\n    templatePath,\n    migrationsPath = './migrations',\n    dbConnectionUri,\n    collectionName = 'migrations',\n    autosync = false,\n    cli = false,\n    connection\n  }) {\n    const defaultTemplate = migrationTemplate;\n    this.template = templatePath ? fs.readFileSync(templatePath, 'utf-8') : defaultTemplate;\n    this.migrationPath = path.resolve(migrationsPath);\n    this.connection = connection || mongoose.createConnection(dbConnectionUri, { useNewUrlParser: true, useUnifiedTopology: true });\n    this.collection = collectionName;\n    this.autosync = autosync;\n    this.cli = cli;\n    MigrationModel = MigrationModelFactory(collectionName, this.connection);\n  }\n\n  log(logString, force = false) {\n    if (force || this.cli) {\n      console.log(logString);\n    }\n  }\n\n  /**\n   * Use your own Mongoose connection object (so you can use this('modelname')\n   * @param {mongoose.connection} connection - Mongoose connection\n   */\n  setMongooseConnection(connection) {\n    MigrationModel = MigrationModelFactory(this.collection, connection)\n    return this\n  }\n\n  /**\n   * Close the underlying connection to mongo\n   * @returns {Promise} A promise that resolves when connection is closed\n   */\n  close() {\n    return this.connection ? this.connection.close() : Promise.resolve();\n  }\n\n  /**\n   * Create a new migration\n   * @param {string} migrationName\n   * @returns {Promise<Object>} A promise of the Migration created\n   */\n  async create(migrationName) {\n    try {\n      const existingMigration = await MigrationModel.findOne({ name: migrationName });\n      if (!!existingMigration) {\n        throw new Error(`There is already a migration with name '${migrationName}' in the database`.red);\n      }\n\n      await this.sync();\n      const now = Date.now();\n      const newMigrationFile = `${now}-${migrationName}.js`;\n      mkdirp.sync(this.migrationPath);\n      fs.writeFileSync(path.join(this.migrationPath, newMigrationFile), this.template);\n      // create instance in db\n      await this.connection;\n      const migrationCreated = await MigrationModel.create({\n        name: migrationName,\n        createdAt: now\n      });\n      this.log(`Created migration ${migrationName} in ${this.migrationPath}.`);\n      return migrationCreated;\n    } catch (error) {\n      this.log(error.stack);\n      fileRequired(error);\n    }\n  }\n\n  /**\n   * Runs migrations up to or down to a given migration name\n   *\n   * @param migrationName\n   * @param direction\n   */\n  async run(direction = 'up', migrationName) {\n    await this.sync();\n\n    if (direction !== 'up' && direction !== 'down') {\n      throw new Error(`The '${direction}' is not supported, use the 'up' or 'down' direction`);\n    }\n\n    const untilMigration = migrationName ?\n      await MigrationModel.findOne({ name: migrationName }) :\n      await MigrationModel.findOne().sort({ createdAt: direction === 'up' ? -1 : 1 });\n\n    if (!untilMigration) {\n      if (migrationName) throw new ReferenceError(\"Could not find that migration in the database\");\n      else throw new Error(\"There are no pending migrations.\");\n    }\n\n    let query = {\n      createdAt: { $lte: untilMigration.createdAt },\n      state: 'down'\n    };\n\n    if (direction == 'down') {\n      query = {\n        createdAt: { $gte: untilMigration.createdAt },\n        state: 'up'\n      };\n    }\n\n\n    const sortDirection = direction == 'up' ? 1 : -1;\n    const migrationsToRun = await MigrationModel.find(query)\n      .sort({ createdAt: sortDirection });\n\n    if (!migrationsToRun.length) {\n      if (this.cli) {\n        this.log('There are no migrations to run'.yellow);\n        this.log(`Current Migrations' Statuses: `);\n        await this.list();\n      }\n    }\n\n    let self = this;\n    let numMigrationsRan = 0;\n    let migrationsRan = [];\n\n    await this.establishConnection(self.migrationPath);\n\n    for (const migration of migrationsToRun) {\n      const migrationFilePath = path.join(self.migrationPath, migration.filename);\n      let migrationFunctions;\n      migrationFunctions = require(migrationFilePath);\n\n      if (!migrationFunctions[direction]) {\n        throw new Error(`The \"${direction}\" export is not defined in ${migration.filename}.`.red);\n      }\n\n      try {\n        await new Promise((resolve, reject) => {\n          const callPromise = migrationFunctions[direction].call(\n            this.connection.model.bind(this.connection),\n            function callback(err) {\n              if (err) return reject(err);\n              resolve();\n            }\n          );\n\n          if (callPromise && typeof callPromise.then === 'function') {\n            callPromise.then(resolve).catch(reject);\n          }\n        });\n\n        this.log(`${direction.toUpperCase()}:   `[direction == 'up' ? 'green' : 'red'] + ` ${migration.filename} `);\n\n        await MigrationModel.where({ name: migration.name }).updateMany({ $set: { state: direction } });\n        migrationsRan.push(migration.toJSON());\n        numMigrationsRan++;\n      } catch (err) {\n        this.log(`Failed to run migration ${migration.name} due to an error.`.red);\n        this.log(`Not continuing. Make sure your data is in consistent state`.red);\n        throw err instanceof (Error) ? err : new Error(err);\n      }\n    }\n\n    if (migrationsToRun.length == numMigrationsRan && numMigrationsRan > 0) this.log('All migrations finished successfully.'.green);\n    return migrationsRan;\n  }\n\n  /**\n   * Set mongoose connection for models\n   */\n  async establishConnection(migrationPath) {\n\n    const initFile = path.join(migrationPath, './init/init-connection.js');\n    try {\n      fs.accessSync(initFile, fs.constants.R_OK);\n    } catch (err) {\n      this.log(`Init connection file not found. Please check \"${initFile}\" path`.yellow);\n      return;\n    }\n\n    try {\n\n      const { init } = require(initFile);\n      await init();\n\n      this.log(`Mongoose connection established`.grey);\n\n    } catch (e) {\n      this.log(`Could not synchronise migrations in the migrations folder up to the database.`.red);\n      throw e;\n    }\n  }\n\n  /**\n   * sync file system -> database\n   * \n   * Imports any migrations that are on the file system but\n   * missing in the database into the database\n   * \n   * This functionality is opposite of prune()\n   */\n  async sync() {\n    try {\n      const filesInMigrationFolder = fs.readdirSync(this.migrationPath);\n      const migrationsInDatabase = await MigrationModel.find({});\n      // Go over migrations in folder and delete any files not in DB\n      const migrationsInFolder = _.filter(filesInMigrationFolder, file => /\\d{13,}\\-.+.js$/.test(file))\n        .map(filename => {\n          const fileCreatedAt = parseInt(filename.split('-')[0]);\n          const existsInDatabase = migrationsInDatabase.some(m => filename == m.filename);\n          return { createdAt: fileCreatedAt, filename, existsInDatabase };\n        });\n\n      const filesNotInDb = _.filter(migrationsInFolder, { existsInDatabase: false }).map(f => f.filename);\n      let migrationsToImport = filesNotInDb;\n      this.log('Synchronizing database with file system migrations...');\n      if (!this.autosync && migrationsToImport.length) {\n        const answers = await new Promise(function (resolve) {\n          ask.prompt({\n            type: 'checkbox',\n            message: 'The following migrations exist in the migrations folder but not in the database. Select the ones you want to import into the database',\n            name: 'migrationsToImport',\n            choices: filesNotInDb\n          }, (answers) => {\n            resolve(answers);\n          });\n        });\n\n        migrationsToImport = answers.migrationsToImport;\n      }\n\n      return Promise.map(migrationsToImport, async (migrationToImport) => {\n        const filePath = path.join(this.migrationPath, migrationToImport),\n          timestampSeparatorIndex = migrationToImport.indexOf('-'),\n          timestamp = migrationToImport.slice(0, timestampSeparatorIndex),\n          migrationName = migrationToImport.slice(timestampSeparatorIndex + 1, migrationToImport.lastIndexOf('.'));\n\n        this.log(`Adding migration ${filePath} into database from file system. State is ` + `DOWN`.red);\n        const createdMigration = await MigrationModel.create({\n          name: migrationName,\n          createdAt: timestamp\n        });\n        return createdMigration.toJSON();\n      });\n    } catch (error) {\n      this.log(`Could not synchronise migrations in the migrations folder up to the database.`.red);\n      throw error;\n    }\n  }\n\n  /**\n   * sync migration database -> file system\n   * \n   * Opposite of sync().\n   * Removes files in migration directory which don't exist in database.\n   */\n  async prune() {\n    try {\n      const filesInMigrationFolder = fs.readdirSync(this.migrationPath);\n      const migrationsInDatabase = await MigrationModel.find({});\n      // Go over migrations in folder and delete any files not in DB\n      const migrationsInFolder = _.filter(filesInMigrationFolder, file => /\\d{13,}\\-.+.js/.test(file))\n        .map(filename => {\n          const fileCreatedAt = parseInt(filename.split('-')[0]);\n          const existsInDatabase = migrationsInDatabase.some(m => filename == m.filename);\n          return { createdAt: fileCreatedAt, filename, existsInDatabase };\n        });\n\n      const dbMigrationsNotOnFs = _.filter(migrationsInDatabase, m => {\n        return !_.find(migrationsInFolder, { filename: m.filename })\n      });\n\n\n      let migrationsToDelete = dbMigrationsNotOnFs.map(m => m.name);\n\n      if (!this.autosync && !!migrationsToDelete.length) {\n        const answers = await new Promise(function (resolve) {\n          ask.prompt({\n            type: 'checkbox',\n            message: 'The following migrations exist in the database but not in the migrations folder. Select the ones you want to remove from the file system.',\n            name: 'migrationsToDelete',\n            choices: migrationsToDelete\n          }, (answers) => {\n            resolve(answers);\n          });\n        });\n\n        migrationsToDelete = answers.migrationsToDelete;\n      }\n\n      const migrationsToDeleteDocs = await MigrationModel\n        .find({\n          name: { $in: migrationsToDelete }\n        }).lean();\n\n      if (migrationsToDelete.length) {\n        this.log(`Removing migration(s) `, `${migrationsToDelete.join(', ')}`.cyan, ` from database`);\n        await MigrationModel.deleteMany({\n          name: { $in: migrationsToDelete }\n        });\n      }\n\n      return migrationsToDeleteDocs;\n    } catch (error) {\n      this.log(`Could not prune extraneous migrations from database.`.red);\n      throw error;\n    }\n  }\n\n  /**\n   * Lists the current migrations and their statuses\n   * @returns {Promise<Array<Object>>}\n   * @example\n   *   [\n   *    { name: 'my-migration', filename: '149213223424_my-migration.js', state: 'up' },\n   *    { name: 'add-cows', filename: '149213223453_add-cows.js', state: 'down' }\n   *   ]\n   */\n  async list() {\n    await this.sync();\n    const migrations = await MigrationModel.find().sort({ createdAt: 1 });\n    if (!migrations.length) this.log('There are no migrations to list.'.yellow);\n    return migrations.map((m) => {\n      this.log(\n        `${m.state == 'up' ? 'UP:  \\t' : 'DOWN:\\t'}`[m.state == 'up' ? 'green' : 'red'] +\n        ` ${m.filename}`\n      );\n      return m.toJSON();\n    });\n  }\n}\n\n\n\nfunction fileRequired(error) {\n  if (error && error.code == 'ENOENT') {\n    throw new ReferenceError(`Could not find any files at path '${error.path}'`);\n  }\n}\n\n\nmodule.exports = Migrator;\n"]}