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AA,GACzD,OAAQ,iBAAE,KAAK,EAAoB,CAAE,SAAU,EAAE,UAClD,IAGG,EAAqB,EAAoB,KAAK,SAAA,GAAA,OAAK,EAAE,IAAP,IAE7C,KAAK,WAAc,EAAmB,O,kCACnB,IAAI,oBAAQ,SAAU,GAC1C,mBAAI,OAAO,CACT,KAAM,WACN,QAAS,4IACT,KAAM,qBACN,QAAS,IACR,SAAC,GACF,EAAQ,EACT,GACF,I,QATK,E,OAWN,EAAqB,EAAQ,mB,yBAGM,eAClC,KAAK,CACJ,KAAM,CAAE,IAAK,KACZ,O,WAHC,E,QAKF,EAAmB,O,wBACrB,KAAK,IAAL,0BAAmC,GAAG,EAAmB,KAAK,OAAQ,KAAtE,kB,UACM,eAAe,OAAO,CAC1B,KAAM,CAAE,IAAK,K,iCAIV,G,wCAEP,KAAK,IAAI,uDAAuD,K,yTAe5D,KAAK,O,uBACc,eAAe,OAAO,KAAK,CAAE,UAAW,I,cAA3D,E,QACU,QAAQ,KAAK,IAAI,mCAAmC,Q,kBAC7D,EAAW,KAAI,SAAC,GAKrB,OAJA,EAAK,KACW,MAAX,EAAE,MAAgB,UAAY,WAAuB,MAAX,EAAE,MAAe,QAAU,OAAxE,IACI,EAAE,UAED,EAAE,QACV,K,oGAML,SAAS,aAAa,GACpB,GAAI,GAAuB,UAAd,EAAM,KACjB,MAAM,IAAI,eAAJ,qCAAwD,EAAM,KAA9D,IAET,C,gBAtVoB,SAyVrB,OAAO,QAAU","file":"/npm/@propellerheads/migrate-mongoose-typescript@3.3.3/dist/lib.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/@propellerheads/migrate-mongoose-typescript@3.3.3/dist/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","import path from 'path';\nimport fs from 'fs';\nimport mkdirp from 'mkdirp';\nimport Promise from 'bluebird';\nimport 'colors';\nimport mongoose from 'mongoose';\nimport _ from 'lodash';\nimport ask from 'inquirer';\n\nimport MigrationModelFactory from './db';\nlet MigrationModel;\n\nPromise.config({\n  warnings: false\n});\n\nconst es6Template =\n`\n/**\n * Make any changes you need to make to the database here\n */\nexport async function up () {\n  // Write migration here\n}\n\n/**\n * Make any changes that UNDO the up function side effects here (if possible)\n */\nexport async function down () {\n  // Write migration here\n}\n`;\n\nconst es5Template =\n`'use strict';\n\n/**\n * Make any changes you need to make to the database here\n */\nexports.up = function up (done) {\n  done();\n};\n\n/**\n * Make any changes that UNDO the up function side effects here (if possible)\n */\nexports.down = function down(done) {\n  done();\n};\n`;\n\n\nexport default class Migrator {\n  constructor({\n    templatePath,\n    migrationsPath = './migrations',\n    dbConnectionUri,\n    es6Templates = false,\n    typescript = false,\n    collectionName = 'migrations',\n    autosync = false,\n    cli = false,\n    connection\n  }) {\n    const defaultTemplate = typescript || es6Templates ?  es6Template : es5Template;\n    this.template = templatePath ? fs.readFileSync(templatePath, 'utf-8') : defaultTemplate;\n    this.migrationPath = path.resolve(migrationsPath);\n    this.connection = connection || mongoose.createConnection(dbConnectionUri);\n    this.es6 = es6Templates;\n    this.typescript = typescript;\n    this.collection = collectionName;\n    this.autosync = autosync;\n    this.cli = cli;\n    MigrationModel = MigrationModelFactory(collectionName, this.connection, {typescript});\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  }\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   * Generate name for migration file with right extension\n   * @param basename\n   * @return {string}\n   */\n  getMigrationFileName(basename) {\n    if (this.typescript) {\n      return `${basename}.ts`\n    };\n    return `${basename}.js`;\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 = this.getMigrationFileName(`${now}-${migrationName}`);\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    const untilMigration = migrationName ?\n      await MigrationModel.findOne({name: migrationName}) :\n      await MigrationModel.findOne().sort({createdAt: -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      throw new Error('There are no migrations to run');\n    }\n\n    let self = this;\n    let numMigrationsRan = 0;\n    let migrationsRan = [];\n\n    for (const migration of migrationsToRun) {\n      const migrationFilePath = path.join(self.migrationPath, migration.filename);\n      if (this.es6) {\n        require('babel-register')({\n          \"presets\": [require(\"babel-preset-latest\")],\n          \"plugins\": [require(\"babel-plugin-transform-runtime\")]\n        });\n\n        require('babel-polyfill');\n      }\n\n      if (this.typescript) {\n        require(\"ts-node\").register({\n          disableWarnings: true,\n          transpileOnly: true\n        });\n      }\n\n      let migrationFunctions;\n\n      try {\n        migrationFunctions = require(migrationFilePath);\n      } catch (err) {\n        err.message = err.message && /Unexpected token/.test(err.message) ?\n          'Unexpected Token when parsing migration. If you are using an ES6 migration file, use option --es6' :\n          err.message;\n        throw err;\n      }\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}).update({$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) this.log('All migrations finished successfully.'.green);\n    return migrationsRan;\n  }\n\n  /**\n   * Looks at the file system migrations and imports any migrations that are\n   * on the file system but 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|ts)$/.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   * 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|ts)/.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.remove({\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\n"]}