contensis-cli 1.0.12-beta.1 → 1.0.12-beta.11
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.
- package/README.md +9 -9
- package/dist/commands/get.js +13 -1
- package/dist/commands/get.js.map +2 -2
- package/dist/commands/globalOptions.js +9 -10
- package/dist/commands/globalOptions.js.map +2 -2
- package/dist/commands/import.js +25 -10
- package/dist/commands/import.js.map +2 -2
- package/dist/commands/index.js +2 -2
- package/dist/commands/index.js.map +2 -2
- package/dist/commands/list.js +9 -0
- package/dist/commands/list.js.map +2 -2
- package/dist/commands/remove.js +13 -0
- package/dist/commands/remove.js.map +2 -2
- package/dist/localisation/en-GB.js +8 -2
- package/dist/localisation/en-GB.js.map +2 -2
- package/dist/mappers/DevInit-to-CIWorkflow.js +6 -8
- package/dist/mappers/DevInit-to-CIWorkflow.js.map +2 -2
- package/dist/mappers/DevInit-to-RolePermissions.js.map +2 -2
- package/dist/providers/file-provider.js +5 -1
- package/dist/providers/file-provider.js.map +2 -2
- package/dist/services/ContensisAuthService.js.map +2 -2
- package/dist/services/ContensisCliService.js +164 -75
- package/dist/services/ContensisCliService.js.map +3 -3
- package/dist/services/ContensisDevService.js +48 -53
- package/dist/services/ContensisDevService.js.map +3 -3
- package/dist/shell.js +5 -0
- package/dist/shell.js.map +2 -2
- package/dist/util/console.printer.js +111 -10
- package/dist/util/console.printer.js.map +2 -2
- package/dist/util/error.js +36 -0
- package/dist/util/error.js.map +7 -0
- package/dist/util/find.js +10 -2
- package/dist/util/find.js.map +2 -2
- package/dist/util/git.js +1 -0
- package/dist/util/git.js.map +2 -2
- package/dist/util/logger.js +52 -9
- package/dist/util/logger.js.map +3 -3
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +4 -4
- package/src/commands/get.ts +19 -1
- package/src/commands/globalOptions.ts +9 -7
- package/src/commands/import.ts +41 -13
- package/src/commands/index.ts +2 -3
- package/src/commands/list.ts +15 -0
- package/src/commands/remove.ts +20 -0
- package/src/localisation/en-GB.ts +10 -3
- package/src/mappers/DevInit-to-CIWorkflow.ts +6 -8
- package/src/mappers/DevInit-to-RolePermissions.ts +1 -0
- package/src/models/Cache.d.ts +1 -1
- package/src/providers/file-provider.ts +5 -1
- package/src/services/ContensisAuthService.ts +1 -1
- package/src/services/ContensisCliService.ts +206 -101
- package/src/services/ContensisDevService.ts +70 -66
- package/src/shell.ts +5 -0
- package/src/util/console.printer.ts +238 -12
- package/src/util/error.ts +7 -0
- package/src/util/find.ts +13 -2
- package/src/util/git.ts +2 -1
- package/src/util/logger.ts +90 -15
- package/src/version.ts +1 -1
|
@@ -46,11 +46,14 @@ var import_os = require("../util/os");
|
|
|
46
46
|
var import_yaml = require("../util/yaml");
|
|
47
47
|
var import_nanospinner = require("nanospinner");
|
|
48
48
|
var import_gitignore = require("../util/gitignore");
|
|
49
|
-
var import_ContensisAuthService = __toESM(require("./ContensisAuthService"));
|
|
50
49
|
var import_ansi_escapes = __toESM(require("ansi-escapes"));
|
|
51
50
|
class ContensisDev extends import_ContensisRoleService.default {
|
|
52
51
|
git;
|
|
53
52
|
blockId;
|
|
53
|
+
deployCredentials = {
|
|
54
|
+
clientId: "",
|
|
55
|
+
clientSecret: ""
|
|
56
|
+
};
|
|
54
57
|
constructor(args, outputOpts, contensisOpts = {}) {
|
|
55
58
|
super(args, outputOpts, contensisOpts);
|
|
56
59
|
}
|
|
@@ -64,7 +67,6 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
64
67
|
const { currentEnv, currentProject, log, messages } = this;
|
|
65
68
|
const contensis = await this.ConnectContensis();
|
|
66
69
|
if (contensis) {
|
|
67
|
-
this.devinit = { ...this.devinit, invokedBy: this.invokedBy };
|
|
68
70
|
const validateBlockId = (blockId2) => {
|
|
69
71
|
const pattern = /^[0-9a-z](-?[0-9a-z])*$/;
|
|
70
72
|
if (blockId2.length >= 1 && blockId2.length <= 225) {
|
|
@@ -77,7 +79,8 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
77
79
|
type: "input",
|
|
78
80
|
prefix: "\u{1F9F1}",
|
|
79
81
|
message: messages.devinit.blockIdQuestion,
|
|
80
|
-
validate: validateBlockId
|
|
82
|
+
validate: validateBlockId,
|
|
83
|
+
default: git.name
|
|
81
84
|
});
|
|
82
85
|
this.blockId = blockId.toLowerCase();
|
|
83
86
|
log.success(`Valid block id: ${blockId.toLowerCase()}`);
|
|
@@ -96,47 +99,12 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
96
99
|
const devKeyName = `${apiKeyName}`;
|
|
97
100
|
const devKeyDescription = `Created by Contensis to allow API access from the running block`;
|
|
98
101
|
let existingDevKey = apiKeyExists(devKeyName);
|
|
99
|
-
if (!existingDevKey) {
|
|
100
|
-
existingDevKey = await this.CreateOrUpdateApiKey(
|
|
101
|
-
existingDevKey,
|
|
102
|
-
devKeyName,
|
|
103
|
-
devKeyDescription
|
|
104
|
-
);
|
|
105
|
-
log.success("Successfully created development key");
|
|
106
|
-
}
|
|
107
102
|
const deployKeyName = `${apiKeyName}-ci`;
|
|
108
103
|
const deployKeyDescription = `Created by the Contensis CLI for use in continuous integration`;
|
|
109
104
|
let existingDeployKey = apiKeyExists(deployKeyName);
|
|
110
|
-
if (!existingDeployKey) {
|
|
111
|
-
existingDeployKey = await this.CreateOrUpdateApiKey(
|
|
112
|
-
existingDeployKey,
|
|
113
|
-
deployKeyName,
|
|
114
|
-
deployKeyDescription
|
|
115
|
-
);
|
|
116
|
-
log.success("Successfully created deploy key");
|
|
117
|
-
}
|
|
118
|
-
if (existingDeployKey) {
|
|
119
|
-
this.devinit = {
|
|
120
|
-
...this.devinit,
|
|
121
|
-
credentials: {
|
|
122
|
-
clientId: existingDeployKey == null ? void 0 : existingDeployKey.id,
|
|
123
|
-
clientSecret: existingDeployKey == null ? void 0 : existingDeployKey.sharedSecret
|
|
124
|
-
}
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
const credentials = await this.GetCredentials(this.devinit.invokedBy);
|
|
128
|
-
let classicToken;
|
|
129
|
-
const auth = new import_ContensisAuthService.default({
|
|
130
|
-
username: (_a = credentials == null ? void 0 : credentials.current) == null ? void 0 : _a.account,
|
|
131
|
-
password: (_b = credentials == null ? void 0 : credentials.current) == null ? void 0 : _b.password,
|
|
132
|
-
projectId: currentProject,
|
|
133
|
-
rootUrl: `https://cms-${currentEnv}.cloud.contensis.com`
|
|
134
|
-
});
|
|
135
|
-
classicToken = await auth.ClassicToken();
|
|
136
105
|
const errors = [];
|
|
137
106
|
log.raw("");
|
|
138
107
|
log.success(messages.devinit.intro());
|
|
139
|
-
log.raw("");
|
|
140
108
|
log.raw(
|
|
141
109
|
log.infoText(
|
|
142
110
|
messages.devinit.projectDetails(
|
|
@@ -174,7 +142,6 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
174
142
|
git.ciFileName = ciFileName;
|
|
175
143
|
}
|
|
176
144
|
log.raw(log.infoText(messages.devinit.ciDetails(ciFileName)));
|
|
177
|
-
let mappedWorkflow;
|
|
178
145
|
const { loc } = await import_inquirer.default.prompt({
|
|
179
146
|
name: "loc",
|
|
180
147
|
type: "list",
|
|
@@ -191,8 +158,8 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
191
158
|
}
|
|
192
159
|
]
|
|
193
160
|
});
|
|
161
|
+
log.raw("");
|
|
194
162
|
log.help(messages.devinit.ciIntro(git, loc));
|
|
195
|
-
mappedWorkflow = await (0, import_DevInit_to_CIWorkflow.mapCIWorkflowContent)(this, loc);
|
|
196
163
|
if (!dryRun) {
|
|
197
164
|
const { confirm } = await import_inquirer.default.prompt([
|
|
198
165
|
{
|
|
@@ -207,14 +174,13 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
207
174
|
return;
|
|
208
175
|
}
|
|
209
176
|
let accessToken = void 0;
|
|
210
|
-
log.raw("");
|
|
211
177
|
const spinner = (0, import_nanospinner.createSpinner)(messages.devinit.accessTokenFetch());
|
|
212
178
|
spinner.start();
|
|
213
179
|
const token = await this.GetDeliveryApiKey();
|
|
214
180
|
if (token) {
|
|
215
|
-
spinner.success();
|
|
216
|
-
this.log.success(messages.devinit.accessTokenSuccess(token));
|
|
217
181
|
accessToken = token;
|
|
182
|
+
spinner.success({ text: messages.devinit.accessTokenSuccess(token) });
|
|
183
|
+
log.raw("");
|
|
218
184
|
} else {
|
|
219
185
|
spinner.error();
|
|
220
186
|
this.log.error(messages.devinit.accessTokenFailed());
|
|
@@ -234,6 +200,27 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
234
200
|
if (dryRun) {
|
|
235
201
|
checkpoint(`skip api key creation (dry-run)`);
|
|
236
202
|
} else {
|
|
203
|
+
const devKeyExisted = !!existingDevKey;
|
|
204
|
+
if (!existingDevKey) {
|
|
205
|
+
existingDevKey = await this.CreateOrUpdateApiKey(
|
|
206
|
+
existingDevKey,
|
|
207
|
+
devKeyName,
|
|
208
|
+
devKeyDescription
|
|
209
|
+
);
|
|
210
|
+
log.success(messages.devinit.createDevKey(devKeyName, devKeyExisted));
|
|
211
|
+
}
|
|
212
|
+
const deployKeyExisted = !!existingDeployKey;
|
|
213
|
+
if (!existingDeployKey) {
|
|
214
|
+
existingDeployKey = await this.CreateOrUpdateApiKey(
|
|
215
|
+
existingDeployKey,
|
|
216
|
+
deployKeyName,
|
|
217
|
+
deployKeyDescription
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
if (existingDeployKey) {
|
|
221
|
+
this.deployCredentials.clientId = existingDeployKey == null ? void 0 : existingDeployKey.id;
|
|
222
|
+
this.deployCredentials.clientSecret = existingDeployKey == null ? void 0 : existingDeployKey.sharedSecret;
|
|
223
|
+
}
|
|
237
224
|
const deployRoleName = `Role for CI push of block '${blockId}'`;
|
|
238
225
|
const deplyRoleDescription = `Created by the Contensis CLI for use in continuous integration`;
|
|
239
226
|
let existingDeployRole = (0, import_find.findByIdOrName)(
|
|
@@ -243,10 +230,12 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
243
230
|
);
|
|
244
231
|
existingDeployRole = await this.CreateOrUpdateRole(
|
|
245
232
|
existingDeployRole,
|
|
246
|
-
(0, import_DevInit_to_RolePermissions.deployKeyRole)(
|
|
233
|
+
(0, import_DevInit_to_RolePermissions.deployKeyRole)(deployRoleName, deplyRoleDescription)
|
|
247
234
|
);
|
|
248
235
|
checkpoint("deploy key role assigned");
|
|
249
|
-
log.success(
|
|
236
|
+
log.success(
|
|
237
|
+
messages.devinit.createDeployKey(deployRoleName, deployKeyExisted)
|
|
238
|
+
);
|
|
250
239
|
checkpoint("api keys done");
|
|
251
240
|
}
|
|
252
241
|
const envFilePath = `${projectHome}/.env`;
|
|
@@ -295,20 +284,23 @@ ${envDiff}`);
|
|
|
295
284
|
checkpoint("skip .env file update (dry-run)");
|
|
296
285
|
} else {
|
|
297
286
|
if (envDiff)
|
|
298
|
-
log.info(`
|
|
287
|
+
log.info(`Updating .env file ${(0, import_os.winSlash)(envFilePath)}`);
|
|
299
288
|
(0, import_file_provider.writeFile)(envFilePath, envFileLines.join("\n"));
|
|
300
289
|
checkpoint(".env file updated");
|
|
301
290
|
log.success(messages.devinit.writeEnvFile());
|
|
302
291
|
}
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
292
|
+
if (dryRun) {
|
|
293
|
+
checkpoint("skip .gitignore file update (dry-run)");
|
|
294
|
+
} else {
|
|
295
|
+
(0, import_gitignore.mergeContentsToAddWithGitignore)(`${projectHome}/.gitignore`, [".env"]);
|
|
296
|
+
log.raw("");
|
|
297
|
+
}
|
|
298
|
+
const mappedWorkflow = await (0, import_DevInit_to_CIWorkflow.mapCIWorkflowContent)(this, loc);
|
|
306
299
|
if (mappedWorkflow == null ? void 0 : mappedWorkflow.diff) {
|
|
307
300
|
log.info(
|
|
308
301
|
`Updating ${(0, import_os.winSlash)(ciFileName)} file:
|
|
309
302
|
${mappedWorkflow.diff}`
|
|
310
303
|
);
|
|
311
|
-
log.raw("");
|
|
312
304
|
}
|
|
313
305
|
if (dryRun) {
|
|
314
306
|
checkpoint("skip CI file update (dry-run)");
|
|
@@ -323,16 +315,18 @@ ${mappedWorkflow.diff}`
|
|
|
323
315
|
} else {
|
|
324
316
|
log.info(messages.devinit.ciFileNoChanges(`./${ciFileName}`));
|
|
325
317
|
}
|
|
318
|
+
log.raw("");
|
|
326
319
|
checkpoint("CI file updated");
|
|
327
320
|
}
|
|
328
321
|
}
|
|
329
322
|
if (loc === "git") {
|
|
323
|
+
const dryRunKeyMessage = dryRun ? "not created in dry-run" : void 0;
|
|
330
324
|
log.warning(messages.devinit.addGitSecretsIntro());
|
|
331
325
|
log.help(
|
|
332
326
|
messages.devinit.addGitSecretsHelp(
|
|
333
327
|
git,
|
|
334
|
-
existingDeployKey == null ? void 0 : existingDeployKey.id,
|
|
335
|
-
existingDeployKey == null ? void 0 : existingDeployKey.sharedSecret
|
|
328
|
+
(existingDeployKey == null ? void 0 : existingDeployKey.id) || dryRunKeyMessage,
|
|
329
|
+
(existingDeployKey == null ? void 0 : existingDeployKey.sharedSecret) || dryRunKeyMessage
|
|
336
330
|
)
|
|
337
331
|
);
|
|
338
332
|
}
|
|
@@ -342,10 +336,11 @@ ${mappedWorkflow.diff}`
|
|
|
342
336
|
} else {
|
|
343
337
|
log.success(messages.devinit.success());
|
|
344
338
|
log.help(messages.devinit.startProjectTip());
|
|
339
|
+
const classicToken = await ((_a = this.auth) == null ? void 0 : _a.ClassicToken());
|
|
345
340
|
log.help(
|
|
346
341
|
import_ansi_escapes.default.link(
|
|
347
342
|
`Open Contensis`,
|
|
348
|
-
|
|
343
|
+
`${(_b = this.urls) == null ? void 0 : _b.cms}${classicToken ? `?SecurityToken=${classicToken}` : ""}`
|
|
349
344
|
)
|
|
350
345
|
);
|
|
351
346
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/ContensisDevService.ts"],
|
|
4
|
-
"sourcesContent": ["import to from 'await-to-js';\nimport { spawn } from 'child_process';\nimport inquirer from 'inquirer';\nimport path from 'path';\n\nimport { Role } from 'contensis-management-api/lib/models';\nimport { MigrateRequest } from 'migratortron';\n\nimport ContensisRole from './ContensisRoleService';\nimport { OutputOptionsConstructorArg } from '~/models/CliService';\nimport { EnvContentsToAdd } from '~/models/DevService';\nimport { mapSiteConfigYaml } from '~/mappers/DevRequests-to-RequestHanderSiteConfigYaml';\nimport { mapCIWorkflowContent } from '~/mappers/DevInit-to-CIWorkflow';\nimport { deployKeyRole } from '~/mappers/DevInit-to-RolePermissions';\nimport { appRootDir, readFile, writeFile } from '~/providers/file-provider';\nimport { diffFileContent } from '~/util/diff';\nimport { mergeDotEnvFileContents } from '~/util/dotenv';\nimport { findByIdOrName } from '~/util/find';\nimport { GitHelper } from '~/util/git';\nimport { jsonFormatter } from '~/util/json.formatter';\nimport { winSlash } from '~/util/os';\nimport { stringifyYaml } from '~/util/yaml';\nimport { createSpinner } from 'nanospinner';\nimport { mergeContentsToAddWithGitignore } from '~/util/gitignore';\nimport ContensisAuthService from './ContensisAuthService';\nimport ansiEscapes from 'ansi-escapes';\n\nclass ContensisDev extends ContensisRole {\n git!: GitHelper;\n blockId!: string;\n\n constructor(\n args: string[],\n outputOpts?: OutputOptionsConstructorArg,\n contensisOpts: Partial<MigrateRequest> = {}\n ) {\n super(args, outputOpts, contensisOpts);\n }\n\n DevelopmentInit = async (projectHome: string, opts: any) => {\n // Retrieve git info\n const git = (this.git = new GitHelper(projectHome));\n // Check if we are in a git repo\n const isRepo = git.checkIsRepo();\n if (!isRepo) return;\n\n const { dryRun = false } = opts || {};\n const { currentEnv, currentProject, log, messages } = this;\n const contensis = await this.ConnectContensis();\n\n if (contensis) {\n this.devinit = { ...this.devinit, invokedBy: this.invokedBy };\n\n // First we need to get the block id from the user\n const validateBlockId = (blockId: string) => {\n const pattern = /^[0-9a-z](-?[0-9a-z])*$/;\n if (blockId.length >= 1 && blockId.length <= 225) {\n return pattern.test(blockId);\n } else return false;\n };\n let { blockId } = await inquirer.prompt({\n name: 'blockId',\n type: 'input',\n prefix: '\uD83E\uDDF1',\n message: messages.devinit.blockIdQuestion,\n validate: validateBlockId,\n });\n // make sure block id is lowercase\n this.blockId = blockId.toLowerCase();\n log.success(`Valid block id: ${blockId.toLowerCase()}`);\n\n // Retrieve keys list for env\n const [keysErr, apiKeys] = await contensis.apiKeys.GetKeys();\n if (keysErr) {\n log.error(messages.keys.noList(currentEnv));\n log.error(jsonFormatter(keysErr));\n return;\n }\n const apiKeyExists = (findKey: string) =>\n apiKeys?.find(\n k => k.name.trim().toLowerCase() === findKey?.trim().toLowerCase()\n );\n\n // Retrieve ci workflow info\n const workflowFiles = git.workflows;\n\n // Set variables for performing operations and logging etc.\n let ciFileName = git.ciFileName;\n\n const apiKeyName = `block-${currentProject}-${blockId}`.toLowerCase();\n\n const devKeyName = `${apiKeyName}`;\n const devKeyDescription = `Created by Contensis to allow API access from the running block`;\n let existingDevKey = apiKeyExists(devKeyName);\n\n // if dev api key doesn't exisit go and create it (we need this for local development, we will store these details in the .env file).\n if (!existingDevKey) {\n existingDevKey = await this.CreateOrUpdateApiKey(\n existingDevKey,\n devKeyName,\n devKeyDescription\n );\n log.success('Successfully created development key');\n }\n\n const deployKeyName = `${apiKeyName}-ci`;\n const deployKeyDescription = `Created by the Contensis CLI for use in continuous integration`;\n\n let existingDeployKey = apiKeyExists(deployKeyName);\n\n // if deploy api key doesn't exisit go and create it (we need this for yml file).\n if (!existingDeployKey) {\n existingDeployKey = await this.CreateOrUpdateApiKey(\n existingDeployKey,\n deployKeyName,\n deployKeyDescription\n );\n log.success('Successfully created deploy key');\n }\n\n // check we have the deply key so we can assign them to this values\n if (existingDeployKey) {\n // Add client id and secret to global 'this'\n this.devinit = {\n ...this.devinit,\n credentials: {\n clientId: existingDeployKey?.id,\n clientSecret: existingDeployKey?.sharedSecret,\n },\n };\n }\n\n // we need to credentials of the user so that we can create a auth service\n const credentials = await this.GetCredentials(this.devinit.invokedBy);\n\n // create new auth service using creds\n let classicToken: string | undefined | null;\n const auth = new ContensisAuthService({\n username: credentials?.current?.account,\n password: credentials?.current?.password,\n projectId: currentProject,\n rootUrl: `https://cms-${currentEnv}.cloud.contensis.com`,\n });\n\n // once we have auth service, we can go and fetch out classic token\n classicToken = await auth.ClassicToken();\n\n // const blockId = git.name;\n const errors = [] as AppError[];\n\n // Start render console output\n log.raw('');\n log.success(messages.devinit.intro());\n log.raw('');\n log.raw(\n log.infoText(\n messages.devinit.projectDetails(\n git.name,\n currentEnv,\n currentProject,\n blockId,\n git\n )\n )\n );\n log.raw(\n log.infoText(\n messages.devinit.developmentKey(devKeyName, !!existingDevKey)\n )\n );\n log.raw(\n log.infoText(\n messages.devinit.deploymentKey(deployKeyName, !!existingDeployKey)\n )\n );\n log.raw('');\n\n if (Array.isArray(workflowFiles) && workflowFiles.length > 1) {\n // Choose GitHub workflow file (if multiple)\n ({ ciFileName } = await inquirer.prompt([\n {\n type: 'list',\n prefix: '\u29F0',\n message: messages.devinit.ciMultipleChoices(),\n name: 'ciFileName',\n choices: workflowFiles,\n default: workflowFiles.find(f => f.includes('docker')),\n },\n ]));\n log.raw('');\n git.ciFileName = ciFileName;\n }\n\n log.raw(log.infoText(messages.devinit.ciDetails(ciFileName)));\n\n let mappedWorkflow;\n // Location for Client ID / Secret.\n const { loc } = await inquirer.prompt({\n name: 'loc',\n type: 'list',\n prefix: '\uD83D\uDD11',\n // Where would you like to store your client id/secret?\n message: messages.devinit.clientDetailsLocation(),\n choices: [\n {\n name: messages.devinit.clientDetailsInGit(git),\n value: 'git',\n },\n {\n name: messages.devinit.clientDetailsInEnv(),\n value: 'env',\n },\n ],\n });\n\n log.help(messages.devinit.ciIntro(git, loc));\n // Update CI Workflow\n mappedWorkflow = await mapCIWorkflowContent(this, loc);\n\n if (!dryRun) {\n // Confirm prompt\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n message: messages.devinit.confirm(),\n name: 'confirm',\n default: false,\n },\n ]);\n log.raw('');\n if (!confirm) return;\n }\n\n // Fetching access token\n let accessToken: string | undefined = undefined;\n log.raw('');\n\n const spinner = createSpinner(messages.devinit.accessTokenFetch());\n spinner.start();\n\n const token = await this.GetDeliveryApiKey();\n\n if (token) {\n spinner.success();\n this.log.success(messages.devinit.accessTokenSuccess(token));\n accessToken = token;\n } else {\n spinner.error();\n this.log.error(messages.devinit.accessTokenFailed());\n return;\n }\n\n // Magic happens...\n const checkpoint = (op: string) => {\n if (errors.length) throw errors[0];\n else log.debug(`${op} completed ok`);\n return true;\n };\n\n // Arrange API keys for development and deployment\n const [getRolesErr, roles] = await to(contensis.roles.GetRoles());\n if (!roles && getRolesErr) errors.push(getRolesErr);\n checkpoint(`fetched ${roles?.length} roles`);\n if (dryRun) {\n checkpoint(`skip api key creation (dry-run)`);\n } else {\n // Ensure deploy API key is assigned to a role with the right permissions\n const deployRoleName = `Role for CI push of block '${blockId}'`;\n const deplyRoleDescription = `Created by the Contensis CLI for use in continuous integration`;\n let existingDeployRole = findByIdOrName(\n roles || [],\n deployRoleName,\n true\n ) as Role | undefined;\n existingDeployRole = await this.CreateOrUpdateRole(\n existingDeployRole,\n deployKeyRole(deployKeyName, deplyRoleDescription)\n );\n\n checkpoint('deploy key role assigned');\n log.success(messages.devinit.createDeployKey(deployRoleName, true));\n checkpoint('api keys done');\n }\n\n const envFilePath = `${projectHome}/.env`;\n const existingEnvFile = readFile(envFilePath);\n let existingEnvFileArray = (existingEnvFile || '')\n .split('\\n')\n .filter(l => !!l);\n\n // Update or create a file called .env in project home\n const envContentsToAdd: EnvContentsToAdd = {\n ALIAS: currentEnv,\n PROJECT_API_ID: currentProject,\n BLOCK_ID: blockId,\n };\n if (accessToken) envContentsToAdd['ACCESS_TOKEN'] = accessToken;\n // add client id and secret to the env file\n if (loc === 'env') {\n envContentsToAdd['CONTENSIS_CLIENT_ID'] = existingDevKey?.id;\n envContentsToAdd['CONTENSIS_CLIENT_SECRET'] =\n existingDevKey?.sharedSecret;\n }\n\n // if we have client id / secret in our env remove it\n const removeEnvItems = (items: string[]) => {\n const indexesToRemove = [];\n\n for (let i = 0; i < existingEnvFileArray.length; i++) {\n for (const item of items) {\n if (existingEnvFileArray[i].includes(item)) {\n indexesToRemove.push(i);\n break;\n }\n }\n }\n\n for (let i = indexesToRemove.length - 1; i >= 0; i--) {\n existingEnvFileArray.splice(indexesToRemove[i], 1);\n }\n };\n\n // remove client id and secret from env file\n if (loc === 'git') {\n removeEnvItems(['CONTENSIS_CLIENT_ID', 'CONTENSIS_CLIENT_SECRET']);\n }\n\n const envFileLines = mergeDotEnvFileContents(\n existingEnvFileArray,\n envContentsToAdd\n );\n const newEnvFileContent = envFileLines.join('\\n');\n const envDiff = diffFileContent(existingEnvFile || '', newEnvFileContent);\n\n if (dryRun) {\n if (envDiff) {\n log.info(`Updating .env file ${winSlash(envFilePath)}:\\n${envDiff}`);\n log.raw('');\n }\n checkpoint('skip .env file update (dry-run)');\n } else {\n if (envDiff) log.info(`updating .env file ${winSlash(envFilePath)}`);\n writeFile(envFilePath, envFileLines.join('\\n'));\n checkpoint('.env file updated');\n log.success(messages.devinit.writeEnvFile());\n // log.help(messages.devinit.useEnvFileTip());\n }\n\n // Update git ignore\n const gitIgnorePath = `${projectHome}/.gitignore`;\n const gitIgnoreContentsToAdd = ['.env'];\n mergeContentsToAddWithGitignore(gitIgnorePath, gitIgnoreContentsToAdd);\n\n // Update CI file -- different for GH/GL\n if (mappedWorkflow?.diff) {\n log.info(\n `Updating ${winSlash(ciFileName)} file:\\n${mappedWorkflow.diff}`\n );\n log.raw('');\n }\n if (dryRun) {\n checkpoint('skip CI file update (dry-run)');\n //log.object(ciFileLines);\n } else {\n if (mappedWorkflow?.newWorkflow) {\n if (mappedWorkflow?.diff) {\n writeFile(git.ciFilePath, mappedWorkflow.newWorkflow);\n log.success(messages.devinit.writeCiFile(`./${ciFileName}`));\n log.info(\n messages.devinit.ciBlockTip(blockId, currentEnv, currentProject)\n );\n } else {\n log.info(messages.devinit.ciFileNoChanges(`./${ciFileName}`));\n }\n checkpoint('CI file updated');\n }\n }\n\n if (loc === 'git') {\n // Echo Deployment API key to console, ask user to add secrets to repo\n log.warning(messages.devinit.addGitSecretsIntro());\n log.help(\n messages.devinit.addGitSecretsHelp(\n git,\n existingDeployKey?.id,\n existingDeployKey?.sharedSecret\n )\n );\n }\n\n if (dryRun) {\n log.success(messages.devinit.dryRun());\n log.help(messages.devinit.noChanges());\n } else {\n log.success(messages.devinit.success());\n log.help(messages.devinit.startProjectTip());\n // open the cms link -- if no classic token just return the cms url\n log.help(\n ansiEscapes.link(\n `Open Contensis`,\n `https://cms-${currentEnv}.cloud.contensis.com${\n classicToken ? `?SecurityToken=${classicToken}` : ''\n }`\n )\n );\n }\n }\n };\n\n ExecRequestHandler = async (blockIds: string[], overrideArgs?: string[]) => {\n // if no request handler exe\n // download it.\n\n // if update arg, redownload it\n\n const { log } = this;\n // const getPrefixOld = log.getPrefix;\n const exeHome = path.join(appRootDir, 'reqhan');\n const exe = 'Zengenti.Contensis.RequestHandler.LocalDevelopment';\n const exePath = path.join(exeHome, exe);\n const siteConfigPath = path.join(appRootDir, 'site_config.yaml');\n\n const siteConfig = await mapSiteConfigYaml(this);\n writeFile('site_config.yaml', stringifyYaml(siteConfig));\n\n const args = overrideArgs\n ? typeof overrideArgs?.[0] === 'string' &&\n overrideArgs[0].includes(' ', 2)\n ? overrideArgs[0].split(' ')\n : overrideArgs\n : []; // args could be [ '-c .\\\\site_config.yaml' ] or [ '-c', '.\\\\site_config.yaml' ]\n\n // Add required args\n if (!args.find(a => a === '-c')) args.push('-c', siteConfigPath);\n\n // const child = execFile(exePath, args);\n\n const child = spawn(exePath, args, { stdio: 'inherit' });\n\n // log.raw('');\n log.info(`Launching request handler...`);\n if (overrideArgs?.length)\n this.log.warning(\n `Spawning process with supplied args: ${JSON.stringify(\n child.spawnargs,\n null,\n 2\n )}`\n );\n\n let isRunning = false;\n\n // Log child output through event listeners\n child?.stdout?.on('data', data => {\n isRunning = true;\n log.raw(data);\n });\n\n child?.stderr?.on('data', data => {\n log.error(data);\n });\n\n child.on('spawn', () => {\n isRunning = true;\n log.help(\n `You may see a firewall popup requesting network access, it is safe to approve`\n );\n // log.getPrefix = () => Logger.infoText(`[rqh]`);\n });\n\n child.on('exit', code => {\n isRunning = false;\n\n log[code === 0 ? 'success' : 'warning'](\n `Request handler exited with code ${code}\\n`\n );\n });\n\n child.on('error', error => {\n isRunning = false;\n log.error(`Could not launch request handler due to error \\n${error}`);\n });\n\n await new Promise(resolve => setTimeout(resolve, 2000));\n\n // keep the method running until we can return\n while (true === true) {\n if (!isRunning) {\n // log.getPrefix = getPrefixOld; // restore logger state\n return;\n }\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n };\n}\nexport const devCommand = (\n commandArgs: string[],\n outputOpts: OutputOptionsConstructorArg,\n contensisOpts: Partial<MigrateRequest> = {}\n) => {\n return new ContensisDev(['', '', ...commandArgs], outputOpts, contensisOpts);\n};\n\nexport default ContensisDev;\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAe;AACf,2BAAsB;AACtB,sBAAqB;AACrB,kBAAiB;AAKjB,kCAA0B;AAG1B,wDAAkC;AAClC,mCAAqC;AACrC,wCAA8B;AAC9B,2BAAgD;AAChD,kBAAgC;AAChC,oBAAwC;AACxC,kBAA+B;AAC/B,iBAA0B;AAC1B,kBAA8B;AAC9B,gBAAyB;AACzB,kBAA8B;AAC9B,yBAA8B;AAC9B,uBAAgD;
|
|
6
|
-
"names": ["ContensisRole", "blockId", "inquirer", "
|
|
4
|
+
"sourcesContent": ["import to from 'await-to-js';\nimport { spawn } from 'child_process';\nimport inquirer from 'inquirer';\nimport path from 'path';\n\nimport { Role } from 'contensis-management-api/lib/models';\nimport { MigrateRequest } from 'migratortron';\n\nimport ContensisRole from './ContensisRoleService';\nimport { OutputOptionsConstructorArg } from '~/models/CliService';\nimport { EnvContentsToAdd } from '~/models/DevService';\nimport { mapSiteConfigYaml } from '~/mappers/DevRequests-to-RequestHanderSiteConfigYaml';\nimport { mapCIWorkflowContent } from '~/mappers/DevInit-to-CIWorkflow';\nimport { deployKeyRole } from '~/mappers/DevInit-to-RolePermissions';\nimport { appRootDir, readFile, writeFile } from '~/providers/file-provider';\nimport { diffFileContent } from '~/util/diff';\nimport { mergeDotEnvFileContents } from '~/util/dotenv';\nimport { findByIdOrName } from '~/util/find';\nimport { GitHelper } from '~/util/git';\nimport { jsonFormatter } from '~/util/json.formatter';\nimport { winSlash } from '~/util/os';\nimport { stringifyYaml } from '~/util/yaml';\nimport { createSpinner } from 'nanospinner';\nimport { mergeContentsToAddWithGitignore } from '~/util/gitignore';\nimport ContensisAuthService from './ContensisAuthService';\nimport ansiEscapes from 'ansi-escapes';\n\nclass ContensisDev extends ContensisRole {\n git!: GitHelper;\n blockId!: string;\n\n deployCredentials = {\n clientId: '',\n clientSecret: '',\n };\n\n constructor(\n args: string[],\n outputOpts?: OutputOptionsConstructorArg,\n contensisOpts: Partial<MigrateRequest> = {}\n ) {\n super(args, outputOpts, contensisOpts);\n }\n\n DevelopmentInit = async (projectHome: string, opts: any) => {\n // Retrieve git info\n const git = (this.git = new GitHelper(projectHome));\n // Check if we are in a git repo\n const isRepo = git.checkIsRepo();\n if (!isRepo) return;\n\n const { dryRun = false } = opts || {};\n const { currentEnv, currentProject, log, messages } = this;\n const contensis = await this.ConnectContensis();\n\n if (contensis) {\n // First we need to get the block id from the user\n const validateBlockId = (blockId: string) => {\n const pattern = /^[0-9a-z](-?[0-9a-z])*$/;\n if (blockId.length >= 1 && blockId.length <= 225) {\n return pattern.test(blockId);\n } else return false;\n };\n let { blockId } = await inquirer.prompt({\n name: 'blockId',\n type: 'input',\n prefix: '\uD83E\uDDF1',\n message: messages.devinit.blockIdQuestion,\n validate: validateBlockId,\n default: git.name,\n });\n // make sure block id is lowercase\n this.blockId = blockId.toLowerCase();\n log.success(`Valid block id: ${blockId.toLowerCase()}`);\n\n // Retrieve keys list for env\n const [keysErr, apiKeys] = await contensis.apiKeys.GetKeys();\n if (keysErr) {\n log.error(messages.keys.noList(currentEnv));\n log.error(jsonFormatter(keysErr));\n return;\n }\n const apiKeyExists = (findKey: string) =>\n apiKeys?.find(\n k => k.name.trim().toLowerCase() === findKey?.trim().toLowerCase()\n );\n\n // Retrieve ci workflow info\n const workflowFiles = git.workflows;\n\n // Set variables for performing operations and logging etc.\n let ciFileName = git.ciFileName;\n\n const apiKeyName = `block-${currentProject}-${blockId}`.toLowerCase();\n\n const devKeyName = `${apiKeyName}`;\n const devKeyDescription = `Created by Contensis to allow API access from the running block`;\n let existingDevKey = apiKeyExists(devKeyName);\n\n const deployKeyName = `${apiKeyName}-ci`;\n const deployKeyDescription = `Created by the Contensis CLI for use in continuous integration`;\n\n let existingDeployKey = apiKeyExists(deployKeyName);\n\n // const blockId = git.name;\n const errors = [] as AppError[];\n\n // Start render console output\n log.raw('');\n log.success(messages.devinit.intro());\n log.raw(\n log.infoText(\n messages.devinit.projectDetails(\n git.name,\n currentEnv,\n currentProject,\n blockId,\n git\n )\n )\n );\n log.raw(\n log.infoText(\n messages.devinit.developmentKey(devKeyName, !!existingDevKey)\n )\n );\n log.raw(\n log.infoText(\n messages.devinit.deploymentKey(deployKeyName, !!existingDeployKey)\n )\n );\n log.raw('');\n\n if (Array.isArray(workflowFiles) && workflowFiles.length > 1) {\n // Choose GitHub workflow file (if multiple)\n ({ ciFileName } = await inquirer.prompt([\n {\n type: 'list',\n prefix: '\u29F0',\n message: messages.devinit.ciMultipleChoices(),\n name: 'ciFileName',\n choices: workflowFiles,\n default: workflowFiles.find(f => f.includes('docker')),\n },\n ]));\n log.raw('');\n git.ciFileName = ciFileName;\n }\n\n log.raw(log.infoText(messages.devinit.ciDetails(ciFileName)));\n\n // Location for Client ID / Secret.\n const { loc } = await inquirer.prompt({\n name: 'loc',\n type: 'list',\n prefix: '\uD83D\uDD11',\n // Where would you like to store your client id/secret?\n message: messages.devinit.clientDetailsLocation(),\n choices: [\n {\n name: messages.devinit.clientDetailsInGit(git),\n value: 'git',\n },\n {\n name: messages.devinit.clientDetailsInEnv(),\n value: 'env',\n },\n ],\n });\n\n log.raw('');\n log.help(messages.devinit.ciIntro(git, loc));\n\n if (!dryRun) {\n // Confirm prompt\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n message: messages.devinit.confirm(),\n name: 'confirm',\n default: false,\n },\n ]);\n log.raw('');\n if (!confirm) return;\n }\n\n // Fetching access token\n let accessToken: string | undefined = undefined;\n\n const spinner = createSpinner(messages.devinit.accessTokenFetch());\n spinner.start();\n\n const token = await this.GetDeliveryApiKey();\n\n if (token) {\n accessToken = token;\n spinner.success({ text: messages.devinit.accessTokenSuccess(token) });\n log.raw('');\n } else {\n spinner.error();\n this.log.error(messages.devinit.accessTokenFailed());\n return;\n }\n\n // Magic happens...\n const checkpoint = (op: string) => {\n if (errors.length) throw errors[0];\n else log.debug(`${op} completed ok`);\n return true;\n };\n\n // Arrange API keys for development and deployment\n const [getRolesErr, roles] = await to(contensis.roles.GetRoles());\n if (!roles && getRolesErr) errors.push(getRolesErr);\n checkpoint(`fetched ${roles?.length} roles`);\n\n if (dryRun) {\n checkpoint(`skip api key creation (dry-run)`);\n } else {\n // if dev api key doesn't exist go and create it (we need this for local development, we will store these details in the .env file).\n const devKeyExisted = !!existingDevKey;\n if (!existingDevKey) {\n existingDevKey = await this.CreateOrUpdateApiKey(\n existingDevKey,\n devKeyName,\n devKeyDescription\n );\n log.success(messages.devinit.createDevKey(devKeyName, devKeyExisted));\n }\n // NF 24/11/23 Added this commented code back in as we are not assigning the dev key to any role here\n // // Ensure dev API key is assigned to a role\n // let existingDevRole = findByIdOrName(roles || [], devKeyName, true) as\n // | Role\n // | undefined;\n // existingDevRole = await this.CreateOrUpdateRole(\n // existingDevRole,\n // devKeyRole(devKeyName, devKeyDescription)\n // );\n // checkpoint('dev key role assigned');\n\n // if deploy api key doesn't exist go and create it (we need this for yml file).\n const deployKeyExisted = !!existingDeployKey;\n if (!existingDeployKey) {\n existingDeployKey = await this.CreateOrUpdateApiKey(\n existingDeployKey,\n deployKeyName,\n deployKeyDescription\n );\n }\n\n // check we have the deploy key so we can assign them to this values\n if (existingDeployKey) {\n // Add client id and secret to credentials\n this.deployCredentials.clientId = existingDeployKey?.id;\n this.deployCredentials.clientSecret = existingDeployKey?.sharedSecret;\n }\n\n // Ensure deploy API key is assigned to a role with the right permissions\n const deployRoleName = `Role for CI push of block '${blockId}'`;\n const deplyRoleDescription = `Created by the Contensis CLI for use in continuous integration`;\n let existingDeployRole = findByIdOrName(\n roles || [],\n deployRoleName,\n true\n ) as Role | undefined;\n existingDeployRole = await this.CreateOrUpdateRole(\n existingDeployRole,\n deployKeyRole(deployRoleName, deplyRoleDescription)\n );\n\n checkpoint('deploy key role assigned');\n log.success(\n messages.devinit.createDeployKey(deployRoleName, deployKeyExisted)\n );\n checkpoint('api keys done');\n }\n\n const envFilePath = `${projectHome}/.env`;\n const existingEnvFile = readFile(envFilePath);\n let existingEnvFileArray = (existingEnvFile || '')\n .split('\\n')\n .filter(l => !!l);\n\n // Update or create a file called .env in project home\n const envContentsToAdd: EnvContentsToAdd = {\n ALIAS: currentEnv,\n PROJECT_API_ID: currentProject,\n BLOCK_ID: blockId,\n };\n if (accessToken) envContentsToAdd['ACCESS_TOKEN'] = accessToken;\n // add client id and secret to the env file\n if (loc === 'env') {\n envContentsToAdd['CONTENSIS_CLIENT_ID'] = existingDevKey?.id;\n envContentsToAdd['CONTENSIS_CLIENT_SECRET'] =\n existingDevKey?.sharedSecret;\n }\n\n // if we have client id / secret in our env remove it\n const removeEnvItems = (items: string[]) => {\n const indexesToRemove = [];\n\n for (let i = 0; i < existingEnvFileArray.length; i++) {\n for (const item of items) {\n if (existingEnvFileArray[i].includes(item)) {\n indexesToRemove.push(i);\n break;\n }\n }\n }\n\n for (let i = indexesToRemove.length - 1; i >= 0; i--) {\n existingEnvFileArray.splice(indexesToRemove[i], 1);\n }\n };\n\n // remove client id and secret from env file\n if (loc === 'git') {\n removeEnvItems(['CONTENSIS_CLIENT_ID', 'CONTENSIS_CLIENT_SECRET']);\n }\n\n const envFileLines = mergeDotEnvFileContents(\n existingEnvFileArray,\n envContentsToAdd\n );\n const newEnvFileContent = envFileLines.join('\\n');\n const envDiff = diffFileContent(existingEnvFile || '', newEnvFileContent);\n\n if (dryRun) {\n if (envDiff) {\n log.info(`Updating .env file ${winSlash(envFilePath)}:\\n${envDiff}`);\n log.raw('');\n }\n checkpoint('skip .env file update (dry-run)');\n } else {\n if (envDiff) log.info(`Updating .env file ${winSlash(envFilePath)}`);\n writeFile(envFilePath, envFileLines.join('\\n'));\n checkpoint('.env file updated');\n log.success(messages.devinit.writeEnvFile());\n // log.help(messages.devinit.useEnvFileTip());\n }\n\n // Update git ignore\n if (dryRun) {\n checkpoint('skip .gitignore file update (dry-run)');\n } else {\n mergeContentsToAddWithGitignore(`${projectHome}/.gitignore`, ['.env']);\n log.raw('');\n }\n\n // Update CI Workflow\n const mappedWorkflow = await mapCIWorkflowContent(this, loc);\n\n // Update CI file -- different for GH/GL\n if (mappedWorkflow?.diff) {\n log.info(\n `Updating ${winSlash(ciFileName)} file:\\n${mappedWorkflow.diff}`\n );\n }\n if (dryRun) {\n checkpoint('skip CI file update (dry-run)');\n //log.object(ciFileLines);\n } else {\n if (mappedWorkflow?.newWorkflow) {\n if (mappedWorkflow?.diff) {\n writeFile(git.ciFilePath, mappedWorkflow.newWorkflow);\n log.success(messages.devinit.writeCiFile(`./${ciFileName}`));\n log.info(\n messages.devinit.ciBlockTip(blockId, currentEnv, currentProject)\n );\n } else {\n log.info(messages.devinit.ciFileNoChanges(`./${ciFileName}`));\n }\n log.raw('');\n checkpoint('CI file updated');\n }\n }\n\n if (loc === 'git') {\n // Echo Deployment API key to console, ask user to add secrets to repo\n const dryRunKeyMessage = dryRun ? 'not created in dry-run' : undefined;\n log.warning(messages.devinit.addGitSecretsIntro());\n log.help(\n messages.devinit.addGitSecretsHelp(\n git,\n existingDeployKey?.id || dryRunKeyMessage,\n existingDeployKey?.sharedSecret || dryRunKeyMessage\n )\n );\n }\n\n if (dryRun) {\n log.success(messages.devinit.dryRun());\n log.help(messages.devinit.noChanges());\n } else {\n log.success(messages.devinit.success());\n log.help(messages.devinit.startProjectTip());\n // open the cms link -- if no classic token just return the cms url\n\n // go and fetch the classic token from auth service\n const classicToken = await this.auth?.ClassicToken();\n log.help(\n ansiEscapes.link(\n `Open Contensis`,\n `${this.urls?.cms}${\n classicToken ? `?SecurityToken=${classicToken}` : ''\n }`\n )\n );\n }\n }\n };\n\n ExecRequestHandler = async (blockIds: string[], overrideArgs?: string[]) => {\n // if no request handler exe\n // download it.\n\n // if update arg, redownload it\n\n const { log } = this;\n // const getPrefixOld = log.getPrefix;\n const exeHome = path.join(appRootDir, 'reqhan');\n const exe = 'Zengenti.Contensis.RequestHandler.LocalDevelopment';\n const exePath = path.join(exeHome, exe);\n const siteConfigPath = path.join(appRootDir, 'site_config.yaml');\n\n const siteConfig = await mapSiteConfigYaml(this);\n writeFile('site_config.yaml', stringifyYaml(siteConfig));\n\n const args = overrideArgs\n ? typeof overrideArgs?.[0] === 'string' &&\n overrideArgs[0].includes(' ', 2)\n ? overrideArgs[0].split(' ')\n : overrideArgs\n : []; // args could be [ '-c .\\\\site_config.yaml' ] or [ '-c', '.\\\\site_config.yaml' ]\n\n // Add required args\n if (!args.find(a => a === '-c')) args.push('-c', siteConfigPath);\n\n // const child = execFile(exePath, args);\n\n const child = spawn(exePath, args, { stdio: 'inherit' });\n\n // log.raw('');\n log.info(`Launching request handler...`);\n if (overrideArgs?.length)\n this.log.warning(\n `Spawning process with supplied args: ${JSON.stringify(\n child.spawnargs,\n null,\n 2\n )}`\n );\n\n let isRunning = false;\n\n // Log child output through event listeners\n child?.stdout?.on('data', data => {\n isRunning = true;\n log.raw(data);\n });\n\n child?.stderr?.on('data', data => {\n log.error(data);\n });\n\n child.on('spawn', () => {\n isRunning = true;\n log.help(\n `You may see a firewall popup requesting network access, it is safe to approve`\n );\n // log.getPrefix = () => Logger.infoText(`[rqh]`);\n });\n\n child.on('exit', code => {\n isRunning = false;\n\n log[code === 0 ? 'success' : 'warning'](\n `Request handler exited with code ${code}\\n`\n );\n });\n\n child.on('error', error => {\n isRunning = false;\n log.error(`Could not launch request handler due to error \\n${error}`);\n });\n\n await new Promise(resolve => setTimeout(resolve, 2000));\n\n // keep the method running until we can return\n while (true === true) {\n if (!isRunning) {\n // log.getPrefix = getPrefixOld; // restore logger state\n return;\n }\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n };\n}\nexport const devCommand = (\n commandArgs: string[],\n outputOpts: OutputOptionsConstructorArg,\n contensisOpts: Partial<MigrateRequest> = {}\n) => {\n return new ContensisDev(['', '', ...commandArgs], outputOpts, contensisOpts);\n};\n\nexport default ContensisDev;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAe;AACf,2BAAsB;AACtB,sBAAqB;AACrB,kBAAiB;AAKjB,kCAA0B;AAG1B,wDAAkC;AAClC,mCAAqC;AACrC,wCAA8B;AAC9B,2BAAgD;AAChD,kBAAgC;AAChC,oBAAwC;AACxC,kBAA+B;AAC/B,iBAA0B;AAC1B,kBAA8B;AAC9B,gBAAyB;AACzB,kBAA8B;AAC9B,yBAA8B;AAC9B,uBAAgD;AAEhD,0BAAwB;AAExB,MAAM,qBAAqB,4BAAAA,QAAc;AAAA,EACvC;AAAA,EACA;AAAA,EAEA,oBAAoB;AAAA,IAClB,UAAU;AAAA,IACV,cAAc;AAAA,EAChB;AAAA,EAEA,YACE,MACA,YACA,gBAAyC,CAAC,GAC1C;AACA,UAAM,MAAM,YAAY,aAAa;AAAA,EACvC;AAAA,EAEA,kBAAkB,OAAO,aAAqB,SAAc;AA5C9D;AA8CI,UAAM,MAAO,KAAK,MAAM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AACH,SAAO,IAAI,aAAa,CAAC,IAAI,IAAI,GAAG,WAAW,GAAG,YAAY,aAAa;AAC7E;AAEA,IAAO,8BAAQ;",
|
|
6
|
+
"names": ["ContensisRole", "blockId", "inquirer", "to", "ansiEscapes", "path"]
|
|
7
7
|
}
|
package/dist/shell.js
CHANGED
|
@@ -157,6 +157,7 @@ class ContensisShell {
|
|
|
157
157
|
"execute block action makelive",
|
|
158
158
|
"execute block action rollback",
|
|
159
159
|
"execute block action markasbroken",
|
|
160
|
+
"get assets",
|
|
160
161
|
"get block",
|
|
161
162
|
"get block logs",
|
|
162
163
|
"get contenttype",
|
|
@@ -169,10 +170,12 @@ class ContensisShell {
|
|
|
169
170
|
"get token",
|
|
170
171
|
"get version",
|
|
171
172
|
"get webhook",
|
|
173
|
+
"get workflow",
|
|
172
174
|
"import contenttypes",
|
|
173
175
|
"import components",
|
|
174
176
|
"import entries",
|
|
175
177
|
"import models",
|
|
178
|
+
"import nodes",
|
|
176
179
|
"list blocks",
|
|
177
180
|
"list contenttypes",
|
|
178
181
|
"list components",
|
|
@@ -182,11 +185,13 @@ class ContensisShell {
|
|
|
182
185
|
"list renderers",
|
|
183
186
|
"list roles",
|
|
184
187
|
"list webhooks",
|
|
188
|
+
"list workflows",
|
|
185
189
|
"push block",
|
|
186
190
|
"remove components",
|
|
187
191
|
"remove contenttypes",
|
|
188
192
|
"remove key",
|
|
189
193
|
"remove entries",
|
|
194
|
+
"remove nodes",
|
|
190
195
|
"remove role",
|
|
191
196
|
"set project name",
|
|
192
197
|
"set project description",
|
package/dist/shell.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/shell.ts"],
|
|
4
|
-
"sourcesContent": ["import figlet from 'figlet';\nimport inquirer from 'inquirer';\nimport inquirerPrompt from 'inquirer-command-prompt';\nimport commands from './commands';\nimport { LogMessages } from './localisation/en-GB';\nimport CredentialProvider from './providers/CredentialProvider';\nimport { appRootDir } from './providers/file-provider';\nimport ContensisCli, { cliCommand } from './services/ContensisCliService';\nimport { Logging } from './util';\nimport { logError, Logger } from './util/logger';\nimport { LIB_VERSION } from './version';\n\nclass ContensisShell {\n private currentEnvironment!: string;\n private emptyInputCounter: number = 0;\n private env!: EnvironmentCache;\n private firstStart = true;\n private userId: string = '';\n private log = Logger;\n private messages = LogMessages;\n\n private refreshEnvironment = () => {\n // Reload any persisted changes from the disk cache\n const {\n cache: { currentEnvironment = '', environments = {} },\n } = new ContensisCli([]);\n // console.log(`refreshing env w/${currentEnvironment}`);\n this.currentEnvironment = currentEnvironment;\n this.env = environments[currentEnvironment];\n\n // Reload logging here to support changing language\n Logging('en-GB').then(({ messages, Log }) => {\n this.log = Log;\n this.messages = messages;\n });\n };\n\n constructor() {\n this.refreshEnvironment();\n inquirerPrompt.setConfig({\n history: {\n save: true,\n folder: appRootDir,\n limit: 100,\n blacklist: ['quit'],\n },\n });\n\n const { log, messages } = this;\n\n figlet.text(\n messages.app.contensis(),\n {\n font: 'Block',\n horizontalLayout: 'default',\n verticalLayout: 'default',\n width: process.stdout.columns,\n whitespaceBreak: true,\n },\n (err, data) => {\n if (err) {\n log.error(messages.app.unknownError());\n console.dir(err);\n return;\n }\n console.log(log.successText(data));\n console.log(log.infoText(messages.app.startup(LIB_VERSION)));\n console.log(log.helpText(messages.app.help()));\n\n this.start().catch(ex => log.error(ex));\n }\n );\n }\n\n restart = async () => {\n this.firstStart = false;\n this.log.line(); // add a line so we can see where the shell has been restarted\n await this.start();\n };\n\n start = async () => {\n this.refreshEnvironment();\n this.userId = '';\n const { currentEnvironment, env, log, messages } = this;\n\n if (env?.lastUserId) {\n const [credsErr, credentials] = await new CredentialProvider(\n {\n userId: env.lastUserId,\n alias: currentEnvironment,\n },\n env.passwordFallback\n ).Init();\n if (credsErr && !credentials.current) {\n log.error(credsErr.message);\n }\n if (credentials.current) {\n if (this.firstStart) {\n const token = await cliCommand(['login', env.lastUserId]).Login(\n env.lastUserId,\n {\n promptPassword: false,\n silent: true,\n }\n );\n if (token) {\n this.userId = env.lastUserId;\n if (!env.currentProject) log.warning(messages.projects.tip());\n }\n this.firstStart = false;\n this.refreshEnvironment();\n } else {\n this.userId = env.lastUserId;\n }\n }\n }\n await this.contensisPrompt();\n };\n\n contensisPrompt = async (): Promise<any> => {\n const { currentEnvironment, env, log, messages, userId } = this;\n\n const availableCommands = [\n {\n filter: (str: string) => {\n return str.replace(/ \\[.*$/, '');\n },\n },\n 'connect',\n 'list envs',\n 'quit',\n ];\n\n if (currentEnvironment)\n availableCommands.push('login', 'list projects', 'set project');\n if (userId)\n availableCommands.push(\n 'create key',\n 'create project',\n 'create role',\n 'diff models',\n 'execute block action release',\n 'execute block action makelive',\n 'execute block action rollback',\n 'execute block action markasbroken',\n 'get block',\n 'get block logs',\n 'get contenttype',\n 'get component',\n 'get entries',\n 'get nodes',\n 'get model',\n 'get project',\n 'get role',\n 'get token',\n 'get version',\n 'get webhook',\n 'import contenttypes',\n 'import components',\n 'import entries',\n 'import models',\n 'list blocks',\n 'list contenttypes',\n 'list components',\n 'list keys',\n 'list models',\n 'list proxies',\n 'list renderers',\n 'list roles',\n 'list webhooks',\n 'push block',\n 'remove components',\n 'remove contenttypes',\n 'remove key',\n 'remove entries',\n 'remove role',\n 'set project name',\n 'set project description',\n 'set role name',\n 'set role description',\n 'set role assignments',\n 'set role enabled',\n 'set role permissions'\n );\n\n const prompt = inquirer.createPromptModule();\n prompt.registerPrompt('command', inquirerPrompt);\n return prompt([\n {\n type: 'command',\n name: 'cmd',\n autoCompletion: availableCommands.sort(),\n autocompletePrompt: log.infoText(messages.app.autocomplete()),\n message: `${userId ? `${userId}@` : ''}${currentEnvironment || ''}>`,\n context: 0,\n validate: (val: string) => {\n if (!val) this.emptyInputCounter++;\n if (this.emptyInputCounter > 1)\n console.log(this.log.infoText(this.messages.app.suggestions()));\n if (val) {\n this.emptyInputCounter = 0;\n return true;\n }\n },\n prefix: `${env?.currentProject || log.infoText('contensis')}`,\n short: true,\n },\n ])\n .then(async (answers: { cmd: string }) => {\n if (answers.cmd === 'quit') {\n this.quit();\n } else {\n try {\n if (answers.cmd) {\n const program = commands();\n await program.parseAsync(\n answers.cmd\n .match(/\"[^\"]+\"|[^\\s]+/g)\n ?.map(e => e.replace(/\"(.+)\"/, '$1')),\n {\n from: 'user',\n }\n );\n }\n } catch (ex: any) {\n const str = ex.toString();\n if (!str.includes('CommanderError'))\n logError(\n ex,\n `Shell ${\n ex instanceof Error\n ? ex.toString()\n : JSON.stringify(ex, null, 2)\n }`\n );\n } finally {\n return this.contensisPrompt();\n }\n }\n })\n .catch((err: Error) => {\n log.error(err.message);\n this.quit();\n });\n };\n\n quit = (error?: Error) => {\n const { log, messages } = this;\n process.removeAllListeners('exit');\n\n if (error) {\n log.error(error.message);\n process.exit(1);\n } else {\n log.success(messages.app.quit());\n process.exitCode = 0;\n process.exit(0);\n }\n };\n}\n\nlet globalShell: ContensisShell;\n\nexport const shell = () => {\n // Return a benign function for shell().restart() when used in cli context\n // as some commands need to restart the shell to show an updated prompt\n // after successful connect / login / set project\n if (typeof process.argv?.[2] !== 'undefined')\n return {\n quit: ContensisCli.quit,\n restart() {},\n } as any;\n if (!globalShell) globalShell = new ContensisShell();\n return globalShell;\n};\n\nprocess.on('uncaughtException', function (err) {\n // Handle the error safely\n console.log(err);\n});\n\nprocess.on('SIGINT', () => {\n Logger.warning('received SIGINT');\n shell().quit();\n // setTimeout(() => {\n // }, 2000);\n});\n\nprocess.on('SIGTERM', () => {\n Logger.warning('received SIGTERM');\n shell().quit();\n});\n\nprocess.stdin.on('data', key => {\n if ((key as any) == '\\u0003') {\n console.log('');\n Logger.info(`[CTRL]+[C] detected, exiting shell...`);\n shell().quit();\n }\n});\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAmB;AACnB,sBAAqB;AACrB,qCAA2B;AAC3B,sBAAqB;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,mBAAO;AAAA,UACT;AAAA,QACF;AAAA,QACA,QAAQ,IAAG,2BAAK,mBAAkB,IAAI,SAAS,WAAW;AAAA,QAC1D,OAAO;AAAA,MACT;AAAA,IACF,CAAC,EACE,KAAK,OAAO,YAA6B;
|
|
4
|
+
"sourcesContent": ["import figlet from 'figlet';\nimport inquirer from 'inquirer';\nimport inquirerPrompt from 'inquirer-command-prompt';\nimport commands from './commands';\nimport { LogMessages } from './localisation/en-GB';\nimport CredentialProvider from './providers/CredentialProvider';\nimport { appRootDir } from './providers/file-provider';\nimport ContensisCli, { cliCommand } from './services/ContensisCliService';\nimport { Logging } from './util';\nimport { logError, Logger } from './util/logger';\nimport { LIB_VERSION } from './version';\n\nclass ContensisShell {\n private currentEnvironment!: string;\n private emptyInputCounter: number = 0;\n private env!: EnvironmentCache;\n private firstStart = true;\n private userId: string = '';\n private log = Logger;\n private messages = LogMessages;\n\n private refreshEnvironment = () => {\n // Reload any persisted changes from the disk cache\n const {\n cache: { currentEnvironment = '', environments = {} },\n } = new ContensisCli([]);\n // console.log(`refreshing env w/${currentEnvironment}`);\n this.currentEnvironment = currentEnvironment;\n this.env = environments[currentEnvironment];\n\n // Reload logging here to support changing language\n Logging('en-GB').then(({ messages, Log }) => {\n this.log = Log;\n this.messages = messages;\n });\n };\n\n constructor() {\n this.refreshEnvironment();\n inquirerPrompt.setConfig({\n history: {\n save: true,\n folder: appRootDir,\n limit: 100,\n blacklist: ['quit'],\n },\n });\n\n const { log, messages } = this;\n\n figlet.text(\n messages.app.contensis(),\n {\n font: 'Block',\n horizontalLayout: 'default',\n verticalLayout: 'default',\n width: process.stdout.columns,\n whitespaceBreak: true,\n },\n (err, data) => {\n if (err) {\n log.error(messages.app.unknownError());\n console.dir(err);\n return;\n }\n console.log(log.successText(data));\n console.log(log.infoText(messages.app.startup(LIB_VERSION)));\n console.log(log.helpText(messages.app.help()));\n\n this.start().catch(ex => log.error(ex));\n }\n );\n }\n\n restart = async () => {\n this.firstStart = false;\n this.log.line(); // add a line so we can see where the shell has been restarted\n await this.start();\n };\n\n start = async () => {\n this.refreshEnvironment();\n this.userId = '';\n const { currentEnvironment, env, log, messages } = this;\n\n if (env?.lastUserId) {\n const [credsErr, credentials] = await new CredentialProvider(\n {\n userId: env.lastUserId,\n alias: currentEnvironment,\n },\n env.passwordFallback\n ).Init();\n if (credsErr && !credentials.current) {\n log.error(credsErr.message);\n }\n if (credentials.current) {\n if (this.firstStart) {\n const token = await cliCommand(['login', env.lastUserId]).Login(\n env.lastUserId,\n {\n promptPassword: false,\n silent: true,\n }\n );\n if (token) {\n this.userId = env.lastUserId;\n if (!env.currentProject) log.warning(messages.projects.tip());\n }\n this.firstStart = false;\n this.refreshEnvironment();\n } else {\n this.userId = env.lastUserId;\n }\n }\n }\n await this.contensisPrompt();\n };\n\n contensisPrompt = async (): Promise<any> => {\n const { currentEnvironment, env, log, messages, userId } = this;\n\n const availableCommands = [\n {\n filter: (str: string) => {\n return str.replace(/ \\[.*$/, '');\n },\n },\n 'connect',\n 'list envs',\n 'quit',\n ];\n\n if (currentEnvironment)\n availableCommands.push('login', 'list projects', 'set project');\n if (userId)\n availableCommands.push(\n 'create key',\n 'create project',\n 'create role',\n 'diff models',\n 'execute block action release',\n 'execute block action makelive',\n 'execute block action rollback',\n 'execute block action markasbroken',\n 'get assets',\n 'get block',\n 'get block logs',\n 'get contenttype',\n 'get component',\n 'get entries',\n 'get nodes',\n 'get model',\n 'get project',\n 'get role',\n 'get token',\n 'get version',\n 'get webhook',\n 'get workflow',\n 'import contenttypes',\n 'import components',\n 'import entries',\n 'import models',\n 'import nodes',\n 'list blocks',\n 'list contenttypes',\n 'list components',\n 'list keys',\n 'list models',\n 'list proxies',\n 'list renderers',\n 'list roles',\n 'list webhooks',\n 'list workflows',\n 'push block',\n 'remove components',\n 'remove contenttypes',\n 'remove key',\n 'remove entries',\n 'remove nodes',\n 'remove role',\n 'set project name',\n 'set project description',\n 'set role name',\n 'set role description',\n 'set role assignments',\n 'set role enabled',\n 'set role permissions'\n );\n\n const prompt = inquirer.createPromptModule();\n prompt.registerPrompt('command', inquirerPrompt);\n return prompt([\n {\n type: 'command',\n name: 'cmd',\n autoCompletion: availableCommands.sort(),\n autocompletePrompt: log.infoText(messages.app.autocomplete()),\n message: `${userId ? `${userId}@` : ''}${currentEnvironment || ''}>`,\n context: 0,\n validate: (val: string) => {\n if (!val) this.emptyInputCounter++;\n if (this.emptyInputCounter > 1)\n console.log(this.log.infoText(this.messages.app.suggestions()));\n if (val) {\n this.emptyInputCounter = 0;\n return true;\n }\n },\n prefix: `${env?.currentProject || log.infoText('contensis')}`,\n short: true,\n },\n ])\n .then(async (answers: { cmd: string }) => {\n if (answers.cmd === 'quit') {\n this.quit();\n } else {\n try {\n if (answers.cmd) {\n const program = commands();\n await program.parseAsync(\n answers.cmd\n .match(/\"[^\"]+\"|[^\\s]+/g)\n ?.map(e => e.replace(/\"(.+)\"/, '$1')),\n {\n from: 'user',\n }\n );\n }\n } catch (ex: any) {\n const str = ex.toString();\n if (!str.includes('CommanderError'))\n logError(\n ex,\n `Shell ${\n ex instanceof Error\n ? ex.toString()\n : JSON.stringify(ex, null, 2)\n }`\n );\n } finally {\n return this.contensisPrompt();\n }\n }\n })\n .catch((err: Error) => {\n log.error(err.message);\n this.quit();\n });\n };\n\n quit = (error?: Error) => {\n const { log, messages } = this;\n process.removeAllListeners('exit');\n\n if (error) {\n log.error(error.message);\n process.exit(1);\n } else {\n log.success(messages.app.quit());\n process.exitCode = 0;\n process.exit(0);\n }\n };\n}\n\nlet globalShell: ContensisShell;\n\nexport const shell = () => {\n // Return a benign function for shell().restart() when used in cli context\n // as some commands need to restart the shell to show an updated prompt\n // after successful connect / login / set project\n if (typeof process.argv?.[2] !== 'undefined')\n return {\n quit: ContensisCli.quit,\n restart() {},\n } as any;\n if (!globalShell) globalShell = new ContensisShell();\n return globalShell;\n};\n\nprocess.on('uncaughtException', function (err) {\n // Handle the error safely\n console.log(err);\n});\n\nprocess.on('SIGINT', () => {\n Logger.warning('received SIGINT');\n shell().quit();\n // setTimeout(() => {\n // }, 2000);\n});\n\nprocess.on('SIGTERM', () => {\n Logger.warning('received SIGTERM');\n shell().quit();\n});\n\nprocess.stdin.on('data', key => {\n if ((key as any) == '\\u0003') {\n console.log('');\n Logger.info(`[CTRL]+[C] detected, exiting shell...`);\n shell().quit();\n }\n});\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAmB;AACnB,sBAAqB;AACrB,qCAA2B;AAC3B,sBAAqB;AACrB,mBAA4B;AAC5B,gCAA+B;AAC/B,2BAA2B;AAC3B,iCAAyC;AACzC,kBAAwB;AACxB,oBAAiC;AACjC,qBAA4B;AAE5B,MAAM,eAAe;AAAA,EACX;AAAA,EACA,oBAA4B;AAAA,EAC5B;AAAA,EACA,aAAa;AAAA,EACb,SAAiB;AAAA,EACjB,MAAM;AAAA,EACN,WAAW;AAAA,EAEX,qBAAqB,MAAM;AAEjC,UAAM;AAAA,MACJ,OAAO,EAAE,qBAAqB,IAAI,eAAe,CAAC,EAAE;AAAA,IACtD,IAAI,IAAI,2BAAAA,QAAa,CAAC,CAAC;AAEvB,SAAK,qBAAqB;AAC1B,SAAK,MAAM,aAAa;AAGxB,6BAAQ,OAAO,EAAE,KAAK,CAAC,EAAE,UAAU,IAAI,MAAM;AAC3C,WAAK,MAAM;AACX,WAAK,WAAW;AAAA,IAClB,CAAC;AAAA,EACH;AAAA,EAEA,cAAc;AACZ,SAAK,mBAAmB;AACxB,mCAAAC,QAAe,UAAU;AAAA,MACvB,SAAS;AAAA,QACP,MAAM;AAAA,QACN,QAAQ;AAAA,QACR,OAAO;AAAA,QACP,WAAW,CAAC,MAAM;AAAA,MACpB;AAAA,IACF,CAAC;AAED,UAAM,EAAE,KAAK,SAAS,IAAI;AAE1B,kBAAAC,QAAO;AAAA,MACL,SAAS,IAAI,UAAU;AAAA,MACvB;AAAA,QACE,M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OAAO;AACrB,WAAK,KAAK;AAAA,IACZ,CAAC;AAAA,EACL;AAAA,EAEA,OAAO,CAAC,UAAkB;AACxB,UAAM,EAAE,KAAK,SAAS,IAAI;AAC1B,YAAQ,mBAAmB,MAAM;AAEjC,QAAI,OAAO;AACT,UAAI,MAAM,MAAM,OAAO;AACvB,cAAQ,KAAK,CAAC;AAAA,IAChB,OAAO;AACL,UAAI,QAAQ,SAAS,IAAI,KAAK,CAAC;AAC/B,cAAQ,WAAW;AACnB,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF;AAEA,IAAI;AAEG,MAAM,QAAQ,MAAM;AA5Q3B;AAgRE,MAAI,SAAO,aAAQ,SAAR,mBAAe,QAAO;AAC/B,WAAO;AAAA,MACL,MAAM,2BAAAL,QAAa;AAAA,MACnB,UAAU;AAAA,MAAC;AAAA,IACb;AACF,MAAI,CAAC;AAAa,kBAAc,IAAI,eAAe;AACnD,SAAO;AACT;AAEA,QAAQ,GAAG,qBAAqB,SAAU,KAAK;AAE7C,UAAQ,IAAI,GAAG;AACjB,CAAC;AAED,QAAQ,GAAG,UAAU,MAAM;AACzB,uBAAO,QAAQ,iBAAiB;AAChC,QAAM,EAAE,KAAK;AAGf,CAAC;AAED,QAAQ,GAAG,WAAW,MAAM;AAC1B,uBAAO,QAAQ,kBAAkB;AACjC,QAAM,EAAE,KAAK;AACf,CAAC;AAED,QAAQ,MAAM,GAAG,QAAQ,SAAO;AAC9B,MAAK,OAAe,KAAU;AAC5B,YAAQ,IAAI,EAAE;AACd,yBAAO,KAAK,uCAAuC;AACnD,UAAM,EAAE,KAAK;AAAA,EACf;AACF,CAAC;",
|
|
6
6
|
"names": ["ContensisCli", "inquirerPrompt", "figlet", "CredentialProvider", "inquirer", "commands"]
|
|
7
7
|
}
|
|
@@ -25,12 +25,15 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
25
25
|
var console_printer_exports = {};
|
|
26
26
|
__export(console_printer_exports, {
|
|
27
27
|
printBlockVersion: () => printBlockVersion,
|
|
28
|
-
|
|
28
|
+
printEntriesMigrateResult: () => printEntriesMigrateResult,
|
|
29
29
|
printModelMigrationAnalysis: () => printModelMigrationAnalysis,
|
|
30
|
-
printModelMigrationResult: () => printModelMigrationResult
|
|
30
|
+
printModelMigrationResult: () => printModelMigrationResult,
|
|
31
|
+
printNodeTreeOutput: () => printNodeTreeOutput,
|
|
32
|
+
printNodesMigrateResult: () => printNodesMigrateResult
|
|
31
33
|
});
|
|
32
34
|
module.exports = __toCommonJS(console_printer_exports);
|
|
33
35
|
var import_dayjs = __toESM(require("dayjs"));
|
|
36
|
+
var import_error = require("./error");
|
|
34
37
|
var import_logger = require("./logger");
|
|
35
38
|
const formatDate = (date, format = "DD/MM/YYYY HH:mm") => (0, import_dayjs.default)(date).format(format);
|
|
36
39
|
const printBlockVersion = ({ log, messages }, block, printOptions = {
|
|
@@ -121,11 +124,11 @@ const printBlockVersion = ({ log, messages }, block, printOptions = {
|
|
|
121
124
|
console.log(` staging url: ${log.infoText(block.stagingUrl)}`);
|
|
122
125
|
console.log("");
|
|
123
126
|
};
|
|
124
|
-
const
|
|
127
|
+
const printEntriesMigrateResult = ({ log, messages, currentProject }, migrateResult, {
|
|
125
128
|
action = "import",
|
|
126
129
|
showDiff = false,
|
|
127
|
-
|
|
128
|
-
|
|
130
|
+
showAll = false,
|
|
131
|
+
showChanged = false
|
|
129
132
|
} = {}) => {
|
|
130
133
|
var _a, _b, _c;
|
|
131
134
|
console.log(``);
|
|
@@ -133,7 +136,7 @@ const printMigrateResult = ({ log, messages, currentProject }, migrateResult, {
|
|
|
133
136
|
migrateResult.entriesToMigrate.entryIds
|
|
134
137
|
)) {
|
|
135
138
|
for (const [originalId, entryStatus] of Object.entries(entryRes)) {
|
|
136
|
-
if (
|
|
139
|
+
if (showAll || showChanged && Object.entries(
|
|
137
140
|
Object.entries(entryStatus[currentProject])[0]
|
|
138
141
|
)[1][1].status !== "no change") {
|
|
139
142
|
console.log(
|
|
@@ -170,7 +173,7 @@ const printMigrateResult = ({ log, messages, currentProject }, migrateResult, {
|
|
|
170
173
|
}
|
|
171
174
|
}
|
|
172
175
|
}
|
|
173
|
-
if (
|
|
176
|
+
if (showAll || showChanged)
|
|
174
177
|
console.log(``);
|
|
175
178
|
for (const [projectId, contentTypeCounts] of Object.entries(
|
|
176
179
|
migrateResult.entries || {}
|
|
@@ -204,7 +207,48 @@ const printMigrateResult = ({ log, messages, currentProject }, migrateResult, {
|
|
|
204
207
|
`
|
|
205
208
|
);
|
|
206
209
|
for (const error of migrateResult.errors)
|
|
207
|
-
log.error(error.message
|
|
210
|
+
log.error(error.message, null, "");
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
const printNodesMigrateResult = ({ log, currentProject }, migrateResult, {
|
|
214
|
+
action = "import",
|
|
215
|
+
logLimit = 50,
|
|
216
|
+
showDiff = false,
|
|
217
|
+
showAll = false,
|
|
218
|
+
showChanged = false
|
|
219
|
+
} = {}) => {
|
|
220
|
+
var _a, _b, _c;
|
|
221
|
+
log.raw(``);
|
|
222
|
+
for (const [projectId, counts] of Object.entries(migrateResult.nodes || {})) {
|
|
223
|
+
const importTitle = action === "delete" ? `Delete from project ${log.warningText(currentProject)}` : `Import ${projectId && projectId !== "null" ? `from project ${log.highlightText(projectId)} ` : ""}to ${log.boldText(log.warningText(currentProject))}`;
|
|
224
|
+
log.help(importTitle);
|
|
225
|
+
const migrateStatusAndCount = migrateResult.nodesToMigrate[currentProject];
|
|
226
|
+
const existingCount = ((_b = (_a = migrateResult.existing) == null ? void 0 : _a[currentProject]) == null ? void 0 : _b.totalCount) || 0;
|
|
227
|
+
const totalCount = Object.keys(migrateResult.nodesToMigrate.nodeIds).length;
|
|
228
|
+
const existingPercent = counts.totalCount ? (existingCount / totalCount * 100).toFixed(0) : "0";
|
|
229
|
+
const noChangeCount = (migrateStatusAndCount == null ? void 0 : migrateStatusAndCount["no change"]) || 0;
|
|
230
|
+
const changedPercentage = counts.totalCount ? (noChangeCount / totalCount * 100).toFixed(0) : "0";
|
|
231
|
+
const existingColor = existingPercent === "0" || action === "delete" ? log.warningText : log.infoText;
|
|
232
|
+
const changedColor = changedPercentage === "100" ? log.successText : log.warningText;
|
|
233
|
+
console.log(
|
|
234
|
+
` - ${log.highlightText(
|
|
235
|
+
`totalCount: ${migrateStatusAndCount.totalCount}`
|
|
236
|
+
)}${changedPercentage === "100" ? "" : existingColor(` [existing: ${`${existingPercent}%`}]`)}${existingPercent === "0" ? "" : changedColor(
|
|
237
|
+
` ${changedPercentage === "100" ? "up to date" : `[needs update: ${100 - Number(changedPercentage)}%]`}`
|
|
238
|
+
)}`
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
if ((_c = migrateResult.errors) == null ? void 0 : _c.length) {
|
|
242
|
+
console.log(
|
|
243
|
+
` - ${log.errorText(`errors: ${migrateResult.errors.length}`)}
|
|
244
|
+
`
|
|
245
|
+
);
|
|
246
|
+
log.limits(
|
|
247
|
+
migrateResult.errors.map((error) => {
|
|
248
|
+
return log.errorText((0, import_error.deconstructApiError)(error));
|
|
249
|
+
}).join("\n"),
|
|
250
|
+
logLimit
|
|
251
|
+
);
|
|
208
252
|
}
|
|
209
253
|
};
|
|
210
254
|
const highlightDiffText = (str) => {
|
|
@@ -300,11 +344,68 @@ const printModelMigrationResult = ({ log, messages }, result) => {
|
|
|
300
344
|
}
|
|
301
345
|
}
|
|
302
346
|
};
|
|
347
|
+
const printNodeTreeOutput = ({ log, messages }, root, logDetail = "errors", logLimit = 1e3) => {
|
|
348
|
+
log.raw("");
|
|
349
|
+
const statusColour = messages.migrate.status;
|
|
350
|
+
if (root && "status" in root)
|
|
351
|
+
log.info(
|
|
352
|
+
`Migrate status: ${statusColour("no change")(
|
|
353
|
+
"N"
|
|
354
|
+
)} [no change]; ${statusColour("create")("C")} [create]; ${statusColour(
|
|
355
|
+
"update"
|
|
356
|
+
)("U")} [update]; ${statusColour("delete")("D")} [delete]; ${statusColour(
|
|
357
|
+
"error"
|
|
358
|
+
)("E")} [error];`
|
|
359
|
+
);
|
|
360
|
+
log.info(
|
|
361
|
+
`Node properties: ${log.highlightText(
|
|
362
|
+
"e"
|
|
363
|
+
)} = has entry; ${log.highlightText("c")} = canonical; ${log.highlightText(
|
|
364
|
+
"m"
|
|
365
|
+
)} = include in menu`
|
|
366
|
+
);
|
|
367
|
+
log.line();
|
|
368
|
+
const outputNode = (node, spaces, isRoot = false) => {
|
|
369
|
+
var _a, _b;
|
|
370
|
+
const errorOutput = "error" in node && node.error && (0, import_error.deconstructApiError)(node.error);
|
|
371
|
+
const fullOutput = logDetail === "all";
|
|
372
|
+
const changesOutput = logDetail === "changes" && "status" in node && ["create", "update"].includes(node.status);
|
|
373
|
+
const diffOutput = (fullOutput || changesOutput || errorOutput) && "diff" in node && ((_a = node.diff) == null ? void 0 : _a.replaceAll("\n", ""));
|
|
374
|
+
return `${"status" in node ? `${statusColour(node.status)(
|
|
375
|
+
node.status.substring(0, 1).toUpperCase()
|
|
376
|
+
)} ` : ""}${node.entry ? log.highlightText("e") : log.infoText("-")}${"isCanonical" in node && node.isCanonical ? log.highlightText("c") : log.infoText("-")}${node.includeInMenu ? log.highlightText("m") : log.infoText("-")}${spaces}${log["status" in node && node.status === "no change" ? "infoText" : "standardText"](
|
|
377
|
+
"isCanonical" in node && node.isCanonical ? log.boldText(fullOutput || isRoot ? node.path : `/${node.slug}`) : fullOutput || isRoot ? node.path : `/${node.slug}`
|
|
378
|
+
)}${node.entry ? ` ${log.helpText(node.entry.sys.contentTypeId)}` : ""}${node.childCount ? ` +${node.childCount}` : ``} ${"displayName" in node ? log.infoText(node.displayName) : ""}${fullOutput || changesOutput && node.id !== node.originalId ? `~n ${log.infoText(`id:`)} ${node.id === node.originalId ? node.id : `${node.id} ${log.infoText(`<= ${node.originalId}`)}`}` : ""}${(fullOutput || changesOutput && node.parentId !== node.originalParentId) && node.parentId ? `~n ${log.infoText(
|
|
379
|
+
`parentId: ${node.parentId === node.originalParentId ? node.parentId : `${node.parentId} <= ${node.originalParentId}`}`
|
|
380
|
+
)}` : ""}${fullOutput && ((_b = node.entry) == null ? void 0 : _b.sys.id) ? `~n ${log.infoText(`entryId: ${node.entry.sys.id}`)}` : ""}${errorOutput ? `~n${(0, import_logger.addNewLines)(` ${log.errorText(errorOutput)}`, "~n")}` : ""}${diffOutput ? `~n${(0, import_logger.addNewLines)(
|
|
381
|
+
` ${log.infoText(`diff: ${highlightDiffText(diffOutput)}`)}`,
|
|
382
|
+
"~n"
|
|
383
|
+
)}` : ""}`;
|
|
384
|
+
};
|
|
385
|
+
const outputChildren = (node, depth = 2) => {
|
|
386
|
+
let str = "";
|
|
387
|
+
for (const child of (node == null ? void 0 : node.children) || []) {
|
|
388
|
+
str += `${outputNode(child, Array(depth + 1).join(" "))}
|
|
389
|
+
`;
|
|
390
|
+
if ("children" in child)
|
|
391
|
+
str += outputChildren(child, depth + 1);
|
|
392
|
+
}
|
|
393
|
+
return str;
|
|
394
|
+
};
|
|
395
|
+
const children = outputChildren(root);
|
|
396
|
+
log.limits(
|
|
397
|
+
`${outputNode(root || {}, " ", true)}${children ? `
|
|
398
|
+
${children}` : ""}`,
|
|
399
|
+
logLimit
|
|
400
|
+
);
|
|
401
|
+
};
|
|
303
402
|
// Annotate the CommonJS export names for ESM import in node:
|
|
304
403
|
0 && (module.exports = {
|
|
305
404
|
printBlockVersion,
|
|
306
|
-
|
|
405
|
+
printEntriesMigrateResult,
|
|
307
406
|
printModelMigrationAnalysis,
|
|
308
|
-
printModelMigrationResult
|
|
407
|
+
printModelMigrationResult,
|
|
408
|
+
printNodeTreeOutput,
|
|
409
|
+
printNodesMigrateResult
|
|
309
410
|
});
|
|
310
411
|
//# sourceMappingURL=console.printer.js.map
|