@contentstack/cli-migration 2.0.0-beta.2 → 2.0.0-beta.3

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 (46) hide show
  1. package/package.json +19 -12
  2. package/src/actions/action-list.js +0 -32
  3. package/src/actions/index.js +0 -217
  4. package/src/commands/cm/stacks/migration.js +0 -283
  5. package/src/config/api-config.js +0 -18
  6. package/src/config/default-options.js +0 -7
  7. package/src/config/index.js +0 -7
  8. package/src/config/master-locale.js +0 -10
  9. package/src/modules/base.js +0 -95
  10. package/src/modules/content-types.js +0 -208
  11. package/src/modules/fields.js +0 -340
  12. package/src/modules/index.js +0 -8
  13. package/src/modules/locale.js +0 -33
  14. package/src/modules/migration.js +0 -112
  15. package/src/modules/parser.js +0 -105
  16. package/src/services/content-types.js +0 -317
  17. package/src/services/index.js +0 -6
  18. package/src/services/locales.js +0 -71
  19. package/src/utils/auto-retry.js +0 -32
  20. package/src/utils/callsite.js +0 -23
  21. package/src/utils/constants.js +0 -223
  22. package/src/utils/contentstack-sdk.js +0 -70
  23. package/src/utils/error-helper.js +0 -105
  24. package/src/utils/fs-helper.js +0 -29
  25. package/src/utils/get-batches.js +0 -7
  26. package/src/utils/get-config.js +0 -13
  27. package/src/utils/group-by.js +0 -38
  28. package/src/utils/index.js +0 -21
  29. package/src/utils/logger.js +0 -75
  30. package/src/utils/map.js +0 -40
  31. package/src/utils/migration-logger.js +0 -21
  32. package/src/utils/modules.js +0 -134
  33. package/src/utils/object-helper.js +0 -9
  34. package/src/utils/request.js +0 -95
  35. package/src/utils/safe-promise.js +0 -3
  36. package/src/utils/schema-helper.js +0 -35
  37. package/src/utils/success-handler.js +0 -12
  38. package/src/validators/api-error.js +0 -20
  39. package/src/validators/base-validator.js +0 -39
  40. package/src/validators/create-content-type-validator.js +0 -54
  41. package/src/validators/edit-content-type-validator.js +0 -53
  42. package/src/validators/field-validator.js +0 -21
  43. package/src/validators/index.js +0 -11
  44. package/src/validators/migration-error.js +0 -20
  45. package/src/validators/schema-validator.js +0 -23
  46. package/src/validators/type-error.js +0 -22
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@contentstack/cli-migration",
3
- "version": "2.0.0-beta.2",
3
+ "version": "2.0.0-beta.3",
4
4
  "author": "@contentstack",
5
5
  "bugs": "https://github.com/contentstack/cli/issues",
6
6
  "dependencies": {
7
- "@contentstack/cli-command": "~1.7.02",
8
- "@contentstack/cli-utilities": "~1.17.0",
7
+ "@contentstack/cli-command": "~1.7.2",
8
+ "@contentstack/cli-utilities": "~1.17.1",
9
9
  "@oclif/core": "^4.3.0",
10
10
  "@oclif/plugin-help": "^6.2.28",
11
11
  "async": "^3.2.6",
@@ -18,6 +18,8 @@
18
18
  },
19
19
  "devDependencies": {
20
20
  "@oclif/test": "^4.1.13",
21
+ "@types/mocha": "^8.2.3",
22
+ "@types/node": "^14.18.63",
21
23
  "chai": "^4.5.0",
22
24
  "eslint": "^8.57.1",
23
25
  "eslint-config-oclif": "^6.0.62",
@@ -27,16 +29,17 @@
27
29
  "nyc": "^15.1.0",
28
30
  "oclif": "^4.17.46",
29
31
  "sinon": "^19.0.5",
30
- "sinon-chai": "^3.7.0"
32
+ "source-map-support": "^0.5.21",
33
+ "ts-node": "^10.9.2",
34
+ "typescript": "^4.9.5"
31
35
  },
32
36
  "engines": {
33
37
  "node": ">=8.3.0"
34
38
  },
35
39
  "files": [
40
+ "/lib",
36
41
  "/npm-shrinkwrap.json",
37
- "/oclif.manifest.json",
38
- "/src",
39
- "/yarn.lock"
42
+ "/oclif.manifest.json"
40
43
  ],
41
44
  "homepage": "https://github.com/contentstack/cli",
42
45
  "keywords": [
@@ -44,16 +47,20 @@
44
47
  ],
45
48
  "license": "MIT",
46
49
  "oclif": {
47
- "commands": "./src/commands",
50
+ "commands": "./lib/commands",
48
51
  "bin": "csdx",
49
52
  "repositoryPrefix": "<%- repo %>/blob/main/packages/contentstack-migration/<%- commandPath %>"
50
53
  },
51
54
  "repository": "contentstack/cli",
52
55
  "scripts": {
53
56
  "postpack": "rm -f oclif.manifest.json",
54
- "generate-api-ref-md-doc": "nyc jsdoc2md ./src/modules/* > ./docs/api-reference.md",
55
- "prepack": "oclif manifest && oclif readme && pnpm generate-api-ref-md-doc",
56
- "test": "nyc mocha --timeout 3000 \"test/**/*.test.js\"",
57
+ "generate-api-ref-md-doc": "nyc jsdoc2md ./src/modules/*.ts > ./docs/api-reference.md || true",
58
+ "compile": "tsc -b tsconfig.json",
59
+ "prepack": "pnpm compile && oclif manifest && oclif readme",
60
+ "pretest": "tsc -p test",
61
+ "test": "mocha --forbid-only \"test/unit/**/*.test.ts\"",
62
+ "test:unit": "mocha --timeout 10000 --forbid-only \"test/unit/**/*.test.ts\"",
63
+ "test:unit:report": "nyc --extension .ts mocha --forbid-only \"test/unit/**/*.test.ts\"",
57
64
  "version": "oclif readme && git add README.md",
58
65
  "clean": "rm -rf ./node_modules tsconfig.build.tsbuildinfo"
59
66
  },
@@ -62,4 +69,4 @@
62
69
  "cm:stacks:migration": "MGRTN"
63
70
  }
64
71
  }
65
- }
72
+ }
@@ -1,32 +0,0 @@
1
- /* eslint-disable no-unused-expressions */
2
- 'use strict';
3
-
4
- class ActionList {
5
- constructor(actionList, typeErrors) {
6
- typeErrors && (this.typeErrors = typeErrors);
7
- actionList && (this.actionList = actionList);
8
- this.validators = [];
9
- }
10
-
11
- addValidators(validator) {
12
- this.validators.push(validator);
13
- }
14
-
15
- validate() {
16
- const { validators, actionList } = this;
17
-
18
- let errors = [];
19
- for (const action of actionList) {
20
- for (const validator of validators) {
21
- if (validator.isApplicable(action)) {
22
- errors = validator.validate(action);
23
- break;
24
- }
25
- }
26
- }
27
-
28
- return errors;
29
- }
30
- }
31
-
32
- module.exports = ActionList;
@@ -1,217 +0,0 @@
1
- 'use strict';
2
-
3
- // Utils
4
- const { constants } = require('../utils');
5
- // Properties
6
- const { actions, validationAction } = constants;
7
- const {
8
- create,
9
- customTask,
10
- edit,
11
- transformEntries,
12
- deriveLinkedEntries,
13
- transformEntriesToType,
14
- typeError,
15
- apiError,
16
- schema,
17
- __migrationError,
18
- field,
19
- } = validationAction;
20
-
21
- const actionCreators = {
22
- customTasks: (callsite, opts) => {
23
- const { CUSTOM_TASK } = actions;
24
- return {
25
- type: customTask,
26
- meta: {
27
- callsite: {
28
- file: callsite.getFileName(),
29
- line: callsite.getLineNumber(),
30
- },
31
- },
32
- payload: {
33
- options: opts,
34
- action: CUSTOM_TASK,
35
- },
36
- };
37
- },
38
- contentType: {
39
- create: (callsite, id, opts) => {
40
- const { CREATE_CT } = actions;
41
- return {
42
- type: create,
43
- meta: {
44
- callsite: {
45
- file: callsite.getFileName(),
46
- line: callsite.getLineNumber(),
47
- },
48
- },
49
- payload: {
50
- contentTypeId: id,
51
- options: opts,
52
- action: CREATE_CT,
53
- },
54
- };
55
- },
56
- edit: (callsite, id, opts) => {
57
- const { EDIT_CT } = actions;
58
-
59
- return {
60
- type: edit,
61
- meta: {
62
- callsite: {
63
- file: callsite.getFileName(),
64
- line: callsite.getLineNumber(),
65
- },
66
- },
67
- payload: {
68
- contentTypeId: id,
69
- options: opts,
70
- action: EDIT_CT,
71
- },
72
- };
73
- },
74
- // delete: () => { },
75
- transformEntries: (callsite, id, opts) => {
76
- return {
77
- type: transformEntries,
78
- meta: {
79
- callsite: {
80
- file: callsite.getFileName(),
81
- line: callsite.getLineNumber(),
82
- },
83
- },
84
- payload: {
85
- options: opts,
86
- },
87
- };
88
- },
89
- deriveLinkedEntries: (callsite, id, opts) => {
90
- return {
91
- type: deriveLinkedEntries,
92
- meta: {
93
- callsite: {
94
- file: callsite.getFileName(),
95
- line: callsite.getLineNumber(),
96
- },
97
- },
98
- payload: {
99
- options: opts,
100
- },
101
- };
102
- },
103
- transformEntriesToType: (callsite, id, opts) => {
104
- return {
105
- type: transformEntriesToType,
106
- meta: {
107
- callsite: {
108
- file: callsite.getFileName(),
109
- line: callsite.getLineNumber(),
110
- },
111
- },
112
- payload: {
113
- options: opts,
114
- },
115
- };
116
- },
117
- typeError: (callsite, id, { typeErrors }) => {
118
- return {
119
- type: typeError,
120
- meta: {
121
- callsite: {
122
- file: callsite.getFileName(),
123
- line: callsite.getLineNumber(),
124
- },
125
- },
126
- payload: { typeErrors },
127
- };
128
- },
129
- apiError: (callsite, id, opts) => {
130
- return {
131
- type: apiError,
132
- meta: {
133
- callsite: {
134
- file: callsite.getFileName(),
135
- line: callsite.getLineNumber(),
136
- },
137
- },
138
- payload: { apiError: opts },
139
- };
140
- },
141
- fromFields: (callsite, id, opts) => {
142
- return {
143
- type: schema,
144
- meta: {
145
- callsite: {
146
- file: callsite.getFileName(),
147
- line: callsite.getLineNumber(),
148
- },
149
- },
150
- payload: { fromField: opts.fromField },
151
- };
152
- },
153
- toFields: (callsite, id, opts) => {
154
- return {
155
- type: schema,
156
- meta: {
157
- callsite: {
158
- file: callsite.getFileName(),
159
- line: callsite.getLineNumber(),
160
- },
161
- },
162
- payload: { toField: opts.toField },
163
- };
164
- },
165
- toReferenceFields: (callsite, id, opts) => {
166
- return {
167
- type: schema,
168
- meta: {
169
- callsite: {
170
- file: callsite.getFileName(),
171
- line: callsite.getLineNumber(),
172
- },
173
- },
174
- payload: { toField: opts.toReferenceField },
175
- };
176
- },
177
- deriveFields: (callsite, id, opts) => {
178
- return {
179
- type: schema,
180
- meta: {
181
- callsite: {
182
- file: callsite.getFileName(),
183
- line: callsite.getLineNumber(),
184
- },
185
- },
186
- payload: { deriveField: opts.deriveField },
187
- };
188
- },
189
- migrationError: (callsite, id, opts) => {
190
- return {
191
- type: __migrationError,
192
- meta: {
193
- callsite: {
194
- file: callsite.getFileName(),
195
- line: callsite.getLineNumber(),
196
- },
197
- },
198
- payload: { migrationError: opts },
199
- };
200
- },
201
- field: (callsite, id, opts) => {
202
- return {
203
- type: field,
204
- meta: {
205
- callsite: {
206
- file: callsite.getFileName(),
207
- line: callsite.getLineNumber(),
208
- },
209
- },
210
- payload: { field: opts },
211
- };
212
- },
213
- },
214
- };
215
-
216
- exports.actionCreators = actionCreators;
217
- exports.ActionList = require('./action-list');
@@ -1,283 +0,0 @@
1
- /* eslint-disable no-unused-expressions */
2
- /* eslint-disable no-warning-comments */
3
- /* eslint-disable camelcase */
4
- 'use strict';
5
-
6
- // Dependencies
7
- const Listr = require('listr');
8
- const { resolve, extname } = require('path');
9
- const { Command } = require('@contentstack/cli-command');
10
- const { waterfall } = require('async');
11
- const { Parser } = require('../../../modules');
12
- const { ActionList } = require('../../../actions');
13
- const fs = require('fs');
14
- const chalk = require('chalk');
15
- const isEmpty = require('lodash/isEmpty');
16
- const {
17
- managementSDKClient,
18
- flags,
19
- isAuthenticated,
20
- pathValidator,
21
- sanitizePath,
22
- } = require('@contentstack/cli-utilities');
23
-
24
- const { ApiError, SchemaValidator, MigrationError, FieldValidator } = require('../../../validators');
25
-
26
- // Utils
27
- const { map: _map, constants, safePromise, errorHelper, installModules } = require('../../../utils');
28
- // Properties
29
- const { get, set, getMapInstance, resetMapInstance } = _map;
30
- const {
31
- requests: _requests,
32
- actionMapper,
33
- MANAGEMENT_SDK,
34
- MANAGEMENT_TOKEN,
35
- AUTH_TOKEN,
36
- API_KEY,
37
- BRANCH,
38
- MANAGEMENT_CLIENT,
39
- } = constants;
40
-
41
- class MigrationCommand extends Command {
42
- static examples = [
43
- '$ csdx cm:migration --file-path <migration/script/file/path> --stack-api-key <stack-api-key>',
44
- '$ csdx cm:migration --file-path <migration/script/file/path> --stack-api-key <stack-api-key> --branch <target branch name>',
45
- '$ csdx cm:migration --config <key1>:<value1> <key2>:<value2> ... --file-path <migration/script/file/path>',
46
- '$ csdx cm:migration --config-file <path/to/json/config/file> --file-path <migration/script/file/path>',
47
- '$ csdx cm:migration --multiple --file-path <migration/scripts/dir/path> ',
48
- '$ csdx cm:migration --alias <management-token-alias> --file-path <migration/script/file/path>',
49
- ];
50
-
51
- async run() {
52
- // TODO: filePath validation required.
53
- const { flags: migrationCommandFlags } = await this.parse(MigrationCommand);
54
- const { branch } = migrationCommandFlags || {};
55
- const filePath = migrationCommandFlags['file-path'] || migrationCommandFlags.filePath;
56
- const multi = migrationCommandFlags.multiple || migrationCommandFlags.multi;
57
- const authtoken = isAuthenticated();
58
- const apiKey = migrationCommandFlags['api-key'] || migrationCommandFlags['stack-api-key'];
59
- const alias = migrationCommandFlags['alias'] || migrationCommandFlags['management-token-alias'];
60
- const config = migrationCommandFlags['config'];
61
-
62
- if (!authtoken && !alias) {
63
- this.log(
64
- "AuthToken is not present in local drive, Hence use 'csdx auth:login' command for login or provide management token alias",
65
- );
66
- this.exit();
67
- }
68
-
69
- if (!filePath || !fs.existsSync(filePath)) {
70
- this.log('Please provide the migration script file path, use --file-path flag');
71
- this.exit();
72
- }
73
-
74
- // Reset map instance
75
- const mapInstance = getMapInstance();
76
- resetMapInstance(mapInstance);
77
- if (migrationCommandFlags['config-file']) {
78
- set('config-path', mapInstance, migrationCommandFlags['config-file']);
79
- }
80
-
81
- if (Array.isArray(config) && config.length > 0) {
82
- let configObj = config.reduce((a, v) => {
83
- //NOTE: Temp code to handle only one spilt(Window absolute path issue).Need to replace with hardcoded config key
84
- let [key, ...value] = v.split(':');
85
- value = value?.length > 1 ? value?.join(':') : value?.join();
86
- return { ...a, [key]: value };
87
- }, {});
88
- set('config', mapInstance, configObj);
89
- }
90
-
91
- const APIClient = await managementSDKClient({ host: this.cmaHost });
92
- let stackSDKInstance;
93
- if (branch) {
94
- set(BRANCH, mapInstance, branch);
95
- }
96
-
97
- if (alias) {
98
- let managementToken = this.getToken(alias);
99
- if (managementToken) {
100
- set(MANAGEMENT_TOKEN, mapInstance, managementToken);
101
- set(API_KEY, mapInstance, managementToken.apiKey);
102
- if (branch) {
103
- stackSDKInstance = APIClient.stack({
104
- management_token: managementToken.token,
105
- api_key: managementToken.apiKey,
106
- branch_uid: branch,
107
- });
108
- } else {
109
- stackSDKInstance = APIClient.stack({
110
- management_token: managementToken.token,
111
- api_key: managementToken.apiKey,
112
- });
113
- }
114
- }
115
- } else if (authtoken) {
116
- set(AUTH_TOKEN, mapInstance, authtoken);
117
- set(API_KEY, mapInstance, apiKey);
118
- if (branch) {
119
- stackSDKInstance = APIClient.stack({
120
- api_key: apiKey,
121
- branch_uid: branch,
122
- });
123
- } else {
124
- stackSDKInstance = APIClient.stack({ api_key: apiKey });
125
- }
126
- }
127
-
128
- set(MANAGEMENT_SDK, mapInstance, stackSDKInstance);
129
- set(MANAGEMENT_CLIENT, mapInstance, APIClient);
130
-
131
- if (!(await installModules(filePath, multi))) {
132
- this.log(`Error: Failed to install dependencies for the specified scripts.`);
133
- process.exit(1);
134
- }
135
-
136
- if (multi) {
137
- await this.execMultiFiles(filePath, mapInstance);
138
- } else {
139
- await this.execSingleFile(filePath, mapInstance);
140
- }
141
- const errLogPath = `${process.cwd()}/migration-logs`;
142
- if (fs.existsSync(errLogPath)) {
143
- this.log(`The log has been stored at: `, errLogPath);
144
- }
145
- }
146
-
147
- async execSingleFile(filePath, mapInstance) {
148
- // Resolved absolute path
149
- const resolvedMigrationPath = pathValidator(filePath);
150
- // User provided migration function
151
- const migrationFunc = require(resolvedMigrationPath);
152
-
153
- const parser = new Parser();
154
-
155
- try {
156
- const migrationParser = await parser.getMigrationParser(migrationFunc);
157
- if (migrationParser.hasErrors) {
158
- errorHelper(migrationParser.hasErrors);
159
- // When the process is child, send error message to parent
160
- if (process.send) process.send({ errorOccurred: true });
161
- this.exit(1);
162
- }
163
-
164
- // Make calls from here
165
- const requests = get(_requests, mapInstance);
166
- // Fetches tasks array
167
- const tasks = this.getTasks(requests);
168
-
169
- const listr = new Listr(tasks);
170
-
171
- await listr.run();
172
- requests.splice(0, requests.length);
173
- } catch (error) {
174
- errorHelper(error, filePath);
175
- if (process.send) process.send({ errorOccurred: true });
176
- }
177
- }
178
-
179
- async execMultiFiles(filePath, mapInstance) {
180
- // Resolved absolute path
181
- const resolvedMigrationPath = pathValidator(filePath);
182
- try {
183
- const files = fs.readdirSync(resolvedMigrationPath);
184
- for (const element of files) {
185
- const file = element;
186
- if (extname(file) === '.js') {
187
- // eslint-disable-next-line no-await-in-loop
188
- await this.execSingleFile(pathValidator(resolve(sanitizePath(filePath), sanitizePath(file))), mapInstance);
189
- }
190
- }
191
- } catch (error) {
192
- errorHelper(error);
193
- }
194
- }
195
-
196
- getTasks(requests) {
197
- const _tasks = [];
198
- const results = [];
199
-
200
- const taskFn = (reqObj) => {
201
- const { failedTitle, successTitle, tasks } = reqObj;
202
-
203
- return async (ctx, task) => {
204
- const [err, result] = await safePromise(waterfall(tasks));
205
- if (err) {
206
- ctx.error = true;
207
- task.title = failedTitle;
208
- throw err;
209
- }
210
- result && results.push(result);
211
- task.title = successTitle;
212
- return result;
213
- };
214
- };
215
-
216
- for (const element of requests) {
217
- let reqObj = element;
218
- const { title } = reqObj;
219
- const taskObj = {
220
- title: title,
221
- task: taskFn(reqObj),
222
- };
223
- _tasks.push(taskObj);
224
- }
225
- return _tasks;
226
- }
227
-
228
- handleErrors() {
229
- const mapInstance = getMapInstance();
230
- const actions = get(actionMapper, mapInstance);
231
- const actionList = new ActionList(actions);
232
-
233
- actionList.addValidators(new ApiError());
234
- actionList.addValidators(new SchemaValidator());
235
- actionList.addValidators(new MigrationError());
236
- actionList.addValidators(new FieldValidator());
237
-
238
- const errors = actionList.validate();
239
- errorHelper(errors);
240
- }
241
- }
242
-
243
- MigrationCommand.description = 'Contentstack migration script.';
244
-
245
- MigrationCommand.flags = {
246
- 'stack-api-key': flags.string({
247
- char: 'k',
248
- description:
249
- 'Use this flag to add the API key of your stack. You must use either the --stack-api-key flag or the --alias flag.',
250
- exclusive: ['alias'],
251
- }),
252
- alias: flags.string({
253
- char: 'a',
254
- description:
255
- 'Use this flag to add the management token alias. You must use either the --alias flag or the --stack-api-key flag.',
256
- exclusive: ['stack-api-key'],
257
- }),
258
- 'file-path': flags.string({
259
- description: 'Use this flag to provide the path of the file of the migration script.',
260
- }),
261
- branch: flags.string({
262
- description: 'Use this flag to add the branch name where you want to perform the migration. (target branch name)',
263
- }),
264
- 'config-file': flags.string({
265
- description: '[optional] Path of the JSON configuration file.',
266
- }),
267
- config: flags.string({
268
- description:
269
- '[optional] Inline configuration, <key1>:<value1>. Passing an external configuration makes the script re-usable.',
270
- multiple: true,
271
- }),
272
- multiple: flags.boolean({
273
- description:
274
- 'This flag helps you to migrate multiple content files in a single instance. Mention the folder path where your migration script files are stored.',
275
- }),
276
- };
277
-
278
- MigrationCommand.aliases = [];
279
-
280
- MigrationCommand.usage =
281
- 'cm:stacks:migration [-k <value>] [-a <value>] [--file-path <value>] [--branch <value>] [--config-file <value>] [--config <value>] [--multiple]';
282
-
283
- module.exports = MigrationCommand;
@@ -1,18 +0,0 @@
1
- /* eslint-disable camelcase */
2
- 'use strict';
3
-
4
- const { CONTENTSTACK_API_KEY, CONTENTSTACK_AUTHTOKEN } = process.env;
5
- const { version } = require('../../package.json');
6
- module.exports = {
7
- hostname: 'api.contentstack.io',
8
- version: '/v3',
9
- method: 'GET', // Default Http method
10
- headers: {
11
- 'Content-Type': 'application/json',
12
- 'Content-Length': null,
13
- 'X-User-Agent': `@contentstack-migration/v${version}`,
14
- authtoken: CONTENTSTACK_AUTHTOKEN,
15
- api_key: CONTENTSTACK_API_KEY,
16
- // management_token: CONTENTSTACK_MANAGEMENT_TOKEN
17
- },
18
- };
@@ -1,7 +0,0 @@
1
- /* eslint-disable camelcase */
2
- 'use strict';
3
-
4
- module.exports = {
5
- is_page: false,
6
- singleton: false,
7
- };
@@ -1,7 +0,0 @@
1
- 'use strict';
2
-
3
- module.exports = {
4
- apiConfig: require('./api-config'),
5
- defaultOptions: require('./default-options'),
6
- masterLocale: require('./master-locale'),
7
- };
@@ -1,10 +0,0 @@
1
- /* eslint-disable camelcase */
2
- 'use strict';
3
-
4
- module.exports = {
5
- master_locale: {
6
- // master locale of the stack
7
- name: 'English - United States',
8
- code: 'en-us',
9
- },
10
- };