forest-cli 3.0.10 → 3.0.12-beta.1

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.
Files changed (138) hide show
  1. package/bin/run +1 -1
  2. package/oclif.manifest.json +1 -1
  3. package/package.json +17 -8
  4. package/src/abstract-authenticated-command.js +0 -46
  5. package/src/abstract-command.js +0 -27
  6. package/src/commands/branch.js +0 -136
  7. package/src/commands/deploy.js +0 -90
  8. package/src/commands/environments/copy-layout.js +0 -116
  9. package/src/commands/environments/create.js +0 -62
  10. package/src/commands/environments/delete.js +0 -81
  11. package/src/commands/environments/get.js +0 -48
  12. package/src/commands/environments/reset.js +0 -76
  13. package/src/commands/environments/update.js +0 -46
  14. package/src/commands/environments.js +0 -41
  15. package/src/commands/init.js +0 -169
  16. package/src/commands/login.js +0 -34
  17. package/src/commands/logout.js +0 -18
  18. package/src/commands/projects/create.js +0 -262
  19. package/src/commands/projects/get.js +0 -53
  20. package/src/commands/projects.js +0 -36
  21. package/src/commands/push.js +0 -75
  22. package/src/commands/schema/apply.js +0 -140
  23. package/src/commands/schema/update.js +0 -70
  24. package/src/commands/set-origin.js +0 -59
  25. package/src/commands/switch.js +0 -117
  26. package/src/commands/user.js +0 -44
  27. package/src/context/command-project-create-plan.js +0 -11
  28. package/src/context/command-projects-common-plan.js +0 -65
  29. package/src/context/command-schema-update-command-plan.js +0 -4
  30. package/src/context/dependencies-plan.js +0 -21
  31. package/src/context/env-plan.js +0 -27
  32. package/src/context/plan.js +0 -12
  33. package/src/context/process-plan.js +0 -3
  34. package/src/context/renderers-plan.js +0 -7
  35. package/src/context/serializers-plan.js +0 -8
  36. package/src/context/services-plan.js +0 -8
  37. package/src/context/static.js +0 -19
  38. package/src/context/utils-plan.js +0 -7
  39. package/src/deserializers/api-error.js +0 -21
  40. package/src/deserializers/application-token.js +0 -15
  41. package/src/deserializers/branch.js +0 -8
  42. package/src/deserializers/environment.js +0 -5
  43. package/src/deserializers/job.js +0 -5
  44. package/src/deserializers/project.js +0 -11
  45. package/src/errors/application-error.js +0 -9
  46. package/src/errors/application-token/unable-to-create-application-token-error.js +0 -16
  47. package/src/errors/database/empty-database-error.js +0 -5
  48. package/src/errors/dumper/incompatible-liana-for-update-error.js +0 -16
  49. package/src/errors/dumper/invalid-forest-cli-project-structure-error.js +0 -16
  50. package/src/errors/forest-cli-error.js +0 -32
  51. package/src/index.js +0 -1
  52. package/src/renderers/branches.js +0 -45
  53. package/src/renderers/defaults.js +0 -19
  54. package/src/renderers/environment.js +0 -51
  55. package/src/renderers/environments.js +0 -51
  56. package/src/renderers/project.js +0 -45
  57. package/src/renderers/projects.js +0 -45
  58. package/src/serializers/application-token.js +0 -11
  59. package/src/serializers/deployment-request.js +0 -5
  60. package/src/serializers/environment.js +0 -20
  61. package/src/serializers/job.js +0 -5
  62. package/src/serializers/project.js +0 -17
  63. package/src/serializers/schema.js +0 -116
  64. package/src/services/api.js +0 -110
  65. package/src/services/apimap-sorter.js +0 -104
  66. package/src/services/application-token.js +0 -56
  67. package/src/services/ask-for-environment.js +0 -24
  68. package/src/services/authenticator.js +0 -187
  69. package/src/services/branch-manager.js +0 -169
  70. package/src/services/dumper/dumper.js +0 -503
  71. package/src/services/dumper/handlebars/helpers/equal.js +0 -3
  72. package/src/services/dumper/handlebars/helpers/indent.js +0 -3
  73. package/src/services/dumper/handlebars/helpers/is-array.js +0 -3
  74. package/src/services/dumper/handlebars/helpers/is-object.js +0 -3
  75. package/src/services/dumper/handlebars/helpers/sum.js +0 -3
  76. package/src/services/dumper/handlebars/helpers/wrap-quotes.js +0 -7
  77. package/src/services/dumper/handlebars/loader.js +0 -10
  78. package/src/services/dumper/handlebars/partials/render-nested.js +0 -27
  79. package/src/services/dumper/templates/app/Dockerfile.hbs +0 -6
  80. package/src/services/dumper/templates/app/app.hbs +0 -79
  81. package/src/services/dumper/templates/app/config/databases.hbs +0 -49
  82. package/src/services/dumper/templates/app/docker-compose.hbs +0 -33
  83. package/src/services/dumper/templates/app/dockerignore.hbs +0 -3
  84. package/src/services/dumper/templates/app/env.hbs +0 -20
  85. package/src/services/dumper/templates/app/forest/collection.hbs +0 -13
  86. package/src/services/dumper/templates/app/gitignore.hbs +0 -3
  87. package/src/services/dumper/templates/app/middlewares/forestadmin.hbs +0 -21
  88. package/src/services/dumper/templates/app/middlewares/welcome.hbs +0 -7
  89. package/src/services/dumper/templates/app/models/index.hbs +0 -56
  90. package/src/services/dumper/templates/app/models/mongo-model.hbs +0 -16
  91. package/src/services/dumper/templates/app/models/sequelize-model.hbs +0 -48
  92. package/src/services/dumper/templates/app/public/favicon.png +0 -0
  93. package/src/services/dumper/templates/app/routes/route.hbs +0 -61
  94. package/src/services/dumper/templates/app/server.hbs +0 -56
  95. package/src/services/dumper/templates/app/views/index.hbs +0 -73
  96. package/src/services/environment-manager.js +0 -139
  97. package/src/services/init-manager.js +0 -183
  98. package/src/services/job-state-checker.js +0 -57
  99. package/src/services/logger.js +0 -125
  100. package/src/services/oidc/authenticator.js +0 -109
  101. package/src/services/oidc/error.js +0 -32
  102. package/src/services/project-manager.js +0 -89
  103. package/src/services/projects/create/command-generate-config-getter.js +0 -61
  104. package/src/services/projects/create/project-creator.js +0 -89
  105. package/src/services/prompter/abstract-prompter.js +0 -13
  106. package/src/services/prompter/application-prompts.js +0 -63
  107. package/src/services/prompter/database-prompts.js +0 -208
  108. package/src/services/prompter/general-prompter.js +0 -61
  109. package/src/services/prompter/project-prompts.js +0 -47
  110. package/src/services/prompter/prompter-error.js +0 -10
  111. package/src/services/schema/schema-service.js +0 -154
  112. package/src/services/schema/update/analyzer/database-analyzer.js +0 -64
  113. package/src/services/schema/update/analyzer/mongo-collections-analyzer.js +0 -344
  114. package/src/services/schema/update/analyzer/mongo-embedded-analyzer.js +0 -226
  115. package/src/services/schema/update/analyzer/mongo-hasmany-analyzer.js +0 -55
  116. package/src/services/schema/update/analyzer/mongo-references-analyzer.js +0 -51
  117. package/src/services/schema/update/analyzer/mysql-table-constraints-getter.js +0 -59
  118. package/src/services/schema/update/analyzer/sequelize-column-type-getter.js +0 -147
  119. package/src/services/schema/update/analyzer/sequelize-default-value.js +0 -122
  120. package/src/services/schema/update/analyzer/sequelize-table-constraints-getter.js +0 -298
  121. package/src/services/schema/update/analyzer/sequelize-tables-analyzer.js +0 -529
  122. package/src/services/schema/update/database.js +0 -160
  123. package/src/services/schema-sender.js +0 -55
  124. package/src/services/spinner.js +0 -130
  125. package/src/services/with-current-project.js +0 -41
  126. package/src/utils/database-url.js +0 -33
  127. package/src/utils/directory-existence-checker.js +0 -17
  128. package/src/utils/error-handler.js +0 -63
  129. package/src/utils/error.js +0 -21
  130. package/src/utils/event-sender.js +0 -80
  131. package/src/utils/fields.js +0 -14
  132. package/src/utils/key-generator.js +0 -18
  133. package/src/utils/messages.js +0 -7
  134. package/src/utils/mongo-collections.js +0 -35
  135. package/src/utils/mongo-primitive-type.js +0 -44
  136. package/src/utils/strings.js +0 -49
  137. package/src/utils/terminator.js +0 -38
  138. package/src/utils/to-valid-package-name.js +0 -24
@@ -1,55 +0,0 @@
1
- const P = require('bluebird');
2
- const agent = require('superagent-promise')(require('superagent'), P);
3
- const Context = require('@forestadmin/context');
4
-
5
- /**
6
- * @class
7
- * @param {string} serializedSchema
8
- * @param {string} secret
9
- * @param {string} authenticationToken
10
- * @param {(code: number) => void} oclifExit
11
- */
12
- function SchemaSender(serializedSchema, secret, authenticationToken, oclifExit) {
13
- /**
14
- * @function
15
- * @returns {Promise<number | undefined>}
16
- */
17
- this.perform = () => {
18
- const { env, logger } = Context.inject();
19
-
20
- return agent
21
- .post(`${env.FOREST_URL}/forest/apimaps`)
22
- .set('forest-secret-key', secret)
23
- .set('Authorization', `Bearer ${authenticationToken}`)
24
- .send(serializedSchema)
25
- .then(({ body }) => {
26
- if (body && body.meta) {
27
- return body.meta.job_id;
28
- }
29
-
30
- return null;
31
- })
32
- .catch((error) => {
33
- if ([200, 202, 204].indexOf(error.status) !== -1) {
34
- if (error.body && error.body.warning) {
35
- logger.error(error.body.warning);
36
- oclifExit(1);
37
- }
38
- } else if (error.status === 0) {
39
- logger.error('Cannot send the forest schema to Forest. Are you online?');
40
- oclifExit(3);
41
- } else if (error.status === 404) {
42
- logger.error('Cannot find the project related to the environment secret you configured.');
43
- oclifExit(4);
44
- } else if (error.status === 503) {
45
- logger.error('Forest is in maintenance for a few minutes. We are upgrading your experience in the forest. We just need a few more minutes to get it right.');
46
- oclifExit(5);
47
- } else {
48
- logger.error('An error occured with the schema sent to Forest. Please contact support@forestadmin.com for further investigations.');
49
- oclifExit(6);
50
- }
51
- });
52
- };
53
- }
54
-
55
- module.exports = SchemaSender;
@@ -1,130 +0,0 @@
1
- const { v4: uuidv4 } = require('uuid');
2
- const chalk = require('chalk');
3
- const Spinnies = require('spinnies');
4
-
5
- const spinniesConstructorParameters = {
6
- color: 'yellow',
7
- failPrefix: `${chalk.bold.red('×')}`,
8
- spinnerColor: 'yellow',
9
- spinner: {
10
- interval: 80,
11
- frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'],
12
- },
13
- succeedPrefix: `${chalk.bold.green('√')}`,
14
- };
15
-
16
- // NOTICE: Singleton used here to attach all generated spinner to the same spinnies instance.
17
- let spinniesInstance;
18
- function getSpinniesInstance() {
19
- if (!spinniesInstance) spinniesInstance = new Spinnies(spinniesConstructorParameters);
20
- return spinniesInstance;
21
- }
22
-
23
- /**
24
- * A single instance of spinner is intended to be used as follow:
25
- * @example
26
- * // synchronously:
27
- * spinner.start({ text: 'my super text' })
28
- * // do something
29
- * spinner.success()
30
- *
31
- * // on promise:
32
- * spinner.start({ text: 'my super text' })
33
- * spinner.attachToPromise(mySuperPromise())
34
- *
35
- * If ever multiple instances are need to be run together:
36
- * @example
37
- * const Spinner = require('./spinner');
38
- *
39
- * const spinner1 = new Spinner();
40
- * const spinner2 = new Spinner();
41
- */
42
- class Spinner {
43
- constructor() {
44
- this.spinnies = getSpinniesInstance();
45
- this.currentSpinnerOptions = null;
46
- }
47
-
48
- start(options) {
49
- if (this.isRunning()) {
50
- throw Error('A spinner is already running.');
51
- }
52
-
53
- this.currentSpinnerOptions = options;
54
- this.currentSpinnerUniqueKey = uuidv4();
55
- this.spinnies.add(this.currentSpinnerUniqueKey, options);
56
- }
57
-
58
- // NOTICE: optional parameter options to have a custom success message
59
- success(options = this.currentSpinnerOptions) {
60
- if (!this.isRunning()) {
61
- throw Error('No spinner is running.');
62
- }
63
-
64
- this.spinnies.succeed(this.currentSpinnerUniqueKey, options);
65
- this.stop();
66
- }
67
-
68
- // NOTICE: optional parameter options to have a custom fail message
69
- fail(options = this.currentSpinnerOptions) {
70
- if (!this.isRunning()) {
71
- throw Error('No spinner is running.');
72
- }
73
-
74
- this.spinnies.fail(this.currentSpinnerUniqueKey, options);
75
- this.stop();
76
- }
77
-
78
- pause() {
79
- if (!this.isRunning()) {
80
- throw Error('No spinner is running.');
81
- }
82
-
83
- this.spinnies.remove(this.currentSpinnerUniqueKey);
84
- // NOTICE: spinnies lib function that checks for active spinners and if none, release cli usage
85
- this.spinnies.checkIfActiveSpinners();
86
- this.pausedSpinnerOptions = this.currentSpinnerOptions;
87
- }
88
-
89
- continue() {
90
- if (this.isRunning()) {
91
- throw Error('A spinner is already running.');
92
- }
93
-
94
- if (!this.pausedSpinnerOptions) {
95
- throw Error('No spinner has been paused.');
96
- }
97
-
98
- this.spinnies.add(this.currentSpinnerUniqueKey, this.pausedSpinnerOptions);
99
- this.pausedSpinnerOptions = null;
100
- }
101
-
102
- isRunning() {
103
- return !!this.spinnies.pick(this.currentSpinnerUniqueKey);
104
- }
105
-
106
- // NOTICE: spinner.start needs to be called first
107
- attachToPromise(promise) {
108
- return promise
109
- .then((result) => {
110
- this.success(this.currentSpinnerOptions);
111
- return result;
112
- })
113
- .catch((error) => {
114
- // NOTICE: Only trigger the fail if the spinner is running (ie. not paused)
115
- if (this.isRunning()) {
116
- this.fail({ text: error });
117
- }
118
- throw error;
119
- });
120
- }
121
-
122
- // NOTICE: this stop method should only be used internally to reset the current spinner
123
- // on success or failure.
124
- stop() {
125
- this.currentSpinnerUniqueKey = null;
126
- this.currentSpinnerOptions = null;
127
- }
128
- }
129
-
130
- module.exports = Spinner;
@@ -1,41 +0,0 @@
1
- const Context = require('@forestadmin/context');
2
-
3
- const ProjectManager = require('./project-manager');
4
-
5
- module.exports = async function withCurrentProject(config) {
6
- const { assertPresent, inquirer, spinner } = Context.inject();
7
- assertPresent({ inquirer, spinner });
8
-
9
- if (config.projectId) { return config; }
10
-
11
- const projectManager = await new ProjectManager(config);
12
-
13
- const envSecret = config.FOREST_ENV_SECRET;
14
- if (envSecret) {
15
- const { includeLegacy } = config;
16
- const projectFromEnv = await projectManager.getByEnvSecret(envSecret, includeLegacy);
17
- if (projectFromEnv) {
18
- return { ...config, projectId: projectFromEnv.id };
19
- }
20
- }
21
-
22
- const projects = await projectManager.listProjects();
23
- if (projects.length) {
24
- if (projects.length === 1) {
25
- return { ...config, projectId: projects[0].id };
26
- }
27
-
28
- // NOTICE: If a spinner is running, it has to be paused during the prompt and resumed after.
29
- const existingSpinner = spinner.isRunning();
30
- if (existingSpinner) spinner.pause();
31
- const response = await inquirer.prompt([{
32
- name: 'project',
33
- message: 'Select your project',
34
- type: 'list',
35
- choices: projects.map((project) => ({ name: project.name, value: project.id })),
36
- }]);
37
- if (existingSpinner) spinner.continue();
38
- return { ...config, projectId: response.project };
39
- }
40
- throw new Error('You don\'t have any project yet.');
41
- };
@@ -1,33 +0,0 @@
1
- function buildDatabaseUrl(config) {
2
- let connectionString;
3
-
4
- if (!config) {
5
- return null;
6
- }
7
-
8
- if (config.dbConnectionUrl) {
9
- connectionString = config.dbConnectionUrl;
10
- } else {
11
- let protocol = config.databaseDialect;
12
- let port = `:${config.databasePort}`;
13
- let password = '';
14
-
15
- if (config.databaseDialect === 'mongodb' && config.mongodbSrv) {
16
- protocol = 'mongodb+srv';
17
- port = '';
18
- }
19
-
20
- if (config.databasePassword) {
21
- // NOTICE: Encode password string in case of special chars.
22
- password = `:${encodeURIComponent(config.databasePassword)}`;
23
- }
24
-
25
- connectionString = `${protocol}://${config.databaseUser}${password}@${config.databaseHost}${port}/${config.databaseName}`;
26
- }
27
-
28
- return connectionString;
29
- }
30
-
31
- module.exports = {
32
- buildDatabaseUrl,
33
- };
@@ -1,17 +0,0 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
-
4
- function DirectoryExistenceChecker(directory, basePath = undefined) {
5
- this.perform = () => {
6
- let directoryToCheck = directory;
7
- if (basePath) directoryToCheck = path.resolve(basePath, directory);
8
- try {
9
- fs.accessSync(directoryToCheck, fs.F_OK);
10
- return true;
11
- } catch (error) {
12
- return false;
13
- }
14
- };
15
- }
16
-
17
- module.exports = DirectoryExistenceChecker;
@@ -1,63 +0,0 @@
1
- const ForestCLIError = require('../errors/forest-cli-error');
2
-
3
- class ErrorHandler {
4
- /**
5
- * @param {import('../context/plan').Context} context
6
- */
7
- constructor({
8
- assertPresent,
9
- chalk,
10
- messages,
11
- terminator,
12
- }) {
13
- assertPresent({
14
- chalk,
15
- messages,
16
- terminator,
17
- });
18
- /** @private @readonly */
19
- this.terminator = terminator;
20
- /** @private @readonly */
21
- this.chalk = chalk;
22
- /** @private @readonly */
23
- this.messages = messages;
24
- }
25
-
26
- /**
27
- * @private
28
- * @param {ForestCLIError} error
29
- * @returns {string[]}
30
- */
31
- getMessages(error) {
32
- const messages = [];
33
- if (error.reason) {
34
- messages.push(`${this.chalk.red(error.message)}: ${error.reason}`);
35
- } else {
36
- messages.push(this.chalk.red(error.message));
37
- }
38
-
39
- if (error.possibleSolution) {
40
- messages.push(error.possibleSolution);
41
- }
42
-
43
- return messages;
44
- }
45
-
46
- /**
47
- * @param {Error} error
48
- */
49
- async handle(error) {
50
- if (error instanceof ForestCLIError) {
51
- await this.terminator.terminate(1, {
52
- logs: this.getMessages(error),
53
- });
54
- } else {
55
- const message = `${this.messages.ERROR_UNEXPECTED} ${this.chalk.red(error.message)}`;
56
- await this.terminator.terminate(1, {
57
- logs: [message],
58
- });
59
- }
60
- }
61
- }
62
-
63
- module.exports = ErrorHandler;
@@ -1,21 +0,0 @@
1
- const ApiErrorDeserializer = require('../deserializers/api-error');
2
-
3
- const UNEXPECTED_ERROR_MESSAGE = 'Oops something went wrong.';
4
-
5
- function handleError(rawError) {
6
- let error;
7
- // NOTICE: We check if the errors are from the API (have a status) or if thrown internally.
8
- if (rawError.status) {
9
- try {
10
- error = ApiErrorDeserializer.deserialize(rawError);
11
- } catch (e) {
12
- return UNEXPECTED_ERROR_MESSAGE;
13
- }
14
- } else {
15
- error = rawError;
16
- }
17
-
18
- return error.message ? error.message : UNEXPECTED_ERROR_MESSAGE;
19
- }
20
-
21
- module.exports = { handleError };
@@ -1,80 +0,0 @@
1
- class EventSender {
2
- constructor({ assertPresent, env, superagent }) {
3
- assertPresent({ env, superagent });
4
- this.env = env;
5
- this.superagent = superagent;
6
-
7
- this.applicationName = null;
8
- this.command = null;
9
- this.meta = null;
10
- this.sessionToken = null;
11
- }
12
-
13
- async notifyError(code = 'unknown_error', message = null, context = undefined) {
14
- if (!this.applicationName || !this.command) { return; }
15
-
16
- const attributes = {
17
- code,
18
- message,
19
- project_name: this.applicationName,
20
- command: this.command,
21
- context,
22
- };
23
-
24
- if (this.command !== 'schema:update') {
25
- attributes.project_id = this.meta.projectId || null;
26
- attributes.db_dialect = this.meta.dbDialect;
27
- attributes.agent = this.meta.agent;
28
- attributes.is_local = this.meta.isLocal;
29
- }
30
-
31
- try {
32
- if (this.sessionToken) {
33
- await this.superagent.post(`${this.env.FOREST_URL}/api/lumber/error`, {
34
- data: {
35
- type: 'events',
36
- attributes,
37
- },
38
- }).set('Authorization', `Bearer ${this.sessionToken}`);
39
- } else {
40
- await this.superagent.post(`${this.env.FOREST_URL}/api/lumber/error`, {
41
- data: {
42
- type: 'events',
43
- attributes,
44
- },
45
- });
46
- }
47
- } catch (e) {
48
- // NOTICE: We want silent error because this is just for reporting error
49
- // and not not blocking if that does not work.
50
- }
51
- }
52
-
53
- async notifySuccess() {
54
- if (
55
- !this.applicationName || !this.command || !this.sessionToken || !Object.keys(this.meta).length
56
- ) { return; }
57
-
58
- try {
59
- await this.superagent.post(`${this.env.FOREST_URL}/api/lumber/success`, {
60
- data: {
61
- type: 'events',
62
- attributes: {
63
- command: this.command,
64
- project_id: this.meta.projectId,
65
- project_name: this.applicationName,
66
- db_dialect: this.meta.dbDialect,
67
- agent: this.meta.agent,
68
- is_local: this.meta.isLocal,
69
- },
70
- },
71
- })
72
- .set('Authorization', `Bearer ${this.sessionToken}`);
73
- } catch (e) {
74
- // NOTICE: We want silent error because this is just for reporting error
75
- // and not not blocking if that does not work.
76
- }
77
- }
78
- }
79
-
80
- module.exports = EventSender;
@@ -1,14 +0,0 @@
1
- const _ = require('lodash');
2
-
3
- function isUnderscored(fields) {
4
- if (!fields || !fields.length) return false;
5
-
6
- if (fields.length === 1 && fields[0].nameColumn === 'id') return true;
7
-
8
- return fields.every((field) => field.nameColumn === _.snakeCase(field.nameColumn))
9
- && fields.some((field) => field.nameColumn.includes('_'));
10
- }
11
-
12
- module.exports = {
13
- isUnderscored,
14
- };
@@ -1,18 +0,0 @@
1
- class KeyGenerator {
2
- constructor({
3
- assertPresent,
4
- crypto,
5
- }) {
6
- assertPresent({
7
- crypto,
8
- });
9
- this.crypto = crypto;
10
- this.length = 24;
11
- }
12
-
13
- generate() {
14
- return this.crypto.randomBytes(this.length).toString('hex');
15
- }
16
- }
17
-
18
- module.exports = KeyGenerator;
@@ -1,7 +0,0 @@
1
- module.exports = {
2
- ERROR_UNEXPECTED: 'An unexpected error occurred. Please reach out for help in our Developers community (https://community.forestadmin.com/) or create a Github issue with following error:',
3
- ERROR_MISSING_PROJECT_NAME: 'Missing project name in the command.',
4
- HINT_MISSING_PROJECT_NAME: 'Please specify a project name. Type "forest help for" more information.',
5
- ERROR_NOT_PARSABLE_CONNECTION_URL: 'Cannot parse the database dialect. Please, check the syntax of the database connection string.',
6
- HINT_DIRECTORY_ALREADY_EXISTS: 'Please retry with another project name.',
7
- };
@@ -1,35 +0,0 @@
1
- const P = require('bluebird');
2
-
3
- function getCollectionName(collection) {
4
- return collection
5
- && collection.s
6
- && collection.s.namespace
7
- && collection.s.namespace.collection;
8
- }
9
-
10
- function isSystemCollection(collection) {
11
- const collectionName = getCollectionName(collection);
12
- return collectionName && collectionName.startsWith('system.');
13
- }
14
-
15
- async function findCollectionMatchingSamples(databaseConnection, samples) {
16
- return P.mapSeries(databaseConnection.collections(), async (collection) => {
17
- if (isSystemCollection(collection)) return null;
18
- const count = await collection.countDocuments({ _id: { $in: samples } });
19
- if (count) {
20
- return collection.s.namespace.collection;
21
- }
22
- return null;
23
- }).then((matches) => matches.filter((match) => match));
24
- }
25
-
26
- function filterReferenceCollection(referencedCollections) {
27
- return referencedCollections.length === 1 ? referencedCollections[0] : null;
28
- }
29
-
30
- module.exports = {
31
- findCollectionMatchingSamples,
32
- isSystemCollection,
33
- filterReferenceCollection,
34
- getCollectionName,
35
- };
@@ -1,44 +0,0 @@
1
- const { ObjectId } = require('mongodb');
2
-
3
- /**
4
- * Retrieves simple mongoose type from value if detectable
5
- * Simple types are 'Date', 'Boolean', 'Number', 'String', 'Mongoose.Schema.Types.ObjectId'
6
- * @param value
7
- * @returns {string|null} return
8
- */
9
- /* istanbul ignore next */
10
- function getMongooseTypeFromValue(value) {
11
- if (typeof value === 'object' && value instanceof Date) {
12
- return 'Date';
13
- }
14
-
15
- if (typeof value === 'object' && value instanceof ObjectId) {
16
- return 'Mongoose.Schema.Types.ObjectId';
17
- }
18
-
19
- switch (typeof value) {
20
- case 'boolean':
21
- return 'Boolean';
22
- case 'number':
23
- return 'Number';
24
- case 'string':
25
- return 'String';
26
- default:
27
- return null;
28
- }
29
- }
30
-
31
- /**
32
- * Checks if the value corresponds to a mongoose type
33
- * @param value
34
- * @returns {boolean}
35
- */
36
- /* istanbul ignore next */
37
- function isOfMongooseType(value) {
38
- return !!getMongooseTypeFromValue(value);
39
- }
40
-
41
- module.exports = {
42
- getMongooseTypeFromValue,
43
- isOfMongooseType,
44
- };
@@ -1,49 +0,0 @@
1
- const _ = require('lodash');
2
-
3
- const RESERVED_WORDS = [
4
- 'abstract', 'await', 'boolean', 'break',
5
- 'byte', 'case', 'catch', 'char',
6
- 'class', 'const', 'continue', 'debugger',
7
- 'default', 'delete', 'do', 'double',
8
- 'else', 'enum', 'export', 'extends',
9
- 'false', 'final', 'finally', 'float',
10
- 'for', 'function', 'goto', 'if',
11
- 'implements', 'import', 'in', 'instanceof',
12
- 'int', 'interface', 'let', 'long',
13
- 'module', 'native', 'new', 'null',
14
- 'package', 'private', 'protected', 'public',
15
- 'return', 'short', 'static', 'super',
16
- 'switch', 'synchronized', 'this', 'throw',
17
- 'throws', 'transient', 'true', 'try',
18
- 'typeof', 'undefined', 'var', 'void',
19
- 'volatile', 'while', 'with', 'yield',
20
- ];
21
-
22
- module.exports = {
23
- pascalCase(input) {
24
- return _.chain(input).camelCase().upperFirst().value();
25
- },
26
-
27
- camelCase(input) {
28
- return _.camelCase(input);
29
- },
30
-
31
- isReservedWord(input) {
32
- return RESERVED_WORDS.includes(_.toLower(input));
33
- },
34
-
35
- transformToSafeString(input) {
36
- if (/^[\d]/g.exec(input)) {
37
- return `model${input}`;
38
- }
39
- // NOTICE: add dash to get proper snake/pascal case
40
- if (this.isReservedWord(input)) {
41
- return `model${_.upperFirst(input)}`;
42
- }
43
- return input;
44
- },
45
-
46
- transformToCamelCaseSafeString(input) {
47
- return this.camelCase(this.transformToSafeString(input));
48
- },
49
- };
@@ -1,38 +0,0 @@
1
- /**
2
- * @typedef {{
3
- * errorCode: string;
4
- * errorMessage: string;
5
- * context: any;
6
- * }} DetailedLog
7
- *
8
- * @typedef {{
9
- * logs: string[]
10
- * }} MultipleMessages
11
- */
12
-
13
- module.exports = ({
14
- assertPresent, eventSender, exitProcess, logger,
15
- }) => {
16
- assertPresent({ eventSender, exitProcess, logger });
17
-
18
- return {
19
- /**
20
- * @param {number} status
21
- * @param {DetailedLog | MultipleMessages | DetailedLog & MultipleMessages} log
22
- */
23
- async terminate(status, {
24
- errorCode, errorMessage, logs, context,
25
- }) {
26
- if (logs.length) {
27
- logger.error(...logs);
28
- }
29
- if (errorCode) {
30
- await eventSender.notifyError(errorCode, errorMessage, context);
31
- } else {
32
- await eventSender.notifyError();
33
- }
34
-
35
- return exitProcess(status);
36
- },
37
- };
38
- };
@@ -1,24 +0,0 @@
1
- const validate = require('validate-npm-package-name');
2
-
3
- module.exports = function toValidPackageName(packageName) {
4
- function isValid(name) {
5
- const { validForNewPackages } = validate(name);
6
- return validForNewPackages;
7
- }
8
-
9
- if (!isValid(packageName)) {
10
- // NOTICE: Create an always valid package name (disallow almost everything)
11
- const validPackageName = packageName.toLowerCase()
12
- // Remove all non "a-z", "0-9", "-" characters with hyphen.
13
- .replace(/[^a-z0-9\\-]/g, '-')
14
- // Remove hyphen sequence (> 1).
15
- .replace(/-{2,}/g, '-')
16
- // Remove leading and trailing hyphen.
17
- .replace(/^-|-$/g, '');
18
-
19
- // NOTICE: Return 'forest-cli-project' if sanitized package name is still not valid.
20
- return isValid(validPackageName) ? validPackageName : 'forest-cli-project';
21
- }
22
-
23
- return packageName;
24
- };