contensis-cli 1.0.11 → 1.0.12-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mappers/DevInit-to-CIWorkflow.js +44 -25
- package/dist/mappers/DevInit-to-CIWorkflow.js.map +2 -2
- package/dist/services/ContensisAuthService.js +14 -8
- package/dist/services/ContensisAuthService.js.map +2 -2
- package/dist/services/ContensisCliService.js +8 -5
- package/dist/services/ContensisCliService.js.map +2 -2
- package/dist/services/ContensisDevService.js +39 -22
- package/dist/services/ContensisDevService.js.map +3 -3
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +1 -1
- package/src/mappers/DevInit-to-CIWorkflow.ts +51 -39
- package/src/services/ContensisAuthService.ts +15 -8
- package/src/services/ContensisCliService.ts +20 -5
- package/src/services/ContensisDevService.ts +52 -29
- package/src/version.ts +1 -1
|
@@ -46,6 +46,8 @@ 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
|
+
var import_ansi_escapes = __toESM(require("ansi-escapes"));
|
|
49
51
|
class ContensisDev extends import_ContensisRoleService.default {
|
|
50
52
|
git;
|
|
51
53
|
blockId;
|
|
@@ -53,6 +55,7 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
53
55
|
super(args, outputOpts, contensisOpts);
|
|
54
56
|
}
|
|
55
57
|
DevelopmentInit = async (projectHome, opts) => {
|
|
58
|
+
var _a, _b;
|
|
56
59
|
const git = this.git = new import_git.GitHelper(projectHome);
|
|
57
60
|
const isRepo = git.checkIsRepo();
|
|
58
61
|
if (!isRepo)
|
|
@@ -61,6 +64,7 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
61
64
|
const { currentEnv, currentProject, log, messages } = this;
|
|
62
65
|
const contensis = await this.ConnectContensis();
|
|
63
66
|
if (contensis) {
|
|
67
|
+
this.devinit = { ...this.devinit, invokedBy: this.invokedBy };
|
|
64
68
|
const validateBlockId = (blockId2) => {
|
|
65
69
|
const pattern = /^[0-9a-z](-?[0-9a-z])*$/;
|
|
66
70
|
if (blockId2.length >= 1 && blockId2.length <= 225) {
|
|
@@ -112,9 +116,23 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
112
116
|
log.success("Successfully created deploy key");
|
|
113
117
|
}
|
|
114
118
|
if (existingDeployKey) {
|
|
115
|
-
this.
|
|
116
|
-
|
|
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
|
+
};
|
|
117
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();
|
|
118
136
|
const errors = [];
|
|
119
137
|
log.raw("");
|
|
120
138
|
log.success(messages.devinit.intro());
|
|
@@ -157,28 +175,24 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
157
175
|
}
|
|
158
176
|
log.raw(log.infoText(messages.devinit.ciDetails(ciFileName)));
|
|
159
177
|
let mappedWorkflow;
|
|
160
|
-
const {
|
|
161
|
-
name: "
|
|
178
|
+
const { loc } = await import_inquirer.default.prompt({
|
|
179
|
+
name: "loc",
|
|
162
180
|
type: "list",
|
|
163
181
|
prefix: "\u{1F511}",
|
|
164
182
|
message: messages.devinit.clientDetailsLocation(),
|
|
165
183
|
choices: [
|
|
166
|
-
|
|
167
|
-
|
|
184
|
+
{
|
|
185
|
+
name: messages.devinit.clientDetailsInGit(git),
|
|
186
|
+
value: "git"
|
|
187
|
+
},
|
|
188
|
+
{
|
|
189
|
+
name: messages.devinit.clientDetailsInEnv(),
|
|
190
|
+
value: "env"
|
|
191
|
+
}
|
|
168
192
|
]
|
|
169
193
|
});
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
} else {
|
|
173
|
-
this.clientDetailsLocation = "git";
|
|
174
|
-
}
|
|
175
|
-
if (this.clientDetailsLocation === "env") {
|
|
176
|
-
mappedWorkflow = await (0, import_DevInit_to_CIWorkflow.mapCIWorkflowContent)(this);
|
|
177
|
-
log.help(messages.devinit.ciIntro(git, "env"));
|
|
178
|
-
} else {
|
|
179
|
-
mappedWorkflow = await (0, import_DevInit_to_CIWorkflow.mapCIWorkflowContent)(this);
|
|
180
|
-
log.help(messages.devinit.ciIntro(git, "git"));
|
|
181
|
-
}
|
|
194
|
+
log.help(messages.devinit.ciIntro(git, loc));
|
|
195
|
+
mappedWorkflow = await (0, import_DevInit_to_CIWorkflow.mapCIWorkflowContent)(this, loc);
|
|
182
196
|
if (!dryRun) {
|
|
183
197
|
const { confirm } = await import_inquirer.default.prompt([
|
|
184
198
|
{
|
|
@@ -245,7 +259,7 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
245
259
|
};
|
|
246
260
|
if (accessToken)
|
|
247
261
|
envContentsToAdd["ACCESS_TOKEN"] = accessToken;
|
|
248
|
-
if (
|
|
262
|
+
if (loc === "env") {
|
|
249
263
|
envContentsToAdd["CONTENSIS_CLIENT_ID"] = existingDevKey == null ? void 0 : existingDevKey.id;
|
|
250
264
|
envContentsToAdd["CONTENSIS_CLIENT_SECRET"] = existingDevKey == null ? void 0 : existingDevKey.sharedSecret;
|
|
251
265
|
}
|
|
@@ -263,7 +277,7 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
263
277
|
existingEnvFileArray.splice(indexesToRemove[i], 1);
|
|
264
278
|
}
|
|
265
279
|
};
|
|
266
|
-
if (
|
|
280
|
+
if (loc === "git") {
|
|
267
281
|
removeEnvItems(["CONTENSIS_CLIENT_ID", "CONTENSIS_CLIENT_SECRET"]);
|
|
268
282
|
}
|
|
269
283
|
const envFileLines = (0, import_dotenv.mergeDotEnvFileContents)(
|
|
@@ -312,7 +326,7 @@ ${mappedWorkflow.diff}`
|
|
|
312
326
|
checkpoint("CI file updated");
|
|
313
327
|
}
|
|
314
328
|
}
|
|
315
|
-
if (
|
|
329
|
+
if (loc === "git") {
|
|
316
330
|
log.warning(messages.devinit.addGitSecretsIntro());
|
|
317
331
|
log.help(
|
|
318
332
|
messages.devinit.addGitSecretsHelp(
|
|
@@ -329,7 +343,10 @@ ${mappedWorkflow.diff}`
|
|
|
329
343
|
log.success(messages.devinit.success());
|
|
330
344
|
log.help(messages.devinit.startProjectTip());
|
|
331
345
|
log.help(
|
|
332
|
-
|
|
346
|
+
import_ansi_escapes.default.link(
|
|
347
|
+
`Open Contensis`,
|
|
348
|
+
`https://cms-${currentEnv}.cloud.contensis.com${classicToken ? `?SecurityToken=${classicToken}` : ""}`
|
|
349
|
+
)
|
|
333
350
|
);
|
|
334
351
|
}
|
|
335
352
|
}
|
|
@@ -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';\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 // 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.clientId = existingDeployKey?.id;\n this.clientSecret = existingDeployKey?.sharedSecret;\n }\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 { clientDetailsOption } = await inquirer.prompt({\n name: 'clientDetailsOption',\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 messages.devinit.clientDetailsInGit(git),\n messages.devinit.clientDetailsInEnv(),\n ],\n });\n\n // global 'clientDetailsLocation' variable stores users input on where client id / secert are stored\n if (clientDetailsOption === messages.devinit.clientDetailsInEnv()) {\n this.clientDetailsLocation = 'env';\n } else {\n this.clientDetailsLocation = 'git';\n }\n\n if (this.clientDetailsLocation === 'env') {\n // Update CI Workflow to pull from ENV variables\n mappedWorkflow = await mapCIWorkflowContent(this);\n log.help(messages.devinit.ciIntro(git, 'env'));\n } else {\n // Look at the workflow file content and make updates\n mappedWorkflow = await mapCIWorkflowContent(this);\n log.help(messages.devinit.ciIntro(git, 'git'));\n }\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 (this.clientDetailsLocation === '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 if (this.clientDetailsLocation === '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 (this.clientDetailsLocation === '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 CMS + TODO: Grab token to log user in.\n log.help(\n `Open Contensis \uD83D\uDC49 https://cms-${currentEnv}.cloud.contensis.com/`\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", "to", "path"]
|
|
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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AC3C,MAAM;AAAA,UACN;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAEF,QAAI,YAAY;AAGhB,yCAAO,WAAP,mBAAe,GAAG,QAAQ,UAAQ;AAChC,kBAAY;AACZ,UAAI,IAAI,IAAI;AAAA,IACd;AAEA,yCAAO,WAAP,mBAAe,GAAG,QAAQ,UAAQ;AAChC,UAAI,MAAM,IAAI;AAAA,IAChB;AAEA,UAAM,GAAG,SAAS,MAAM;AACtB,kBAAY;AACZ,UAAI;AAAA,QACF;AAAA,MACF;AAAA,IAEF,CAAC;AAED,UAAM,GAAG,QAAQ,UAAQ;AACvB,kBAAY;AAEZ,UAAI,SAAS,IAAI,YAAY;AAAA,QAC3B,oCAAoC;AAAA;AAAA,MACtC;AAAA,IACF,CAAC;AAED,UAAM,GAAG,SAAS,WAAS;AACzB,kBAAY;AACZ,UAAI,MAAM;AAAA,EAAmD,OAAO;AAAA,IACtE,CAAC;AAED,UAAM,IAAI,QAAQ,aAAW,WAAW,SAAS,GAAI,CAAC;AAGtD,WAAO,MAAe;AACpB,UAAI,CAAC,WAAW;AAEd;AAAA,MACF;AACA,YAAM,IAAI,QAAQ,aAAW,WAAW,SAAS,GAAI,CAAC;AAAA,IACxD;AAAA,EACF;AACF;AACO,MAAM,aAAa,CACxB,aACA,YACA,gBAAyC,CAAC,MACvC;AACH,SAAO,IAAI,aAAa,CAAC,IAAI,IAAI,GAAG,WAAW,GAAG,YAAY,aAAa;AAC7E;AAEA,IAAO,8BAAQ;",
|
|
6
|
+
"names": ["ContensisRole", "blockId", "inquirer", "ContensisAuthService", "to", "ansiEscapes", "path"]
|
|
7
7
|
}
|
package/dist/version.js
CHANGED
|
@@ -21,7 +21,7 @@ __export(version_exports, {
|
|
|
21
21
|
LIB_VERSION: () => LIB_VERSION
|
|
22
22
|
});
|
|
23
23
|
module.exports = __toCommonJS(version_exports);
|
|
24
|
-
const LIB_VERSION = "1.0.
|
|
24
|
+
const LIB_VERSION = "1.0.12-beta.1";
|
|
25
25
|
// Annotate the CommonJS export names for ESM import in node:
|
|
26
26
|
0 && (module.exports = {
|
|
27
27
|
LIB_VERSION
|
package/dist/version.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/version.ts"],
|
|
4
|
-
"sourcesContent": ["export const LIB_VERSION = \"1.0.
|
|
4
|
+
"sourcesContent": ["export const LIB_VERSION = \"1.0.12-beta.1\";\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,MAAM,cAAc;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "contensis-cli",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.12-beta.1",
|
|
4
4
|
"description": "A fully featured Contensis command line interface with a shell UI provides simple and intuitive ways to manage or profile your content in any NodeJS terminal.",
|
|
5
5
|
"repository": "https://github.com/contensis/node-cli",
|
|
6
6
|
"homepage": "https://github.com/contensis/node-cli/tree/main/packages/contensis-cli#readme",
|
|
@@ -20,7 +20,8 @@ type MappedWorkflowOutput = {
|
|
|
20
20
|
};
|
|
21
21
|
|
|
22
22
|
export const mapCIWorkflowContent = async (
|
|
23
|
-
cli: ContensisDev
|
|
23
|
+
cli: ContensisDev,
|
|
24
|
+
loc: 'git' | 'env'
|
|
24
25
|
): Promise<MappedWorkflowOutput | undefined> => {
|
|
25
26
|
// get existing workflow file
|
|
26
27
|
const workflowFile = readFile(cli.git.ciFilePath);
|
|
@@ -34,7 +35,8 @@ export const mapCIWorkflowContent = async (
|
|
|
34
35
|
const newWorkflow = await mapGitHubActionCIWorkflowContent(
|
|
35
36
|
cli,
|
|
36
37
|
workflowDoc,
|
|
37
|
-
workflowJS
|
|
38
|
+
workflowJS,
|
|
39
|
+
loc
|
|
38
40
|
);
|
|
39
41
|
return {
|
|
40
42
|
existingWorkflow: workflowFile,
|
|
@@ -45,7 +47,8 @@ export const mapCIWorkflowContent = async (
|
|
|
45
47
|
const newWorkflow = await mapGitLabCIWorkflowContent(
|
|
46
48
|
cli,
|
|
47
49
|
workflowDoc,
|
|
48
|
-
workflowJS
|
|
50
|
+
workflowJS,
|
|
51
|
+
loc
|
|
49
52
|
);
|
|
50
53
|
return {
|
|
51
54
|
existingWorkflow: workflowFile,
|
|
@@ -89,7 +92,8 @@ const setWorkflowElement = (
|
|
|
89
92
|
const mapGitLabCIWorkflowContent = async (
|
|
90
93
|
cli: ContensisDev,
|
|
91
94
|
workflowDoc: Document,
|
|
92
|
-
workflowJS: any
|
|
95
|
+
workflowJS: any,
|
|
96
|
+
loc: 'env' | 'git'
|
|
93
97
|
) => {
|
|
94
98
|
const addGitLabJobStage: GitLabPushBlockJobStage = {
|
|
95
99
|
stage: 'push-block',
|
|
@@ -98,16 +102,33 @@ const mapGitLabCIWorkflowContent = async (
|
|
|
98
102
|
alias: cli.currentEnv,
|
|
99
103
|
project_id: cli.currentProject,
|
|
100
104
|
client_id:
|
|
101
|
-
|
|
102
|
-
? cli.clientId
|
|
105
|
+
loc === 'env'
|
|
106
|
+
? cli.devinit?.credentials.clientId
|
|
103
107
|
: '$CONTENSIS_CLIENT_ID',
|
|
104
108
|
shared_secret:
|
|
105
|
-
|
|
106
|
-
? cli.clientSecret
|
|
109
|
+
loc === 'env'
|
|
110
|
+
? cli.devinit?.credentials.clientSecret
|
|
107
111
|
: '$CONTENSIS_SHARED_SECRET',
|
|
108
112
|
},
|
|
109
113
|
};
|
|
110
114
|
|
|
115
|
+
if (loc === 'git') {
|
|
116
|
+
// remove env vars from yml if we choose git
|
|
117
|
+
workflowDoc.deleteIn(findPath(`variables.CONTENSIS_CLIENT_ID`));
|
|
118
|
+
workflowDoc.deleteIn(findPath(`variables.CONTENSIS_SHARED_SECRET`));
|
|
119
|
+
} else {
|
|
120
|
+
setWorkflowElement(
|
|
121
|
+
workflowDoc,
|
|
122
|
+
`variables.CONTENSIS_CLIENT_ID`,
|
|
123
|
+
`${cli.devinit.credentials.clientId}`
|
|
124
|
+
);
|
|
125
|
+
setWorkflowElement(
|
|
126
|
+
workflowDoc,
|
|
127
|
+
`variables.CONTENSIS_CLIENT_SECRET`,
|
|
128
|
+
`${cli.devinit.credentials.clientSecret}`
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
111
132
|
const addAppImageUri = async () => {
|
|
112
133
|
// Look in document level "variables"
|
|
113
134
|
const appImageUri = await determineAppImageUri(
|
|
@@ -179,16 +200,12 @@ const mapGitLabCIWorkflowContent = async (
|
|
|
179
200
|
setWorkflowElement(
|
|
180
201
|
workflowDoc,
|
|
181
202
|
`${stepPath}.variables.client_id`,
|
|
182
|
-
|
|
183
|
-
? cli.clientId
|
|
184
|
-
: '$CONTENSIS_CLIENT_ID'
|
|
203
|
+
'$CONTENSIS_CLIENT_ID'
|
|
185
204
|
);
|
|
186
205
|
setWorkflowElement(
|
|
187
206
|
workflowDoc,
|
|
188
207
|
`${stepPath}.variables.shared_secret`,
|
|
189
|
-
|
|
190
|
-
? cli.clientSecret
|
|
191
|
-
: '$CONTENSIS_SHARED_SECRET'
|
|
208
|
+
'$CONTENSIS_SHARED_SECRET'
|
|
192
209
|
);
|
|
193
210
|
} else {
|
|
194
211
|
// create job with push step
|
|
@@ -212,17 +229,15 @@ const mapGitLabCIWorkflowContent = async (
|
|
|
212
229
|
|
|
213
230
|
cli.log.debug(`New file content to write\n\n${workflowDoc}`);
|
|
214
231
|
|
|
215
|
-
const newWorkflow =
|
|
216
|
-
workflowDoc.toString({ lineWidth: 0 })
|
|
217
|
-
);
|
|
218
|
-
|
|
232
|
+
const newWorkflow = workflowDoc.toString({ lineWidth: 0 });
|
|
219
233
|
return newWorkflow;
|
|
220
234
|
};
|
|
221
235
|
|
|
222
236
|
const mapGitHubActionCIWorkflowContent = async (
|
|
223
237
|
cli: ContensisDev,
|
|
224
238
|
workflowDoc: Document,
|
|
225
|
-
workflowJS: any
|
|
239
|
+
workflowJS: any,
|
|
240
|
+
loc: 'git' | 'env'
|
|
226
241
|
) => {
|
|
227
242
|
const addGitHubActionJobStep: GitHubActionPushBlockJobStep = {
|
|
228
243
|
name: 'Push block to Contensis',
|
|
@@ -234,11 +249,11 @@ const mapGitHubActionCIWorkflowContent = async (
|
|
|
234
249
|
alias: cli.currentEnv,
|
|
235
250
|
'project-id': cli.currentProject,
|
|
236
251
|
'client-id':
|
|
237
|
-
|
|
252
|
+
loc === 'env'
|
|
238
253
|
? '${{ env.CONTENSIS_CLIENT_ID }}'
|
|
239
254
|
: '${{ secrets.CONTENSIS_CLIENT_ID }}',
|
|
240
255
|
'shared-secret':
|
|
241
|
-
|
|
256
|
+
loc === 'env'
|
|
242
257
|
? '${{ env.CONTENSIS_SHARED_SECRET }}'
|
|
243
258
|
: '${{ secrets.CONTENSIS_SHARED_SECRET }}',
|
|
244
259
|
},
|
|
@@ -274,20 +289,22 @@ const mapGitHubActionCIWorkflowContent = async (
|
|
|
274
289
|
'all'
|
|
275
290
|
);
|
|
276
291
|
|
|
277
|
-
|
|
278
|
-
if (cli.clientDetailsLocation === 'env') {
|
|
279
|
-
setWorkflowElement(workflowDoc, `env.CONTENSIS_CLIENT_ID`, cli.clientId);
|
|
280
|
-
setWorkflowElement(
|
|
281
|
-
workflowDoc,
|
|
282
|
-
`env.CONTENSIS_SHARED_SECRET`,
|
|
283
|
-
cli.clientSecret
|
|
284
|
-
);
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
if (cli.clientDetailsLocation === 'git') {
|
|
292
|
+
if (loc === 'git') {
|
|
288
293
|
// remove env vars from yml if we choose git
|
|
289
294
|
workflowDoc.deleteIn(findPath(`env.CONTENSIS_CLIENT_ID`));
|
|
290
295
|
workflowDoc.deleteIn(findPath(`env.CONTENSIS_SHARED_SECRET`));
|
|
296
|
+
} else {
|
|
297
|
+
// update 'env' and store client id and secret
|
|
298
|
+
setWorkflowElement(
|
|
299
|
+
workflowDoc,
|
|
300
|
+
`env.CONTENSIS_CLIENT_ID`,
|
|
301
|
+
cli.devinit?.credentials.clientId
|
|
302
|
+
);
|
|
303
|
+
setWorkflowElement(
|
|
304
|
+
workflowDoc,
|
|
305
|
+
'env.CONTENSIS_SHARED_SECRET',
|
|
306
|
+
cli.devinit?.credentials.clientSecret
|
|
307
|
+
);
|
|
291
308
|
}
|
|
292
309
|
|
|
293
310
|
// update job step
|
|
@@ -326,14 +343,14 @@ const mapGitHubActionCIWorkflowContent = async (
|
|
|
326
343
|
setWorkflowElement(
|
|
327
344
|
workflowDoc,
|
|
328
345
|
`${stepPath}.with.client-id`,
|
|
329
|
-
|
|
346
|
+
loc === 'env'
|
|
330
347
|
? '${{ env.CONTENSIS_CLIENT_ID }}'
|
|
331
348
|
: '${{ secrets.CONTENSIS_CLIENT_ID }}'
|
|
332
349
|
);
|
|
333
350
|
setWorkflowElement(
|
|
334
351
|
workflowDoc,
|
|
335
352
|
`${stepPath}.with.shared-secret`,
|
|
336
|
-
|
|
353
|
+
loc === 'env'
|
|
337
354
|
? '${{ env.CONTENSIS_SHARED_SECRET }}'
|
|
338
355
|
: '${{ secrets.CONTENSIS_SHARED_SECRET }}'
|
|
339
356
|
);
|
|
@@ -437,12 +454,7 @@ const mapGitHubActionCIWorkflowContent = async (
|
|
|
437
454
|
);
|
|
438
455
|
}
|
|
439
456
|
|
|
440
|
-
// const newWorkflow = normaliseLineEndings(
|
|
441
|
-
// workflowDoc.toString({ lineWidth: 0 })
|
|
442
|
-
// );
|
|
443
|
-
|
|
444
457
|
const newWorkflow = workflowDoc.toString({ lineWidth: 0 });
|
|
445
|
-
|
|
446
458
|
return newWorkflow;
|
|
447
459
|
};
|
|
448
460
|
|
|
@@ -25,7 +25,15 @@ class ContensisAuthService {
|
|
|
25
25
|
clientType: ClientGrantType;
|
|
26
26
|
clientDetails: ClientGrants;
|
|
27
27
|
};
|
|
28
|
-
if (
|
|
28
|
+
if (clientId && clientSecret) {
|
|
29
|
+
credentials = {
|
|
30
|
+
clientType: 'client_credentials',
|
|
31
|
+
clientDetails: {
|
|
32
|
+
clientId,
|
|
33
|
+
clientSecret,
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
} else if (username && password) {
|
|
29
37
|
credentials = {
|
|
30
38
|
clientType: 'contensis_classic',
|
|
31
39
|
clientDetails: {
|
|
@@ -41,13 +49,7 @@ class ContensisAuthService {
|
|
|
41
49
|
},
|
|
42
50
|
};
|
|
43
51
|
} else {
|
|
44
|
-
credentials = {
|
|
45
|
-
clientType: 'client_credentials',
|
|
46
|
-
clientDetails: {
|
|
47
|
-
clientId,
|
|
48
|
-
clientSecret,
|
|
49
|
-
},
|
|
50
|
-
};
|
|
52
|
+
credentials = { clientType: 'none', clientDetails: { refreshToken: '' } };
|
|
51
53
|
}
|
|
52
54
|
|
|
53
55
|
this.client = NodejsClient.create({
|
|
@@ -57,6 +59,11 @@ class ContensisAuthService {
|
|
|
57
59
|
});
|
|
58
60
|
}
|
|
59
61
|
|
|
62
|
+
ClassicToken = async () => {
|
|
63
|
+
// make sure our token isn't expried.
|
|
64
|
+
await this.client.ensureBearerToken();
|
|
65
|
+
return (this.client as any).contensisClassicToken;
|
|
66
|
+
};
|
|
60
67
|
BearerToken = async () =>
|
|
61
68
|
this.client.bearerToken || (await this.client.ensureBearerToken());
|
|
62
69
|
RefreshToken = async () =>
|
|
@@ -71,9 +71,13 @@ class ContensisCli {
|
|
|
71
71
|
contensisOpts: Partial<MigrateRequest>;
|
|
72
72
|
currentProject: string;
|
|
73
73
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
74
|
+
devinit!: {
|
|
75
|
+
invokedBy: string;
|
|
76
|
+
credentials: {
|
|
77
|
+
clientId: string;
|
|
78
|
+
clientSecret: string;
|
|
79
|
+
};
|
|
80
|
+
};
|
|
77
81
|
|
|
78
82
|
sourceAlias?: string;
|
|
79
83
|
targetEnv?: string;
|
|
@@ -94,6 +98,10 @@ class ContensisCli {
|
|
|
94
98
|
noun: string;
|
|
95
99
|
thirdArg: string;
|
|
96
100
|
|
|
101
|
+
get invokedBy() {
|
|
102
|
+
return this.command.createdUserId;
|
|
103
|
+
}
|
|
104
|
+
|
|
97
105
|
get cache() {
|
|
98
106
|
return this.session.Get();
|
|
99
107
|
}
|
|
@@ -436,9 +444,9 @@ class ContensisCli {
|
|
|
436
444
|
Login = async (
|
|
437
445
|
userId: string,
|
|
438
446
|
{
|
|
439
|
-
password =
|
|
447
|
+
password = '',
|
|
440
448
|
promptPassword = true,
|
|
441
|
-
sharedSecret =
|
|
449
|
+
sharedSecret = '',
|
|
442
450
|
silent = false,
|
|
443
451
|
attempt = 1,
|
|
444
452
|
}: {
|
|
@@ -450,6 +458,13 @@ class ContensisCli {
|
|
|
450
458
|
} = {}
|
|
451
459
|
): Promise<string | undefined> => {
|
|
452
460
|
let inputPassword = password || sharedSecret;
|
|
461
|
+
|
|
462
|
+
if (!inputPassword)
|
|
463
|
+
inputPassword =
|
|
464
|
+
isSharedSecret(this.env.passwordFallback) ||
|
|
465
|
+
isPassword(this.env.passwordFallback) ||
|
|
466
|
+
'';
|
|
467
|
+
|
|
453
468
|
const { log, messages } = this;
|
|
454
469
|
|
|
455
470
|
if (userId) {
|