Parcourir la source

Merge pull request #21202 from overleaf/ls-scripts-to-esm-2

Migrate scripts folder to esm 2/x

GitOrigin-RevId: 1698bc4f13e026fa281d37a4914a2f997849c761
Liangjun Song il y a 1 an
Parent
commit
902ae750dc

+ 1 - 1
services/web/migrations/20190730093801_script_example.mjs

@@ -8,7 +8,7 @@
  * or "hello <name>", when User.findOne() finds something.
  * or "hello <name>", when User.findOne() finds something.
  */
  */
 
 
-import runScript from '../scripts/example/script_for_migration.js'
+import runScript from '../scripts/example/script_for_migration.mjs'
 
 
 const tags = []
 const tags = []
 
 

+ 1 - 1
services/web/migrations/README.md

@@ -46,7 +46,7 @@ undo the changes made in `migrate`.
 #### Running scripts as a migration
 #### Running scripts as a migration
 
 
 To run a script in a migration file, look at `migrations/20190730093801_script_example.js`, which runs the script
 To run a script in a migration file, look at `migrations/20190730093801_script_example.js`, which runs the script
-`scripts/example/script_for_migration.js`. This uses a method where the script can be run standalone via `node`, or
+`scripts/example/script_for_migration.mjs`. This uses a method where the script can be run standalone via `node`, or
 through the migrations' mechanism.
 through the migrations' mechanism.
 
 
 ### Running migrations
 ### Running migrations

+ 2 - 2
services/web/scripts/analytics/helpers/GoogleBigQueryHelper.js → services/web/scripts/analytics/helpers/GoogleBigQueryHelper.mjs

@@ -1,4 +1,4 @@
-const GoogleBigQuery = require('@google-cloud/bigquery').BigQuery
+import { BigQuery as GoogleBigQuery } from '@google-cloud/bigquery'
 
 
 let dataset = null
 let dataset = null
 
 
@@ -25,6 +25,6 @@ async function query(query) {
   return rows
   return rows
 }
 }
 
 
-module.exports = {
+export default {
   query,
   query,
 }
 }

+ 18 - 19
services/web/scripts/analytics/sync_group_subscription_memberships.js → services/web/scripts/analytics/sync_group_subscription_memberships.mjs

@@ -1,13 +1,13 @@
-const GoogleBigQueryHelper = require('./helpers/GoogleBigQueryHelper')
-const { Subscription } = require('../../app/src/models/Subscription')
-const { waitForDb } = require('../../app/src/infrastructure/mongodb')
-const AnalyticsManager = require('../../app/src/Features/Analytics/AnalyticsManager')
-const {
-  DeletedSubscription,
-} = require('../../app/src/models/DeletedSubscription')
-const minimist = require('minimist')
-const _ = require('lodash')
-const { ObjectId } = require('mongodb-legacy')
+import GoogleBigQueryHelper from './helpers/GoogleBigQueryHelper.mjs'
+import { Subscription } from '../../app/src/models/Subscription.js'
+import { waitForDb } from '../../app/src/infrastructure/mongodb.js'
+import AnalyticsManager from '../../app/src/Features/Analytics/AnalyticsManager.js'
+import { DeletedSubscription } from '../../app/src/models/DeletedSubscription.js'
+import minimist from 'minimist'
+import _ from 'lodash'
+import mongodb from 'mongodb-legacy'
+
+const { ObjectId } = mongodb
 
 
 let FETCH_LIMIT, COMMIT, VERBOSE
 let FETCH_LIMIT, COMMIT, VERBOSE
 
 
@@ -260,12 +260,11 @@ const setup = () => {
 }
 }
 
 
 setup()
 setup()
-main()
-  .then(() => {
-    console.error('Done.')
-    process.exit(0)
-  })
-  .catch(error => {
-    console.error({ error })
-    process.exit(1)
-  })
+try {
+  await main()
+  console.error('Done.')
+  process.exit(0)
+} catch (error) {
+  console.error({ error })
+  process.exit(1)
+}

+ 2 - 2
services/web/scripts/delete-duplicate-splittest-versions/delete_test_dupes.js → services/web/scripts/delete-duplicate-splittest-versions/delete_test_dupes.mjs

@@ -1,5 +1,5 @@
-const { db, waitForDb } = require('../../app/src/infrastructure/mongodb')
-const minimist = require('minimist')
+import { db, waitForDb } from '../../app/src/infrastructure/mongodb.js'
+import minimist from 'minimist'
 
 
 const argv = minimist(process.argv.slice(2))
 const argv = minimist(process.argv.slice(2))
 const commit = argv.commit !== undefined
 const commit = argv.commit !== undefined

+ 8 - 10
services/web/scripts/delete-orphaned-docs/delete-orphaned-docs.js → services/web/scripts/delete-orphaned-docs/delete-orphaned-docs.mjs

@@ -1,16 +1,14 @@
-'use strict'
-
-const fs = require('fs')
-const minimist = require('minimist')
-const readline = require('readline')
-
-const {
+import fs from 'fs'
+import minimist from 'minimist'
+import readline from 'readline'
+import {
   db,
   db,
   ObjectId,
   ObjectId,
   waitForDb,
   waitForDb,
-} = require('../../app/src/infrastructure/mongodb')
-const DocstoreManager =
-  require('../../app/src/Features/Docstore/DocstoreManager').promises
+} from '../../app/src/infrastructure/mongodb.js'
+import DocstoreManagerModule from '../../app/src/Features/Docstore/DocstoreManager.js'
+
+const { promises: DocstoreManager } = DocstoreManagerModule
 
 
 const argv = minimist(process.argv.slice(2))
 const argv = minimist(process.argv.slice(2))
 const commit = argv.commit !== undefined
 const commit = argv.commit !== undefined

+ 12 - 9
services/web/scripts/example/script_for_migration.js → services/web/scripts/example/script_for_migration.mjs

@@ -6,7 +6,9 @@
  * in the migrations directory.
  * in the migrations directory.
  */
  */
 
 
-const { User } = require('../../app/src/models/User')
+import { User } from '../../app/src/models/User.js'
+import { fileURLToPath } from 'url'
+
 // const somePackage = require('some-package')
 // const somePackage = require('some-package')
 
 
 const runScript = async () => {
 const runScript = async () => {
@@ -15,13 +17,14 @@ const runScript = async () => {
   console.log(`Hello ${name}!`)
   console.log(`Hello ${name}!`)
 }
 }
 
 
-if (require.main === module) {
-  runScript()
-    .then(() => process.exit())
-    .catch(err => {
-      console.error(err)
-      process.exit(1)
-    })
+if (fileURLToPath(import.meta.url) === process.argv[1]) {
+  try {
+    await runScript()
+    process.exit()
+  } catch (error) {
+    console.error(error)
+    process.exit(1)
+  }
 }
 }
 
 
-module.exports = runScript
+export default runScript

+ 6 - 3
services/web/scripts/history/clean_sl_history_data.js → services/web/scripts/history/clean_sl_history_data.mjs

@@ -1,6 +1,9 @@
-// Increase default mongo query timeout from 1min to 1h
-process.env.MONGO_SOCKET_TIMEOUT = process.env.MONGO_SOCKET_TIMEOUT || '360000'
-const { waitForDb, db } = require('../../app/src/infrastructure/mongodb')
+import { waitForDb, db } from '../../app/src/infrastructure/mongodb.js'
+import { ensureMongoTimeout } from '../helpers/env_variable_helper.mjs'
+// Ensure default mongo query timeout has been increased 1h
+if (!process.env.MONGO_SOCKET_TIMEOUT) {
+  ensureMongoTimeout(360000)
+}
 
 
 async function main() {
 async function main() {
   await checkAllProjectsAreMigrated()
   await checkAllProjectsAreMigrated()

+ 11 - 12
services/web/scripts/history/migrate_ranges_support.js → services/web/scripts/history/migrate_ranges_support.mjs

@@ -1,6 +1,6 @@
-const HistoryRangesSupportMigration = require('../../app/src/Features/History/HistoryRangesSupportMigration')
-const { waitForDb } = require('../../app/src/infrastructure/mongodb')
-const minimist = require('minimist')
+import HistoryRangesSupportMigration from '../../app/src/Features/History/HistoryRangesSupportMigration.mjs'
+import { waitForDb } from '../../app/src/infrastructure/mongodb.js'
+import minimist from 'minimist'
 
 
 async function main() {
 async function main() {
   await waitForDb()
   await waitForDb()
@@ -31,7 +31,7 @@ async function main() {
 }
 }
 
 
 function usage() {
 function usage() {
-  console.error(`Usage: migrate_ranges_support.js [OPTIONS]
+  console.error(`Usage: migrate_ranges_support.mjs [OPTIONS]
 
 
 Options:
 Options:
 
 
@@ -112,11 +112,10 @@ function arrayOpt(value) {
   }
   }
 }
 }
 
 
-main()
-  .then(() => {
-    process.exit(0)
-  })
-  .catch(err => {
-    console.error(err)
-    process.exit(1)
-  })
+try {
+  await main()
+  process.exit(0)
+} catch (error) {
+  console.error(error)
+  process.exit(1)
+}

+ 12 - 12
services/web/scripts/merge_group_subscription_members.js → services/web/scripts/merge_group_subscription_members.mjs

@@ -6,9 +6,10 @@
 // node scripts/merge_group_subscription_members \
 // node scripts/merge_group_subscription_members \
 //  --target [targetSubscriptionId] --source [sourceSubscriptionId] --commit
 //  --target [targetSubscriptionId] --source [sourceSubscriptionId] --commit
 
 
-const { db, ObjectId, waitForDb } = require('../app/src/infrastructure/mongodb')
-const SubscriptionUpdater = require('../app/src/Features/Subscription/SubscriptionUpdater')
-const minimist = require('minimist')
+import { db, ObjectId, waitForDb } from '../app/src/infrastructure/mongodb.js'
+
+import SubscriptionUpdater from '../app/src/Features/Subscription/SubscriptionUpdater.js'
+import minimist from 'minimist'
 const argv = minimist(process.argv.slice(2), {
 const argv = minimist(process.argv.slice(2), {
   string: ['target', 'source'],
   string: ['target', 'source'],
   boolean: ['commit'],
   boolean: ['commit'],
@@ -93,12 +94,11 @@ async function main() {
   }
   }
 }
 }
 
 
-main()
-  .then(() => {
-    console.error('Done.')
-    process.exit(0)
-  })
-  .catch(error => {
-    console.error({ error })
-    process.exit(1)
-  })
+try {
+  await main()
+  console.error('Done.')
+  process.exit(0)
+} catch (error) {
+  console.error({ error })
+  process.exit(1)
+}

+ 10 - 13
services/web/scripts/oauth/backfill_hashed_secrets.js → services/web/scripts/oauth/backfill_hashed_secrets.mjs

@@ -1,11 +1,9 @@
-const {
+import {
   db,
   db,
   waitForDb,
   waitForDb,
   READ_PREFERENCE_SECONDARY,
   READ_PREFERENCE_SECONDARY,
-} = require('../../app/src/infrastructure/mongodb')
-const {
-  hashSecret,
-} = require('../../modules/oauth2-server/app/src/SecretsHelper')
+} from '../../app/src/infrastructure/mongodb.js'
+import { hashSecret } from '../../modules/oauth2-server/app/src/SecretsHelper.js'
 
 
 async function main() {
 async function main() {
   await waitForDb()
   await waitForDb()
@@ -38,11 +36,10 @@ async function hashSecrets(collection, field) {
   console.log(`${hashedCount} secrets hashed`)
   console.log(`${hashedCount} secrets hashed`)
 }
 }
 
 
-main()
-  .then(() => {
-    process.exit(0)
-  })
-  .catch(err => {
-    console.error(err)
-    process.exit(1)
-  })
+try {
+  await main()
+  process.exit(0)
+} catch (error) {
+  console.error(error)
+  process.exit(1)
+}

+ 10 - 13
services/web/scripts/oauth/create_token.js → services/web/scripts/oauth/create_token.mjs

@@ -1,8 +1,6 @@
-const minimist = require('minimist')
-const { waitForDb, db } = require('../../app/src/infrastructure/mongodb')
-const {
-  hashSecret,
-} = require('../../modules/oauth2-server/app/src/SecretsHelper')
+import minimist from 'minimist'
+import { waitForDb, db } from '../../app/src/infrastructure/mongodb.js'
+import { hashSecret } from '../../modules/oauth2-server/app/src/SecretsHelper.js'
 
 
 async function main() {
 async function main() {
   const opts = parseArgs()
   const opts = parseArgs()
@@ -91,11 +89,10 @@ Options:
 `)
 `)
 }
 }
 
 
-main()
-  .then(() => {
-    process.exit(0)
-  })
-  .catch(err => {
-    console.error(err)
-    process.exit(1)
-  })
+try {
+  await main()
+  process.exit(0)
+} catch (error) {
+  console.error(error)
+  process.exit(1)
+}

+ 13 - 14
services/web/scripts/oauth/register_client.js → services/web/scripts/oauth/register_client.mjs

@@ -1,9 +1,9 @@
-const minimist = require('minimist')
-const { ObjectId } = require('mongodb-legacy')
-const { waitForDb, db } = require('../../app/src/infrastructure/mongodb')
-const {
-  hashSecret,
-} = require('../../modules/oauth2-server/app/src/SecretsHelper')
+import minimist from 'minimist'
+import mongodb from 'mongodb-legacy'
+import { waitForDb, db } from '../../app/src/infrastructure/mongodb.js'
+import { hashSecret } from '../../modules/oauth2-server/app/src/SecretsHelper.js'
+
+const { ObjectId } = mongodb
 
 
 async function main() {
 async function main() {
   const opts = parseArgs()
   const opts = parseArgs()
@@ -121,11 +121,10 @@ function toArray(value) {
   }
   }
 }
 }
 
 
-main()
-  .then(() => {
-    process.exit(0)
-  })
-  .catch(err => {
-    console.error(err)
-    process.exit(1)
-  })
+try {
+  await main()
+  process.exit(0)
+} catch (error) {
+  console.error(error)
+  process.exit(1)
+}

+ 10 - 11
services/web/scripts/oauth/remove_client.js → services/web/scripts/oauth/remove_client.mjs

@@ -1,9 +1,9 @@
-const minimist = require('minimist')
-const {
+import minimist from 'minimist'
+import {
   waitForDb,
   waitForDb,
   db,
   db,
   READ_PREFERENCE_SECONDARY,
   READ_PREFERENCE_SECONDARY,
-} = require('../../app/src/infrastructure/mongodb')
+} from '../../app/src/infrastructure/mongodb.js'
 
 
 async function main() {
 async function main() {
   const opts = parseArgs()
   const opts = parseArgs()
@@ -114,11 +114,10 @@ Options:
 `)
 `)
 }
 }
 
 
-main()
-  .then(() => {
-    process.exit(0)
-  })
-  .catch(err => {
-    console.error(err)
-    process.exit(1)
-  })
+try {
+  await main()
+  process.exit(0)
+} catch (error) {
+  console.error(error)
+  process.exit(1)
+}

+ 10 - 7
services/web/scripts/purge_non_logged_in_sessions.js → services/web/scripts/purge_non_logged_in_sessions.mjs

@@ -1,10 +1,11 @@
-const RedisWrapper = require('@overleaf/redis-wrapper')
-const Settings = require('@overleaf/settings')
-const SessionManager = require('../app/src/Features/Authentication/SessionManager')
+import RedisWrapper from '@overleaf/redis-wrapper'
+import Settings from '@overleaf/settings'
+import SessionManager from '../app/src/Features/Authentication/SessionManager.js'
+import minimist from 'minimist'
 
 
 const redis = RedisWrapper.createClient(Settings.redis.websessions)
 const redis = RedisWrapper.createClient(Settings.redis.websessions)
 
 
-const argv = require('minimist')(process.argv.slice(2), {
+const argv = minimist(process.argv.slice(2), {
   string: ['count'],
   string: ['count'],
   boolean: ['dry-run', 'help'],
   boolean: ['dry-run', 'help'],
   alias: {
   alias: {
@@ -92,7 +93,9 @@ async function scanAndPurge() {
   redis.quit()
   redis.quit()
 }
 }
 
 
-scanAndPurge().catch(err => {
-  console.error(err)
+try {
+  await scanAndPurge()
+} catch (error) {
+  console.error(error)
   process.exit()
   process.exit()
-})
+}

+ 15 - 15
services/web/scripts/recover_docs_from_redis.js → services/web/scripts/recover_docs_from_redis.mjs

@@ -1,12 +1,13 @@
 // recover docs from redis where there is no doc in mongo but the project exists
 // recover docs from redis where there is no doc in mongo but the project exists
 
 
-const minimist = require('minimist')
-const { db, waitForDb, ObjectId } = require('../app/src/infrastructure/mongodb')
-const ProjectEntityUpdateHandler = require('../app/src/Features/Project/ProjectEntityUpdateHandler')
-const ProjectEntityRestoreHandler = require('../app/src/Features/Project/ProjectEntityRestoreHandler')
-const RedisWrapper = require('@overleaf/redis-wrapper')
-const Settings = require('@overleaf/settings')
-const logger = require('@overleaf/logger')
+import minimist from 'minimist'
+
+import { db, waitForDb, ObjectId } from '../app/src/infrastructure/mongodb.js'
+import ProjectEntityUpdateHandler from '../app/src/Features/Project/ProjectEntityUpdateHandler.js'
+import ProjectEntityRestoreHandler from '../app/src/Features/Project/ProjectEntityRestoreHandler.js'
+import RedisWrapper from '@overleaf/redis-wrapper'
+import Settings from '@overleaf/settings'
+import logger from '@overleaf/logger'
 const opts = parseArgs()
 const opts = parseArgs()
 const redis = RedisWrapper.createClient(Settings.redis.web)
 const redis = RedisWrapper.createClient(Settings.redis.web)
 
 
@@ -172,11 +173,10 @@ async function deleteDocFromRedis(projectId, docId) {
   await redis.srem(`DocsIn:{${projectId}}`, projectId)
   await redis.srem(`DocsIn:{${projectId}}`, projectId)
 }
 }
 
 
-main()
-  .then(() => {
-    process.exit(0)
-  })
-  .catch(err => {
-    console.error(err)
-    process.exit(1)
-  })
+try {
+  await main()
+  process.exit(0)
+} catch (error) {
+  console.error(error)
+  process.exit(1)
+}

+ 15 - 15
services/web/scripts/recurly/collect_paypal_past_due_invoice.js → services/web/scripts/recurly/collect_paypal_past_due_invoice.mjs

@@ -1,9 +1,10 @@
-const RecurlyWrapper = require('../../app/src/Features/Subscription/RecurlyWrapper')
-const minimist = require('minimist')
-const logger = require('@overleaf/logger')
+import RecurlyWrapper from '../../app/src/Features/Subscription/RecurlyWrapper.js'
+import minimist from 'minimist'
+import logger from '@overleaf/logger'
+import { fileURLToPath } from 'url'
 
 
 const waitMs =
 const waitMs =
-  require.main === module
+  fileURLToPath(import.meta.url) === process.argv[1]
     ? timeout => new Promise(resolve => setTimeout(() => resolve(), timeout))
     ? timeout => new Promise(resolve => setTimeout(() => resolve(), timeout))
     : () => Promise.resolve()
     : () => Promise.resolve()
 
 
@@ -116,16 +117,15 @@ const main = async () => {
   }
   }
 }
 }
 
 
-if (require.main === module) {
-  main()
-    .then(() => {
-      logger.info('Done.')
-      process.exit(0)
-    })
-    .catch(err => {
-      logger.error({ err }, 'Error')
-      process.exit(1)
-    })
+if (fileURLToPath(import.meta.url) === process.argv[1]) {
+  try {
+    await main()
+    logger.info('Done.')
+    process.exit(0)
+  } catch (error) {
+    logger.error({ error }, 'Error')
+    process.exit(1)
+  }
 }
 }
 
 
-module.exports = { main }
+export default { main }

+ 3 - 3
services/web/scripts/recurly/get_paypal_accounts_csv.js → services/web/scripts/recurly/get_paypal_accounts_csv.mjs

@@ -1,6 +1,6 @@
-const RecurlyWrapper = require('../../app/src/Features/Subscription/RecurlyWrapper')
-const async = require('async')
-const CSVParser = require('json2csv').Parser
+import RecurlyWrapper from '../../app/src/Features/Subscription/RecurlyWrapper.js'
+import async from 'async'
+import { Parser as CSVParser } from 'json2csv'
 
 
 const NOW = new Date()
 const NOW = new Date()
 
 

+ 11 - 11
services/web/scripts/recurly/get_recurly_group_prices.js → services/web/scripts/recurly/get_recurly_group_prices.mjs

@@ -2,10 +2,11 @@
 // app/templates/plans/groups.json
 // app/templates/plans/groups.json
 //
 //
 // Usage example:
 // Usage example:
-// node scripts/recurly/get_recurly_group_prices.js
+// node scripts/recurly/get_recurly_group_prices.mjs
 
 
-const recurly = require('recurly')
-const Settings = require('@overleaf/settings')
+import recurly from 'recurly'
+
+import Settings from '@overleaf/settings'
 
 
 const recurlySettings = Settings.apis.recurly
 const recurlySettings = Settings.apis.recurly
 const recurlyApiKey = recurlySettings ? recurlySettings.apiKey : undefined
 const recurlyApiKey = recurlySettings ? recurlySettings.apiKey : undefined
@@ -37,11 +38,10 @@ async function main() {
   console.log(JSON.stringify(prices, undefined, 2))
   console.log(JSON.stringify(prices, undefined, 2))
 }
 }
 
 
-main()
-  .then(() => {
-    process.exit(0)
-  })
-  .catch(error => {
-    console.error({ error })
-    process.exit(1)
-  })
+try {
+  await main()
+  process.exit(0)
+} catch (error) {
+  console.error({ error })
+  process.exit(1)
+}

+ 11 - 10
services/web/scripts/refresh_institution_users.js → services/web/scripts/refresh_institution_users.mjs

@@ -1,18 +1,11 @@
-const { waitForDb } = require('../app/src/infrastructure/mongodb')
-const minimist = require('minimist')
-const InstitutionsManager = require('../app/src/Features/Institutions/InstitutionsManager')
+import { waitForDb } from '../app/src/infrastructure/mongodb.js'
+import minimist from 'minimist'
+import InstitutionsManager from '../app/src/Features/Institutions/InstitutionsManager.js'
 
 
 const institutionId = parseInt(process.argv[2])
 const institutionId = parseInt(process.argv[2])
 if (isNaN(institutionId)) throw new Error('No institution id')
 if (isNaN(institutionId)) throw new Error('No institution id')
 console.log('Refreshing users at institution', institutionId)
 console.log('Refreshing users at institution', institutionId)
 
 
-waitForDb()
-  .then(main)
-  .catch(err => {
-    console.error(err)
-    process.exit(1)
-  })
-
 function main() {
 function main() {
   const argv = minimist(process.argv.slice(2))
   const argv = minimist(process.argv.slice(2))
   if (!argv.notify) {
   if (!argv.notify) {
@@ -37,3 +30,11 @@ function main() {
     }
     }
   )
   )
 }
 }
+
+try {
+  await waitForDb()
+  await main()
+} catch (error) {
+  console.error(error)
+  process.exit(1)
+}

+ 3 - 1
services/web/test/acceptance/src/CollectPayPalPastDueInvoiceTest.mjs

@@ -2,10 +2,12 @@ import sinon from 'sinon'
 import chai, { expect } from 'chai'
 import chai, { expect } from 'chai'
 import chaiAsPromised from 'chai-as-promised'
 import chaiAsPromised from 'chai-as-promised'
 import sinonChai from 'sinon-chai'
 import sinonChai from 'sinon-chai'
-import { main } from '../../../scripts/recurly/collect_paypal_past_due_invoice.js'
+import CollectPaypalPastDueInvoice from '../../../scripts/recurly/collect_paypal_past_due_invoice.mjs'
 import RecurlyWrapper from '../../../app/src/Features/Subscription/RecurlyWrapper.js'
 import RecurlyWrapper from '../../../app/src/Features/Subscription/RecurlyWrapper.js'
 import OError from '@overleaf/o-error'
 import OError from '@overleaf/o-error'
 
 
+const { main } = CollectPaypalPastDueInvoice
+
 chai.use(chaiAsPromised)
 chai.use(chaiAsPromised)
 chai.use(sinonChai)
 chai.use(sinonChai)