@squiz/dxp-cli-next 5.9.0-develop.32 → 5.9.0-develop.34

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.
@@ -15,6 +15,7 @@ describe('dxp', () => {
15
15
  'auth Authenticate into the DXP CLI',
16
16
  'cmp Component Service Commands',
17
17
  'job-runner Job Runner Service Commands',
18
+ 'datastore Datastore Commands',
18
19
  ]);
19
20
  });
20
21
  });
@@ -0,0 +1,3 @@
1
+ import { Command } from 'commander';
2
+ declare const createAddCommand: () => Command;
3
+ export default createAddCommand;
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const commander_1 = require("commander");
16
+ const chalk_1 = __importDefault(require("chalk"));
17
+ const ora_1 = __importDefault(require("ora"));
18
+ const ApiService_1 = require("../../../ApiService");
19
+ const utils_1 = require("../../utils");
20
+ const createAddCommand = () => {
21
+ const addCommand = new commander_1.Command('add')
22
+ .name('add')
23
+ .description('Adds a new blueprint')
24
+ .addOption(new commander_1.Option('-t, --tenant <string>', 'Tenant ID to run against. If not provided will use configured tenant from login'))
25
+ .addOption(new commander_1.Option('-p, --path <string>', 'Path to your blueprint API yaml file e.g. documents/inputs/blueprint.yaml').makeOptionMandatory())
26
+ .addOption(new commander_1.Option('-n, --name <string>', 'Name for your blueprint e.g. MyFirstBlueprint').makeOptionMandatory())
27
+ .addOption(new commander_1.Option('-r, --region <string>', 'Region for your blueprint to be deployed yo e.g. au')
28
+ .choices(['au', 'uk', 'us'])
29
+ .makeOptionMandatory())
30
+ .configureOutput({
31
+ outputError(str, write) {
32
+ write(chalk_1.default.red(str));
33
+ },
34
+ })
35
+ .action((options) => __awaiter(void 0, void 0, void 0, function* () {
36
+ yield (0, utils_1.throwErrorIfNotLoggedIn)(addCommand);
37
+ console.log('');
38
+ const spinner = (0, ora_1.default)('Please wait (5 minutes) while our cloud builds this for you.').start();
39
+ let input;
40
+ try {
41
+ const apiService = new ApiService_1.ApiService(utils_1.validateAxiosStatus);
42
+ (0, utils_1.logDebug)('Checking blueprint limit');
43
+ // Check if we are at the blueprint limit.
44
+ const dxpTenantResp = yield apiService.client.get(yield (0, utils_1.buildOrganisationUrl)(options.tenant, options.overrideUrl));
45
+ (0, utils_1.logDebug)(`Blueprint limit response: ${JSON.stringify(dxpTenantResp.data)}`);
46
+ if (dxpTenantResp.data.numberOfDatastoreInstances &&
47
+ dxpTenantResp.data.numberOfDatastoreInstances + 1 >
48
+ dxpTenantResp.data.maximumDatastoreInstances) {
49
+ let limitError = 'Sorry. You are currently limited to ';
50
+ limitError += `${dxpTenantResp.data.maximumDatastoreInstances} blueprint for this customer.`;
51
+ limitError += ' Please speak to your account owner to enable more';
52
+ if (dxpTenantResp.data.maximumDatastoreInstances > 1) {
53
+ limitError = 'Sorry. You are currently limited to ';
54
+ limitError += `${dxpTenantResp.data.maximumDatastoreInstances} blueprints for this customer.`;
55
+ limitError += ' Please speak to your account owner to enable more.';
56
+ }
57
+ throw new Error(limitError);
58
+ }
59
+ // Bundle the blueprint.
60
+ input = yield (0, utils_1.bundleBlueprint)(options.path, true);
61
+ const blueprintFile = Buffer.from(input).toString('base64');
62
+ // Create the instance in the DXP console.
63
+ const datastoreInstanceReq = {
64
+ blueprintFile,
65
+ name: options.name,
66
+ region: options.region,
67
+ type: 'datastore',
68
+ };
69
+ (0, utils_1.logDebug)('Creating new blueprint');
70
+ const datastoreInstanceResp = yield apiService.client.post(yield (0, utils_1.buildInstanceUrl)(options.tenant, undefined, options.overrideUrl, false), datastoreInstanceReq);
71
+ (0, utils_1.logDebug)(`Creating blueprint instance: ${JSON.stringify(datastoreInstanceResp.data)}`);
72
+ if (datastoreInstanceResp.data.message) {
73
+ let errorMsg = '';
74
+ if (datastoreInstanceResp.data.message.startsWith('Error') &&
75
+ datastoreInstanceResp.data.message.toLowerCase() ===
76
+ 'error: name is not unique') {
77
+ errorMsg =
78
+ 'That blueprint name is already taken. Try renaming to something else.';
79
+ }
80
+ else {
81
+ errorMsg = `Failed to add blueprint for "${options.name}" - "${options.path}".`;
82
+ }
83
+ throw new Error(errorMsg);
84
+ }
85
+ // Deploy the instance.
86
+ (0, utils_1.logDebug)('Starting deploy');
87
+ const deployResp = yield apiService.client.post(yield (0, utils_1.buildInstanceUrl)(options.tenant, datastoreInstanceResp.data.instanceId, options.overrideUrl, true));
88
+ (0, utils_1.logDebug)(`Deploying blueprint: ${JSON.stringify(deployResp.data)}`);
89
+ const createdInstance = yield (0, utils_1.checkDeploymentStatus)(apiService, options.tenant, datastoreInstanceResp.data.instanceId, options.overrideUrl);
90
+ spinner.succeed('Done! Use these details for production querying:');
91
+ console.log('');
92
+ console.log(` URL: ${createdInstance.deploymentUrl}`);
93
+ console.log(` Secret Key: ${createdInstance.secretKey}`);
94
+ console.log(` Region: ${createdInstance.region}`);
95
+ console.log('');
96
+ return;
97
+ }
98
+ catch (error) {
99
+ (0, utils_1.logDebug)(`ERROR: ${JSON.stringify(error)}`);
100
+ spinner.fail();
101
+ (0, utils_1.handleCommandError)(addCommand, error);
102
+ }
103
+ }));
104
+ if (process.env.ENABLE_OVERRIDE_DATASTORE_URL === 'true') {
105
+ addCommand.addOption(new commander_1.Option('-ou, --overrideUrl <string>', 'Developer option to override the entire DXP url with a custom value'));
106
+ }
107
+ return addCommand;
108
+ };
109
+ exports.default = createAddCommand;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const nock_1 = __importDefault(require("nock"));
16
+ const add_1 = __importDefault(require("./add"));
17
+ const utils_1 = require("../../utils");
18
+ const logSpy = jest.spyOn(global.console, 'log');
19
+ describe('listJobContexts', () => {
20
+ process.env.ENABLE_OVERRIDE_DATASTORE_URL = 'true';
21
+ it('correctly adds a blueprint', () => __awaiter(void 0, void 0, void 0, function* () {
22
+ (0, nock_1.default)('http://localhost:9999')
23
+ .get('/__dxp/au/dxp/tenants/myTenant')
24
+ .reply(200, {
25
+ numberOfDatastoreInstances: 1,
26
+ maximumDatastoreInstances: 2,
27
+ });
28
+ (0, nock_1.default)('http://localhost:9999')
29
+ .post('/__dxp/au/dxp/tenants/myTenant/instances', {
30
+ blueprintFile: /.+/i,
31
+ name: 'myBlueprint',
32
+ region: 'au',
33
+ type: 'datastore',
34
+ })
35
+ .reply(200, {
36
+ instanceId: 'mock-instance-id',
37
+ });
38
+ (0, nock_1.default)('http://localhost:9999')
39
+ .post('/__dxp/au/dxp/tenants/myTenant/instances/mock-instance-id/_deploy')
40
+ .reply(200, {
41
+ instanceId: 'mock-instance-id',
42
+ });
43
+ (0, nock_1.default)('http://localhost:9999')
44
+ .get('/__dxp/au/dxp/tenants/myTenant/instances/mock-instance-id')
45
+ .reply(200, {
46
+ status: {
47
+ code: utils_1.CONSOLE_STATUS_CODE_LIVE,
48
+ },
49
+ deploymentUrl: 'https://au-12345678.datastore.squiz.cloud',
50
+ secretKey: 'secretKey',
51
+ region: 'au',
52
+ });
53
+ const program = (0, add_1.default)();
54
+ yield program.parseAsync([
55
+ 'node',
56
+ 'dxp-cli',
57
+ 'datastore',
58
+ 'blueprint',
59
+ 'add',
60
+ '-t',
61
+ 'myTenant',
62
+ '-p',
63
+ './src/__tests__/datastore/blueprints/blueprint.yaml',
64
+ '-n',
65
+ 'myBlueprint',
66
+ '-r',
67
+ 'au',
68
+ '-ou',
69
+ 'http://localhost:9999',
70
+ ]);
71
+ const opts = program.opts();
72
+ expect(opts.tenant).toEqual('myTenant');
73
+ expect(opts.overrideUrl).toEqual('http://localhost:9999');
74
+ expect(logSpy).toHaveBeenCalledTimes(6);
75
+ expect(logSpy).toHaveBeenCalledWith('');
76
+ expect(logSpy).toHaveBeenCalledWith('');
77
+ expect(logSpy).toHaveBeenCalledWith(' URL: https://au-12345678.datastore.squiz.cloud');
78
+ expect(logSpy).toHaveBeenCalledWith(' Secret Key: secretKey');
79
+ expect(logSpy).toHaveBeenCalledWith(' Region: au');
80
+ expect(logSpy).toHaveBeenCalledWith('');
81
+ }));
82
+ });
@@ -0,0 +1,3 @@
1
+ import { Command } from 'commander';
2
+ declare const createBlueprintCommand: () => Command;
3
+ export default createBlueprintCommand;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const commander_1 = require("commander");
7
+ const add_1 = __importDefault(require("./add/add"));
8
+ const update_1 = __importDefault(require("./update/update"));
9
+ const createBlueprintCommand = () => {
10
+ const datastoreBlueprintCommand = new commander_1.Command('blueprint');
11
+ datastoreBlueprintCommand
12
+ .description('Datastore Blueprint Commands')
13
+ .addCommand((0, add_1.default)())
14
+ .addCommand((0, update_1.default)());
15
+ return datastoreBlueprintCommand;
16
+ };
17
+ exports.default = createBlueprintCommand;
@@ -0,0 +1,3 @@
1
+ import { Command } from 'commander';
2
+ declare const createUpdateCommand: () => Command;
3
+ export default createUpdateCommand;
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const commander_1 = require("commander");
16
+ const chalk_1 = __importDefault(require("chalk"));
17
+ const ora_1 = __importDefault(require("ora"));
18
+ const ApiService_1 = require("../../../ApiService");
19
+ const utils_1 = require("../../utils");
20
+ const createUpdateCommand = () => {
21
+ const updateCommand = new commander_1.Command('update')
22
+ .name('update')
23
+ .description('Updates an existing blueprint')
24
+ .addOption(new commander_1.Option('-t, --tenant <string>', 'Tenant ID to run against. If not provided will use configured tenant from login'))
25
+ .addOption(new commander_1.Option('-p, --path <string>', 'Path to your blueprint API yaml file e.g. documents/inputs/blueprint.yaml').makeOptionMandatory())
26
+ .addOption(new commander_1.Option('-n, --name <string>', 'Name for your blueprint e.g. MyFirstBlueprint').makeOptionMandatory())
27
+ .configureOutput({
28
+ outputError(str, write) {
29
+ write(chalk_1.default.red(str));
30
+ },
31
+ })
32
+ .action((options) => __awaiter(void 0, void 0, void 0, function* () {
33
+ yield (0, utils_1.throwErrorIfNotLoggedIn)(updateCommand);
34
+ console.log('');
35
+ const spinner = (0, ora_1.default)('Please wait (5 minutes) while our cloud builds this for you.').start();
36
+ let input;
37
+ try {
38
+ const apiService = new ApiService_1.ApiService(utils_1.validateAxiosStatus);
39
+ (0, utils_1.logDebug)('Checking current blueprints');
40
+ // Check if we are at the blueprint limit.
41
+ const datastoreInstancesResp = yield apiService.client.get(yield (0, utils_1.buildDatastoreInstancesUrl)(options.tenant, options.overrideUrl));
42
+ (0, utils_1.logDebug)(`Finding blueprint with name: ${options.name}`);
43
+ const datastoreInstances = datastoreInstancesResp.data.filter((instance) => {
44
+ return instance.name === options.name;
45
+ });
46
+ if (datastoreInstances.length !== 1) {
47
+ throw new Error('Unexpected error. Ask for help in our support forums.');
48
+ }
49
+ const datastoreInstance = datastoreInstances[0];
50
+ // Bundle the blueprint.
51
+ input = yield (0, utils_1.bundleBlueprint)(options.path, true);
52
+ const blueprintFile = Buffer.from(input).toString('base64');
53
+ const datastoreInstanceReq = {
54
+ blueprintFile,
55
+ status: {
56
+ code: 'Deploying',
57
+ message: 'Instance is deploying',
58
+ },
59
+ };
60
+ (0, utils_1.logDebug)(`Updating blueprint: ${options.name}`);
61
+ const datastoreInstanceResp = yield apiService.client.patch(yield (0, utils_1.buildInstanceUrl)(options.tenant, datastoreInstance.instanceId, options.overrideUrl, false), datastoreInstanceReq);
62
+ (0, utils_1.logDebug)(`Updating blueprint instance: ${JSON.stringify(datastoreInstanceResp.data)}`);
63
+ // Deploy the instance.
64
+ (0, utils_1.logDebug)('Starting deploy');
65
+ const deployResp = yield apiService.client.post(yield (0, utils_1.buildInstanceUrl)(options.tenant, datastoreInstance.instanceId, options.overrideUrl, true), datastoreInstanceReq);
66
+ (0, utils_1.logDebug)(`Deploying blueprint: ${JSON.stringify(deployResp.data)}`);
67
+ const updatedInstance = yield (0, utils_1.checkDeploymentStatus)(apiService, options.tenant, datastoreInstance.instanceId, options.overrideUrl);
68
+ spinner.succeed('Done! Use these details for production querying:');
69
+ console.log('');
70
+ console.log(` URL: ${updatedInstance.deploymentUrl}`);
71
+ console.log(` Secret Key: ${updatedInstance.secretKey}`);
72
+ console.log(` Region: ${updatedInstance.region}`);
73
+ console.log('');
74
+ return;
75
+ }
76
+ catch (error) {
77
+ (0, utils_1.logDebug)(`ERROR: ${JSON.stringify(error)}`);
78
+ spinner.fail();
79
+ (0, utils_1.handleCommandError)(updateCommand, error);
80
+ }
81
+ }));
82
+ if (process.env.ENABLE_OVERRIDE_DATASTORE_URL === 'true') {
83
+ updateCommand.addOption(new commander_1.Option('-ou, --overrideUrl <string>', 'Developer option to override the entire DXP url with a custom value'));
84
+ }
85
+ return updateCommand;
86
+ };
87
+ exports.default = createUpdateCommand;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const nock_1 = __importDefault(require("nock"));
16
+ const update_1 = __importDefault(require("./update"));
17
+ const utils_1 = require("../../utils");
18
+ const logSpy = jest.spyOn(global.console, 'log');
19
+ describe('listJobContexts', () => {
20
+ process.env.ENABLE_OVERRIDE_DATASTORE_URL = 'true';
21
+ it('correctly adds a blueprint', () => __awaiter(void 0, void 0, void 0, function* () {
22
+ (0, nock_1.default)('http://localhost:9999')
23
+ .get('/__dxp/au/dxp/tenants/myTenant/instances?type=datastore')
24
+ .reply(200, [
25
+ {
26
+ status: {
27
+ code: utils_1.CONSOLE_STATUS_CODE_LIVE,
28
+ },
29
+ deploymentUrl: 'https://au-asdfghj.datastore.squiz.cloud',
30
+ secretKey: 'secretKey',
31
+ region: 'au',
32
+ name: 'secondBlueprint',
33
+ instanceId: '1234',
34
+ },
35
+ {
36
+ status: {
37
+ code: utils_1.CONSOLE_STATUS_CODE_LIVE,
38
+ },
39
+ deploymentUrl: 'https://au-12345678.datastore.squiz.cloud',
40
+ secretKey: 'secretKey',
41
+ region: 'au',
42
+ name: 'myBlueprint',
43
+ instanceId: 'mock-instance-id',
44
+ },
45
+ ]);
46
+ (0, nock_1.default)('http://localhost:9999')
47
+ .patch('/__dxp/au/dxp/tenants/myTenant/instances/mock-instance-id', {
48
+ blueprintFile: /.+/i,
49
+ status: {
50
+ code: 'Deploying',
51
+ message: 'Instance is deploying',
52
+ },
53
+ })
54
+ .reply(200, {
55
+ instanceId: 'mock-instance-id',
56
+ });
57
+ (0, nock_1.default)('http://localhost:9999')
58
+ .post('/__dxp/au/dxp/tenants/myTenant/instances/mock-instance-id/_deploy')
59
+ .reply(200, {
60
+ instanceId: 'mock-instance-id',
61
+ });
62
+ (0, nock_1.default)('http://localhost:9999')
63
+ .get('/__dxp/au/dxp/tenants/myTenant/instances/mock-instance-id')
64
+ .reply(200, {
65
+ status: {
66
+ code: utils_1.CONSOLE_STATUS_CODE_LIVE,
67
+ },
68
+ deploymentUrl: 'https://au-12345678.datastore.squiz.cloud',
69
+ secretKey: 'secretKey',
70
+ region: 'au',
71
+ });
72
+ const program = (0, update_1.default)();
73
+ yield program.parseAsync([
74
+ 'node',
75
+ 'dxp-cli',
76
+ 'datastore',
77
+ 'blueprint',
78
+ 'update',
79
+ '-t',
80
+ 'myTenant',
81
+ '-p',
82
+ './src/__tests__/datastore/blueprints/blueprint.yaml',
83
+ '-n',
84
+ 'myBlueprint',
85
+ '-ou',
86
+ 'http://localhost:9999',
87
+ ]);
88
+ const opts = program.opts();
89
+ expect(opts.tenant).toEqual('myTenant');
90
+ expect(opts.overrideUrl).toEqual('http://localhost:9999');
91
+ expect(logSpy).toHaveBeenCalledTimes(6);
92
+ expect(logSpy).toHaveBeenCalledWith('');
93
+ expect(logSpy).toHaveBeenCalledWith('');
94
+ expect(logSpy).toHaveBeenCalledWith(' URL: https://au-12345678.datastore.squiz.cloud');
95
+ expect(logSpy).toHaveBeenCalledWith(' Secret Key: secretKey');
96
+ expect(logSpy).toHaveBeenCalledWith(' Region: au');
97
+ expect(logSpy).toHaveBeenCalledWith('');
98
+ }));
99
+ });
@@ -0,0 +1,3 @@
1
+ import { Command } from 'commander';
2
+ declare const datastoreCommand: Command;
3
+ export default datastoreCommand;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const commander_1 = require("commander");
7
+ const blueprintCommand_1 = __importDefault(require("./blueprint/blueprintCommand"));
8
+ const datastoreCommand = new commander_1.Command('datastore');
9
+ datastoreCommand
10
+ .description('Datastore Commands')
11
+ .addCommand((0, blueprintCommand_1.default)());
12
+ exports.default = datastoreCommand;
@@ -0,0 +1,18 @@
1
+ import { Command } from 'commander';
2
+ import { ApiService } from '../ApiService';
3
+ export declare const CONSOLE_STATUS_CODE_LIVE = "Live";
4
+ export declare const CONSOLE_STATUS_CODE_ERROR = "Error";
5
+ export declare function logDebug(message: string): void;
6
+ export declare function bundleBlueprint(filePath: string, asYaml?: boolean): Promise<string>;
7
+ export declare function handleCommandError(command: Command, error: Error): void;
8
+ export declare function throwErrorIfNotLoggedIn(command: Command): Promise<void>;
9
+ export declare function writeLineSeparator(): void;
10
+ export declare function validateAxiosStatus(status: number): boolean;
11
+ export declare function buildDXPUrl(tenantID?: string, override?: string): Promise<{
12
+ dxpUrl: string;
13
+ tenant: string | undefined;
14
+ }>;
15
+ export declare function buildOrganisationUrl(tenantID?: string, override?: string): Promise<string>;
16
+ export declare function buildInstanceUrl(tenantID?: string, instanceID?: string, override?: string, isDeploy?: boolean): Promise<string>;
17
+ export declare function buildDatastoreInstancesUrl(tenantID?: string, override?: string): Promise<string>;
18
+ export declare function checkDeploymentStatus(apiService: ApiService, tenantID?: string, instanceID?: string, override?: string): Promise<any>;
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ exports.checkDeploymentStatus = exports.buildDatastoreInstancesUrl = exports.buildInstanceUrl = exports.buildOrganisationUrl = exports.buildDXPUrl = exports.validateAxiosStatus = exports.writeLineSeparator = exports.throwErrorIfNotLoggedIn = exports.handleCommandError = exports.bundleBlueprint = exports.logDebug = exports.CONSOLE_STATUS_CODE_ERROR = exports.CONSOLE_STATUS_CODE_LIVE = void 0;
39
+ const path_1 = __importDefault(require("path"));
40
+ const fs_1 = __importDefault(require("fs"));
41
+ const chalk_1 = __importDefault(require("chalk"));
42
+ const ApplicationConfig_1 = require("../ApplicationConfig");
43
+ const axios_1 = __importDefault(require("axios"));
44
+ const ApplicationStore_1 = require("../ApplicationStore");
45
+ const swagger_parser_1 = __importDefault(require("@apidevtools/swagger-parser"));
46
+ const YAML = __importStar(require("yaml"));
47
+ exports.CONSOLE_STATUS_CODE_LIVE = 'Live';
48
+ exports.CONSOLE_STATUS_CODE_ERROR = 'Error';
49
+ /* istanbul ignore next */
50
+ const sleep = (ms) => {
51
+ return new Promise(resolve => setTimeout(resolve, ms));
52
+ };
53
+ /* istanbul ignore next */
54
+ function logDebug(message) {
55
+ if (!!process.env.DEBUG) {
56
+ console.log(message);
57
+ }
58
+ }
59
+ exports.logDebug = logDebug;
60
+ function bundleBlueprint(filePath, asYaml = true) {
61
+ return __awaiter(this, void 0, void 0, function* () {
62
+ const inputPath = path_1.default.resolve(filePath);
63
+ let bundle;
64
+ if (fs_1.default.existsSync(inputPath)) {
65
+ try {
66
+ logDebug(`Bundling ${inputPath}`);
67
+ bundle = yield swagger_parser_1.default.dereference(inputPath, {
68
+ dereference: {
69
+ circular: 'ignore',
70
+ },
71
+ parse: {
72
+ json: {
73
+ order: 2,
74
+ },
75
+ yaml: {
76
+ order: 1,
77
+ },
78
+ },
79
+ resolve: {
80
+ external: true,
81
+ file: {
82
+ canRead: true,
83
+ order: 1,
84
+ },
85
+ http: {
86
+ canRead: true,
87
+ order: 1,
88
+ },
89
+ },
90
+ validate: {
91
+ spec: true,
92
+ },
93
+ });
94
+ if (asYaml) {
95
+ bundle = YAML.stringify(bundle);
96
+ }
97
+ else {
98
+ bundle = JSON.stringify(bundle);
99
+ }
100
+ return bundle;
101
+ }
102
+ catch (e) {
103
+ throw new Error(`Unable to read file ${inputPath} - ${e.message}`);
104
+ }
105
+ }
106
+ else {
107
+ throw new Error('Input could not be found');
108
+ }
109
+ });
110
+ }
111
+ exports.bundleBlueprint = bundleBlueprint;
112
+ function handleCommandError(command, error) {
113
+ var _a, _b, _c, _d;
114
+ if (axios_1.default.isAxiosError(error)) {
115
+ let message = `${error.message}`;
116
+ if ((_b = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.message) {
117
+ message += `: ${error.response.data.message}`;
118
+ }
119
+ if ((_d = (_c = error.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.details) {
120
+ message += ` - ${error.response.data.details}`;
121
+ }
122
+ command.error(chalk_1.default.red(message));
123
+ }
124
+ else {
125
+ if (!!process.env.DEBUG && error.stack) {
126
+ command.error(error.stack);
127
+ }
128
+ if (error.message) {
129
+ command.error(chalk_1.default.red(error.message));
130
+ }
131
+ else {
132
+ command.error(chalk_1.default.red('An unknown error occurred'));
133
+ }
134
+ }
135
+ }
136
+ exports.handleCommandError = handleCommandError;
137
+ function throwErrorIfNotLoggedIn(command) {
138
+ return __awaiter(this, void 0, void 0, function* () {
139
+ if (!(yield (0, ApplicationStore_1.getApplicationFile)(ApplicationStore_1.STORE_FILES.sessionCookie))) {
140
+ command.error(chalk_1.default.red('You must login to interact with the job runner. See `dxp-next auth login`'));
141
+ }
142
+ });
143
+ }
144
+ exports.throwErrorIfNotLoggedIn = throwErrorIfNotLoggedIn;
145
+ function writeLineSeparator() {
146
+ console.log(chalk_1.default.cyan('------------------------------'));
147
+ }
148
+ exports.writeLineSeparator = writeLineSeparator;
149
+ function validateAxiosStatus(status) {
150
+ return status < 400;
151
+ }
152
+ exports.validateAxiosStatus = validateAxiosStatus;
153
+ function buildDXPUrl(tenantID, override) {
154
+ return __awaiter(this, void 0, void 0, function* () {
155
+ if (!override) {
156
+ const existingConfig = yield (0, ApplicationConfig_1.fetchApplicationConfig)(tenantID);
157
+ logDebug(`existingConfig: ${JSON.stringify(existingConfig)}`);
158
+ return {
159
+ dxpUrl: `${existingConfig.baseUrl}/__dxp/${existingConfig.region}/dxp`,
160
+ tenant: existingConfig.tenant,
161
+ };
162
+ }
163
+ else {
164
+ logDebug(`Using override URL: ${override}`);
165
+ return {
166
+ dxpUrl: `${override}/__dxp/au/dxp`,
167
+ tenant: tenantID,
168
+ };
169
+ }
170
+ });
171
+ }
172
+ exports.buildDXPUrl = buildDXPUrl;
173
+ function buildOrganisationUrl(tenantID, override) {
174
+ return __awaiter(this, void 0, void 0, function* () {
175
+ const dxpUrlConfig = yield buildDXPUrl(tenantID, override);
176
+ return `${dxpUrlConfig.dxpUrl}/tenants/${dxpUrlConfig.tenant}`;
177
+ });
178
+ }
179
+ exports.buildOrganisationUrl = buildOrganisationUrl;
180
+ function buildInstanceUrl(tenantID, instanceID, override, isDeploy = false) {
181
+ return __awaiter(this, void 0, void 0, function* () {
182
+ const dxpUrlConfig = yield buildDXPUrl(tenantID, override);
183
+ const base = `${dxpUrlConfig.dxpUrl}/tenants/${dxpUrlConfig.tenant}`;
184
+ if (isDeploy) {
185
+ return `${base}/instances/${instanceID}/_deploy`;
186
+ }
187
+ return instanceID ? `${base}/instances/${instanceID}` : `${base}/instances`;
188
+ });
189
+ }
190
+ exports.buildInstanceUrl = buildInstanceUrl;
191
+ function buildDatastoreInstancesUrl(tenantID, override) {
192
+ return __awaiter(this, void 0, void 0, function* () {
193
+ const url = yield buildInstanceUrl(tenantID, undefined, override, false);
194
+ return `${url}?type=datastore`;
195
+ });
196
+ }
197
+ exports.buildDatastoreInstancesUrl = buildDatastoreInstancesUrl;
198
+ function checkDeploymentStatus(apiService, tenantID, instanceID, override) {
199
+ return __awaiter(this, void 0, void 0, function* () {
200
+ let lastPollStatus = '';
201
+ let lastPollTime = 0;
202
+ let pollTimeout = false;
203
+ let datastoreInstanceResp;
204
+ let datastoreInstance;
205
+ do {
206
+ datastoreInstanceResp = yield apiService.client.get(yield buildInstanceUrl(tenantID, instanceID, override, false));
207
+ datastoreInstance = datastoreInstanceResp.data;
208
+ const nowAt = Math.floor(Date.now() / 1000);
209
+ if (lastPollStatus !== datastoreInstance.status.message) {
210
+ lastPollStatus = datastoreInstance.status.message;
211
+ lastPollTime = nowAt;
212
+ }
213
+ else if (nowAt - lastPollTime > 600 &&
214
+ lastPollStatus === datastoreInstance.status.message) {
215
+ pollTimeout = true;
216
+ }
217
+ yield sleep(3000);
218
+ } while (datastoreInstance.status.code !== exports.CONSOLE_STATUS_CODE_LIVE &&
219
+ datastoreInstance.status.code !== exports.CONSOLE_STATUS_CODE_ERROR &&
220
+ !pollTimeout);
221
+ if (datastoreInstance.status.code === exports.CONSOLE_STATUS_CODE_LIVE) {
222
+ return datastoreInstance;
223
+ }
224
+ else {
225
+ throw new Error(datastoreInstance.status.message);
226
+ }
227
+ });
228
+ }
229
+ exports.checkDeploymentStatus = checkDeploymentStatus;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const utils_1 = require("./utils");
16
+ const commander_1 = require("commander");
17
+ const axios_1 = require("axios");
18
+ const chalk_1 = __importDefault(require("chalk"));
19
+ const path_1 = __importDefault(require("path"));
20
+ const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => {
21
+ return undefined;
22
+ }); // prevent process exit on error
23
+ const stderrSpy = jest.spyOn(process.stderr, 'write');
24
+ const logSpy = jest.spyOn(global.console, 'log');
25
+ beforeEach(() => {
26
+ jest.resetAllMocks();
27
+ });
28
+ describe('handleCommandError', () => {
29
+ it('correctly displays the console logs for command error', () => __awaiter(void 0, void 0, void 0, function* () {
30
+ const command = new commander_1.Command();
31
+ const message = 'Something bad happened';
32
+ (0, utils_1.handleCommandError)(command, new Error(message));
33
+ expect(stderrSpy).toHaveBeenCalledTimes(1);
34
+ console.log(stderrSpy.mock.calls);
35
+ // read the mock call strings directly otherwise colours cause test failures with .toEqual()
36
+ expect(stderrSpy.mock.calls[0][0]).toContain(message);
37
+ }));
38
+ it('correctly displays the console logs for axios error', () => __awaiter(void 0, void 0, void 0, function* () {
39
+ const command = new commander_1.Command();
40
+ const message = 'Something bad happened';
41
+ const responseMessage = 'I am an error response';
42
+ const errDetails = 'i am error details';
43
+ (0, utils_1.handleCommandError)(command, new axios_1.AxiosError(message, '500', undefined, undefined, {
44
+ data: { message: responseMessage, details: errDetails },
45
+ }));
46
+ expect(stderrSpy).toHaveBeenCalledTimes(1);
47
+ // read the mock call strings directly otherwise colours cause test failures with .toEqual()
48
+ expect(stderrSpy.mock.calls[0][0]).toContain(`${message}: ${responseMessage} - ${errDetails}`);
49
+ }));
50
+ it('correctly displays the console logs for error without a message', () => __awaiter(void 0, void 0, void 0, function* () {
51
+ const command = new commander_1.Command();
52
+ (0, utils_1.handleCommandError)(command, new Error());
53
+ expect(stderrSpy).toHaveBeenCalledTimes(1);
54
+ // read the mock call strings directly otherwise colours cause test failures with .toEqual()
55
+ expect(stderrSpy.mock.calls[0][0]).toContain('An unknown error occurred');
56
+ }));
57
+ });
58
+ describe('writeLineSeparator', () => {
59
+ it('correctly displays the console logs for line separator', () => __awaiter(void 0, void 0, void 0, function* () {
60
+ (0, utils_1.writeLineSeparator)();
61
+ expect(logSpy).toHaveBeenCalledTimes(1);
62
+ expect(logSpy).toHaveBeenCalledWith(chalk_1.default.cyan('------------------------------'));
63
+ }));
64
+ });
65
+ describe('validateAxiosStatus', () => {
66
+ it('correctly validates the status', () => __awaiter(void 0, void 0, void 0, function* () {
67
+ expect((0, utils_1.validateAxiosStatus)(200)).toBe(true);
68
+ expect((0, utils_1.validateAxiosStatus)(400)).toBe(false);
69
+ }));
70
+ });
71
+ describe('bundleBlueprint', () => {
72
+ it('should return a YAML string', () => __awaiter(void 0, void 0, void 0, function* () {
73
+ const res = yield (0, utils_1.bundleBlueprint)(path_1.default.join('./src/__tests__/datastore/blueprints/blueprint.yaml'));
74
+ expect(res).toEqual(`openapi: 3.0.2
75
+ info:
76
+ description: A Sample Test API
77
+ version: 1.0.0
78
+ title: Unit Test
79
+ paths:
80
+ /acl-dxp-authentication-1:
81
+ get:
82
+ x-datastore-acl: public
83
+ responses:
84
+ "200":
85
+ description: OK
86
+ `);
87
+ }));
88
+ it('should return a JSON string', () => __awaiter(void 0, void 0, void 0, function* () {
89
+ const res = yield (0, utils_1.bundleBlueprint)(path_1.default.join('./src/__tests__/datastore/blueprints/blueprint.json'), false);
90
+ expect(res).toStrictEqual('{"openapi":"3.0.2","info":{"description":"A Sample Test API","version":"1.0.0","title":"Unit Test"},"paths":{"/acl-dxp-authentication-1":{"get":{"x-datastore-acl":"public","responses":{"200":{"description":"OK"}}}}}}');
91
+ }));
92
+ });
package/lib/dxp.js CHANGED
@@ -14,6 +14,7 @@ validateNodeVersion();
14
14
  const auth_1 = __importDefault(require("./auth"));
15
15
  const cmp_1 = __importDefault(require("./cmp"));
16
16
  const job_runner_1 = __importDefault(require("./job-runner"));
17
+ const datastore_1 = __importDefault(require("./datastore"));
17
18
  const program = new commander_1.default.Command();
18
19
  const packageJson = require('../package.json');
19
20
  const version = packageJson.version;
@@ -24,6 +25,7 @@ program
24
25
  .addCommand(auth_1.default)
25
26
  .addCommand(cmp_1.default)
26
27
  .addCommand(job_runner_1.default)
28
+ .addCommand(datastore_1.default)
27
29
  .action(() => {
28
30
  program.help();
29
31
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@squiz/dxp-cli-next",
3
- "version": "5.9.0-develop.32",
3
+ "version": "5.9.0-develop.34",
4
4
  "repository": {
5
5
  "url": "https://gitlab.squiz.net/dxp/dxp-cli-next"
6
6
  },
@@ -39,7 +39,8 @@
39
39
  "codecov"
40
40
  ],
41
41
  "dependencies": {
42
- "@squiz/component-cli-lib": "1.60.0",
42
+ "@squiz/component-cli-lib": "1.60.1-alpha.1",
43
+ "@apidevtools/swagger-parser": "10.1.0",
43
44
  "axios": "1.1.3",
44
45
  "cli-color": "2.0.3",
45
46
  "commander": "9.4.0",
@@ -49,7 +50,8 @@
49
50
  "ora": "^5.4.1",
50
51
  "prompt": "^1.3.0",
51
52
  "tough-cookie": "4.1.2",
52
- "update-notifier": "5.1.0"
53
+ "update-notifier": "5.1.0",
54
+ "yaml": "^2.3.4"
53
55
  },
54
56
  "devDependencies": {
55
57
  "@semantic-release/git": "10.0.1",