@contentstack/cli-utilities 1.1.0 → 1.3.0

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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2022 Contentstack
3
+ Copyright (c) 2023 Contentstack
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/lib/cli-ux.js CHANGED
@@ -1,9 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Command = exports.Args = exports.Flags = void 0;
3
4
  const tslib_1 = require("tslib");
4
5
  const chalk_1 = tslib_1.__importDefault(require("chalk"));
5
6
  const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
6
- const cli_ux_1 = require("@oclif/core/lib/cli-ux");
7
+ const core_1 = require("@oclif/core");
8
+ Object.defineProperty(exports, "Args", { enumerable: true, get: function () { return core_1.Args; } });
9
+ Object.defineProperty(exports, "Flags", { enumerable: true, get: function () { return core_1.Flags; } });
10
+ Object.defineProperty(exports, "Command", { enumerable: true, get: function () { return core_1.Command; } });
7
11
  const message_handler_1 = tslib_1.__importDefault(require("./message-handler"));
8
12
  /**
9
13
  * CLI Interface
@@ -13,47 +17,61 @@ class CLIInterface {
13
17
  this.loading = false;
14
18
  }
15
19
  get uxTable() {
16
- return cli_ux_1.ux.table;
20
+ return core_1.ux.table;
17
21
  }
18
22
  init(context) { }
23
+ registerSearchPlugin() {
24
+ inquirer_1.default.registerPrompt('search-list', require('inquirer-search-list'));
25
+ inquirer_1.default.registerPrompt('search-checkbox', require('inquirer-search-checkbox'));
26
+ }
19
27
  print(message, opts) {
20
- if (opts && opts.color) {
21
- cli_ux_1.ux.log(chalk_1.default[opts.color](message_handler_1.default.parse(message)));
28
+ if (opts) {
29
+ let chalkFn = chalk_1.default;
30
+ if (opts.color)
31
+ chalkFn = chalkFn[opts.color];
32
+ if (opts.bold)
33
+ chalkFn = chalkFn.bold;
34
+ core_1.ux.log(chalkFn(message_handler_1.default.parse(message)));
22
35
  return;
23
36
  }
24
- cli_ux_1.ux.log(message_handler_1.default.parse(message));
37
+ core_1.ux.log(message_handler_1.default.parse(message));
25
38
  }
26
39
  success(message) {
27
- cli_ux_1.ux.log(chalk_1.default.green(message_handler_1.default.parse(message)));
40
+ core_1.ux.log(chalk_1.default.green(message_handler_1.default.parse(message)));
28
41
  }
29
42
  error(message, ...params) {
30
- cli_ux_1.ux.log(chalk_1.default.red(message_handler_1.default.parse(message) + (params && params.length > 0 ? ': ' : '')), ...params);
43
+ core_1.ux.log(chalk_1.default.red(message_handler_1.default.parse(message) + (params && params.length > 0 ? ': ' : '')), ...params);
31
44
  }
32
45
  loader(message = '') {
33
46
  if (!this.loading) {
34
- cli_ux_1.ux.action.start(message_handler_1.default.parse(message));
47
+ core_1.ux.action.start(message_handler_1.default.parse(message));
35
48
  }
36
49
  else {
37
- cli_ux_1.ux.action.stop(message_handler_1.default.parse(message));
50
+ core_1.ux.action.stop(message_handler_1.default.parse(message));
38
51
  }
39
52
  this.loading = !this.loading;
40
53
  }
41
54
  table(data, columns, options) {
42
- cli_ux_1.ux.table(data, columns, options);
55
+ core_1.ux.table(data, columns, options);
43
56
  }
44
57
  async inquire(inquirePayload) {
45
- inquirePayload.message = message_handler_1.default.parse(inquirePayload.message);
46
- const result = await inquirer_1.default.prompt(inquirePayload);
47
- return result[inquirePayload.name];
58
+ if (Array.isArray(inquirePayload)) {
59
+ return inquirer_1.default.prompt(inquirePayload);
60
+ }
61
+ else {
62
+ inquirePayload.message = message_handler_1.default.parse(inquirePayload.message);
63
+ const result = await inquirer_1.default.prompt(inquirePayload);
64
+ return result[inquirePayload.name];
65
+ }
48
66
  }
49
67
  prompt(name, options) {
50
- return cli_ux_1.ux.prompt(name, options);
68
+ return core_1.ux.prompt(name, options);
51
69
  }
52
70
  confirm(message) {
53
- return cli_ux_1.ux.confirm(message);
71
+ return core_1.ux.confirm(message);
54
72
  }
55
73
  progress(options) {
56
- return cli_ux_1.ux.progress(options);
74
+ return core_1.ux.progress(options);
57
75
  }
58
76
  }
59
77
  exports.default = new CLIInterface();
@@ -1,33 +1,37 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.managementSDKInitiator = void 0;
3
4
  const tslib_1 = require("tslib");
4
- const ContentstackManagementSDK = tslib_1.__importStar(require("@contentstack/management"));
5
- const https = require('https');
5
+ const management_1 = require("@contentstack/management");
6
+ const node_https_1 = require("node:https");
6
7
  const config_handler_1 = tslib_1.__importDefault(require("./config-handler"));
7
- exports.default = async (config) => {
8
- try {
9
- let managementAPIClient;
8
+ class ManagementSDKInitiator {
9
+ constructor() { }
10
+ init(context) {
11
+ this.analyticsInfo = context === null || context === void 0 ? void 0 : context.analyticsInfo;
12
+ }
13
+ async createAPIClient(config) {
10
14
  const option = {
11
15
  host: config.host,
12
- management_token: config.management_token,
13
- api_key: config.stack_api_key,
14
16
  maxContentLength: 100000000,
15
17
  maxBodyLength: 1000000000,
16
18
  maxRequests: 10,
17
19
  retryLimit: 3,
18
20
  timeout: 60000,
19
- httpsAgent: new https.Agent({
21
+ httpsAgent: new node_https_1.Agent({
20
22
  maxSockets: 100,
21
23
  maxFreeSockets: 10,
22
24
  keepAlive: true,
23
- timeout: 60000,
24
- freeSocketTimeout: 30000, // free socket keepalive for 30 seconds
25
+ timeout: 60000, // active socket keepalive for 60 seconds
26
+ // NOTE freeSocketTimeout option not exist in https client
27
+ // freeSocketTimeout: 30000, // free socket keepalive for 30 seconds
25
28
  }),
26
29
  retryDelay: Math.floor(Math.random() * (8000 - 3000 + 1) + 3000),
27
30
  logHandler: (level, data) => { },
28
31
  retryCondition: (error) => {
32
+ // LINK https://github.com/contentstack/contentstack-javascript/blob/72fee8ad75ba7d1d5bab8489ebbbbbbaefb1c880/src/core/stack.js#L49
29
33
  if (error.response && error.response.status) {
30
- switch (error.response.status) {
34
+ switch (error.status) {
31
35
  case 401:
32
36
  case 429:
33
37
  case 408:
@@ -44,32 +48,32 @@ exports.default = async (config) => {
44
48
  },
45
49
  },
46
50
  refreshToken: () => {
47
- return new Promise((resolve, reject) => {
48
- reject('You do not have permissions to perform this action, please login to proceed');
49
- });
51
+ return Promise.reject('You do not have permissions to perform this action, please login to proceed');
50
52
  },
51
53
  };
52
54
  if (typeof config.branchName === 'string') {
53
- option['headers'] = {
54
- branch: config.branchName,
55
- };
55
+ if (!option.headers)
56
+ option.headers = {};
57
+ option.headers.branch = config.branchName;
58
+ }
59
+ if (this.analyticsInfo) {
60
+ if (!option.headers)
61
+ option.headers = {};
62
+ option.headers['X-CS-CLI'] = this.analyticsInfo;
56
63
  }
57
64
  if (!config.management_token) {
58
65
  const authtoken = config_handler_1.default.get('authtoken');
59
66
  if (authtoken) {
60
- option['authtoken'] = config_handler_1.default.get('authtoken');
61
- option['authorization'] = '';
67
+ option.authtoken = authtoken;
68
+ option.authorization = '';
62
69
  }
63
70
  else {
64
- option['authtoken'] = '';
65
- option['authorization'] = '';
71
+ option.authtoken = '';
72
+ option.authorization = '';
66
73
  }
67
74
  }
68
- managementAPIClient = ContentstackManagementSDK.client(option);
69
- return managementAPIClient;
70
- }
71
- catch (error) {
72
- console.error(error);
73
- throw new Error(error);
75
+ return (0, management_1.client)(option);
74
76
  }
75
- };
77
+ }
78
+ exports.managementSDKInitiator = new ManagementSDKInitiator();
79
+ exports.default = exports.managementSDKInitiator.createAPIClient.bind(exports.managementSDKInitiator);
package/lib/helpers.js ADDED
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isAuthenticated = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const config_handler_1 = tslib_1.__importDefault(require("./config-handler"));
6
+ function isAuthenticated() {
7
+ const authtoken = config_handler_1.default.get('authtoken');
8
+ if (authtoken) {
9
+ return true;
10
+ }
11
+ else {
12
+ return false;
13
+ }
14
+ }
15
+ exports.isAuthenticated = isAuthenticated;
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NodeCrypto = exports.printFlagDeprecation = exports.managementSDKClient = exports.configHandler = exports.messageHandler = exports.CLIError = exports.cliux = exports.logger = void 0;
3
+ exports.stdout = exports.stderr = exports.execute = exports.ux = exports.flush = exports.settings = exports.toConfiguredId = exports.toStandardizedId = exports.tsPath = exports.toCached = exports.run = exports.Plugin = exports.Parser = exports.Interfaces = exports.HelpBase = exports.Help = exports.loadHelpClass = exports.Flags = exports.Errors = exports.Config = exports.CommandHelp = exports.Args = exports.Command = exports.flags = exports.args = exports.NodeCrypto = exports.printFlagDeprecation = exports.managementSDKInitiator = exports.managementSDKClient = exports.configHandler = exports.messageHandler = exports.CLIError = exports.cliux = exports.logger = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  var logger_1 = require("./logger");
6
6
  Object.defineProperty(exports, "logger", { enumerable: true, get: function () { return tslib_1.__importDefault(logger_1).default; } });
@@ -14,8 +14,38 @@ var config_handler_1 = require("./config-handler");
14
14
  Object.defineProperty(exports, "configHandler", { enumerable: true, get: function () { return tslib_1.__importDefault(config_handler_1).default; } });
15
15
  var contentstack_management_sdk_1 = require("./contentstack-management-sdk");
16
16
  Object.defineProperty(exports, "managementSDKClient", { enumerable: true, get: function () { return tslib_1.__importDefault(contentstack_management_sdk_1).default; } });
17
+ Object.defineProperty(exports, "managementSDKInitiator", { enumerable: true, get: function () { return contentstack_management_sdk_1.managementSDKInitiator; } });
17
18
  var flag_deprecation_check_1 = require("./flag-deprecation-check");
18
19
  Object.defineProperty(exports, "printFlagDeprecation", { enumerable: true, get: function () { return tslib_1.__importDefault(flag_deprecation_check_1).default; } });
19
20
  tslib_1.__exportStar(require("./http-client"), exports);
20
21
  var encrypter_1 = require("./encrypter");
21
22
  Object.defineProperty(exports, "NodeCrypto", { enumerable: true, get: function () { return tslib_1.__importDefault(encrypter_1).default; } });
23
+ var cli_ux_2 = require("./cli-ux");
24
+ Object.defineProperty(exports, "args", { enumerable: true, get: function () { return cli_ux_2.Args; } });
25
+ Object.defineProperty(exports, "flags", { enumerable: true, get: function () { return cli_ux_2.Flags; } });
26
+ Object.defineProperty(exports, "Command", { enumerable: true, get: function () { return cli_ux_2.Command; } });
27
+ tslib_1.__exportStar(require("./helpers"), exports);
28
+ // NOTE Exporting all @oclif/core modules: So that all the module can be acessed through cli-utility
29
+ var core_1 = require("@oclif/core");
30
+ Object.defineProperty(exports, "Args", { enumerable: true, get: function () { return core_1.Args; } });
31
+ Object.defineProperty(exports, "CommandHelp", { enumerable: true, get: function () { return core_1.CommandHelp; } });
32
+ Object.defineProperty(exports, "Config", { enumerable: true, get: function () { return core_1.Config; } });
33
+ Object.defineProperty(exports, "Errors", { enumerable: true, get: function () { return core_1.Errors; } });
34
+ Object.defineProperty(exports, "Flags", { enumerable: true, get: function () { return core_1.Flags; } });
35
+ Object.defineProperty(exports, "loadHelpClass", { enumerable: true, get: function () { return core_1.loadHelpClass; } });
36
+ Object.defineProperty(exports, "Help", { enumerable: true, get: function () { return core_1.Help; } });
37
+ Object.defineProperty(exports, "HelpBase", { enumerable: true, get: function () { return core_1.HelpBase; } });
38
+ Object.defineProperty(exports, "Interfaces", { enumerable: true, get: function () { return core_1.Interfaces; } });
39
+ Object.defineProperty(exports, "Parser", { enumerable: true, get: function () { return core_1.Parser; } });
40
+ Object.defineProperty(exports, "Plugin", { enumerable: true, get: function () { return core_1.Plugin; } });
41
+ Object.defineProperty(exports, "run", { enumerable: true, get: function () { return core_1.run; } });
42
+ Object.defineProperty(exports, "toCached", { enumerable: true, get: function () { return core_1.toCached; } });
43
+ Object.defineProperty(exports, "tsPath", { enumerable: true, get: function () { return core_1.tsPath; } });
44
+ Object.defineProperty(exports, "toStandardizedId", { enumerable: true, get: function () { return core_1.toStandardizedId; } });
45
+ Object.defineProperty(exports, "toConfiguredId", { enumerable: true, get: function () { return core_1.toConfiguredId; } });
46
+ Object.defineProperty(exports, "settings", { enumerable: true, get: function () { return core_1.settings; } });
47
+ Object.defineProperty(exports, "flush", { enumerable: true, get: function () { return core_1.flush; } });
48
+ Object.defineProperty(exports, "ux", { enumerable: true, get: function () { return core_1.ux; } });
49
+ Object.defineProperty(exports, "execute", { enumerable: true, get: function () { return core_1.execute; } });
50
+ Object.defineProperty(exports, "stderr", { enumerable: true, get: function () { return core_1.stderr; } });
51
+ Object.defineProperty(exports, "stdout", { enumerable: true, get: function () { return core_1.stdout; } });
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@contentstack/cli-utilities",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "description": "Utilities for contentstack projects",
5
5
  "main": "lib/index.js",
6
6
  "types": "./types/index.d.ts",
7
7
  "scripts": {
8
- "prepack": "npm run clean && npm run compile",
9
- "clean": "rm -rf ./lib && rm -rf tsconfig.build.tsbuildinfo",
8
+ "prepack": "pnpm compile",
9
+ "clean": "rm -rf ./lib ./node_modules tsconfig.build.tsbuildinfo",
10
10
  "compile": "tsc -b tsconfig.json",
11
11
  "test:report": "tsc -p test && nyc --reporter=lcov --extension .ts mocha --forbid-only \"test/**/*.test.ts\"",
12
12
  "pretest": "tsc -p test",
@@ -32,14 +32,15 @@
32
32
  "license": "MIT",
33
33
  "dependencies": {
34
34
  "@contentstack/management": "^1.6.1",
35
- "@oclif/core": "^1.21.0",
36
- "axios": "1.1.3",
35
+ "@oclif/core": "^2.3.0",
36
+ "axios": "1.3.4",
37
37
  "chalk": "^4.0.0",
38
38
  "conf": "^10.1.2",
39
39
  "debug": "^4.1.1",
40
40
  "inquirer": "8.2.4",
41
41
  "inquirer-search-checkbox": "^1.0.0",
42
42
  "inquirer-search-list": "^1.2.6",
43
+ "lodash": "^4.17.15",
43
44
  "ora": "^5.4.0",
44
45
  "unique-string": "^2.0.0",
45
46
  "uuid": "^9.0.0",
@@ -54,10 +55,9 @@
54
55
  "@types/mocha": "^8.2.2",
55
56
  "@types/node": "^14.14.32",
56
57
  "@types/sinon": "^10.0.2",
57
- "@types/tar": "^4.0.3",
58
58
  "chai": "^4.3.4",
59
59
  "eslint": "^8.18.0",
60
- "eslint-config-oclif": "^3.1.0",
60
+ "eslint-config-oclif": "^4.0.0",
61
61
  "eslint-config-oclif-typescript": "^0.2.0",
62
62
  "fancy-test": "^2.0.0",
63
63
  "globby": "^10.0.2",
@@ -68,6 +68,7 @@
68
68
  "sinon": "^15.0.1",
69
69
  "tmp": "^0.2.1",
70
70
  "ts-node": "^10.9.1",
71
- "typescript": "^4.9.3"
71
+ "typescript": "^4.9.3",
72
+ "tslib": "^1.13.0"
72
73
  }
73
- }
74
+ }
package/types/cli-ux.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Table } from '@oclif/core/lib/cli-ux';
2
+ import { Args, Flags, Command } from '@oclif/core';
2
3
  import { PrintOptions, InquirePayload, CliUXPromptOptions } from './interfaces';
3
4
  /**
4
5
  * CLI Interface
@@ -8,15 +9,17 @@ declare class CLIInterface {
8
9
  constructor();
9
10
  get uxTable(): typeof Table.table;
10
11
  init(context: any): void;
12
+ registerSearchPlugin(): void;
11
13
  print(message: string, opts?: PrintOptions): void;
12
14
  success(message: string): void;
13
15
  error(message: string, ...params: any): void;
14
16
  loader(message?: string): void;
15
17
  table(data: Record<string, unknown>[], columns: Table.table.Columns<Record<string, unknown>>, options?: Table.table.Options): void;
16
- inquire<T>(inquirePayload: InquirePayload): Promise<T>;
18
+ inquire<T>(inquirePayload: InquirePayload | Array<InquirePayload>): Promise<T>;
17
19
  prompt(name: string, options?: CliUXPromptOptions): Promise<any>;
18
20
  confirm(message?: string): Promise<boolean>;
19
21
  progress(options?: any): any;
20
22
  }
21
23
  declare const _default: CLIInterface;
22
24
  export default _default;
25
+ export { Flags, Args, Command };
@@ -1,3 +1,11 @@
1
- import * as ContentstackManagementSDK from '@contentstack/management';
2
- declare const _default: (config: any) => Promise<ContentstackManagementSDK.ContentstackClient>;
1
+ import { ContentstackClient, ContentstackConfig } from '@contentstack/management';
2
+ declare class ManagementSDKInitiator {
3
+ private analyticsInfo;
4
+ constructor();
5
+ init(context: any): void;
6
+ createAPIClient(config: any): Promise<ContentstackClient>;
7
+ }
8
+ export declare const managementSDKInitiator: ManagementSDKInitiator;
9
+ declare const _default: any;
3
10
  export default _default;
11
+ export { ContentstackConfig, ContentstackClient };
@@ -1,4 +1,4 @@
1
- declare type CryptoConfig = {
1
+ type CryptoConfig = {
2
2
  algorithm?: string;
3
3
  encryptionKey?: string;
4
4
  typeIdentifier?: string;
@@ -0,0 +1 @@
1
+ export declare function isAuthenticated(): boolean;
@@ -225,6 +225,8 @@ export declare class HttpClient {
225
225
  */
226
226
  prepareRequestPayload(): any;
227
227
  }
228
+ export interface HttpRequestConfig extends AxiosRequestConfig {
229
+ }
228
230
  type BodyFormat = 'json' | 'formParams';
229
231
  type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS';
230
232
  export {};
package/types/index.d.ts CHANGED
@@ -3,7 +3,11 @@ export { default as cliux } from './cli-ux';
3
3
  export { default as CLIError } from './cli-error';
4
4
  export { default as messageHandler } from './message-handler';
5
5
  export { default as configHandler } from './config-handler';
6
- export { default as managementSDKClient } from './contentstack-management-sdk';
6
+ export { default as managementSDKClient, managementSDKInitiator, ContentstackClient, ContentstackConfig, } from './contentstack-management-sdk';
7
7
  export { default as printFlagDeprecation } from './flag-deprecation-check';
8
8
  export * from './http-client';
9
9
  export { default as NodeCrypto } from './encrypter';
10
+ export { Args as args, Flags as flags, Command } from './cli-ux';
11
+ export * from './helpers';
12
+ export { Args, CommandHelp, Config, Errors, Flags, loadHelpClass, Help, HelpBase, HelpSection, HelpSectionRenderer, HelpSectionKeyValueTable, Hook, Interfaces, Parser, Plugin, run, toCached, tsPath, toStandardizedId, toConfiguredId, settings, Settings, flush, ux, execute, stderr, stdout, } from '@oclif/core';
13
+ export { FlagInput } from '@oclif/core/lib/interfaces/parser';
@@ -1,13 +1,16 @@
1
1
  import { IPromptOptions } from "@oclif/core/lib/cli-ux";
2
2
  export interface PrintOptions {
3
+ bold?: boolean;
3
4
  color?: string;
4
5
  }
5
6
  export interface InquirePayload {
6
7
  type: string;
7
8
  name: string;
9
+ default?: any;
8
10
  message: string;
9
11
  choices?: Array<any>;
10
12
  transformer?: Function;
13
+ validate?(input: any, answers?: any): boolean | string | Promise<boolean | string>;
11
14
  }
12
15
  export interface Region {
13
16
  name: string;
@@ -1,410 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.chooseDeliveryTokenAlias = exports.chooseTokenAlias = exports.chooseLocale = exports.chooseLocales = exports.chooseEnvironment = exports.chooseEnvironments = exports.chooseContentTypes = exports.chooseEntry = exports.chooseContentType = exports.chooseStack = exports.chooseOrganization = void 0;
4
- const tslib_1 = require("tslib");
5
- const ora_1 = tslib_1.__importDefault(require("ora"));
6
- const cli_error_1 = tslib_1.__importDefault(require("../cli-error"));
7
- const config_handler_1 = tslib_1.__importDefault(require("../config-handler"));
8
- const validations_1 = require("./validations");
9
- const management_1 = tslib_1.__importDefault(require("@contentstack/management"));
10
- const inquirer = require('inquirer');
11
- inquirer.registerPrompt('search-list', require('inquirer-search-list'));
12
- inquirer.registerPrompt('search-checkbox', require('inquirer-search-checkbox'));
13
- let _region;
14
- let _authToken;
15
- let _managementAPIClient;
16
- const region = () => {
17
- if (!_region) {
18
- _region = config_handler_1.default.get('region');
19
- }
20
- return _region;
21
- };
22
- const cmaHost = () => {
23
- let cma = region().cma;
24
- if (cma.startsWith('http')) {
25
- const u = new URL(cma);
26
- if (u.host)
27
- return u.host;
28
- }
29
- return cma;
30
- };
31
- const managementAPIClient = (params) => {
32
- if (params) {
33
- _managementAPIClient = management_1.default.client(params);
34
- }
35
- else if (!_managementAPIClient) {
36
- _managementAPIClient = management_1.default.client({ host: cmaHost() });
37
- }
38
- return _managementAPIClient;
39
- };
40
- const authToken = () => {
41
- if (!_authToken) {
42
- _authToken = config_handler_1.default.get('authtoken');
43
- }
44
- if (!_authToken) {
45
- throw new cli_error_1.default('You are not logged in. Please login with command $ csdx auth:login');
46
- }
47
- return _authToken;
48
- };
49
- function chooseOrganization(client, displayMessage, region, orgUid) {
50
- return new Promise(async (resolve, reject) => {
51
- try {
52
- const spinner = (0, ora_1.default)('Loading Organizations').start();
53
- let { items: organizations } = await client.organization().fetchAll();
54
- spinner.stop();
55
- let orgMap = {};
56
- if (orgUid) {
57
- organizations.forEach((org) => {
58
- orgMap[org.uid] = org.name;
59
- });
60
- if (orgMap[orgUid]) {
61
- resolve({ orgUid: orgUid, orgName: orgMap[orgUid] });
62
- }
63
- else {
64
- return reject(new Error('The given orgUid doesn\'t exist or you might not have access to it.'));
65
- }
66
- }
67
- else {
68
- organizations.forEach((org) => {
69
- orgMap[org.name] = org.uid;
70
- });
71
- const orgList = Object.keys(orgMap);
72
- let inquirerConfig = {
73
- type: 'search-list',
74
- name: 'chosenOrganization',
75
- message: displayMessage || 'Choose an organization',
76
- choices: orgList,
77
- loop: false,
78
- validate: validations_1.shouldNotBeEmpty
79
- };
80
- inquirer.prompt(inquirerConfig).then(({ chosenOrganization }) => {
81
- resolve({ orgUid: orgMap[chosenOrganization], orgName: chosenOrganization });
82
- });
83
- }
84
- }
85
- catch (error) {
86
- reject(error);
87
- }
88
- });
89
- }
90
- exports.chooseOrganization = chooseOrganization;
91
- function chooseStack(client, organizationId, displayMessage, region) {
92
- return new Promise(async (resolve, reject) => {
93
- try {
94
- const spinner = (0, ora_1.default)('Loading Stacks').start();
95
- let { items: stacks } = await client.stack({ organization_uid: organizationId }).query({ query: {} }).find();
96
- spinner.stop();
97
- let stackMap = {};
98
- stacks.forEach((stack) => {
99
- stackMap[stack.name] = stack.api_key;
100
- });
101
- const stackList = Object.keys(stackMap);
102
- let inquirerConfig = {
103
- type: 'search-list',
104
- name: 'chosenStack',
105
- choices: stackList,
106
- message: displayMessage || 'Choose a stack',
107
- loop: false,
108
- };
109
- inquirer.prompt(inquirerConfig).then(({ chosenStack }) => {
110
- resolve({ api_key: stackMap[chosenStack], name: chosenStack });
111
- });
112
- }
113
- catch (error) {
114
- console.error(error.message);
115
- }
116
- });
117
- }
118
- exports.chooseStack = chooseStack;
119
- function chooseContentType(stackApiKey, displayMessage, region) {
120
- return new Promise(async (resolve, reject) => {
121
- const client = managementAPIClient({ host: cmaHost(), authtoken: authToken() });
122
- try {
123
- const spinner = (0, ora_1.default)('Loading Content Types').start();
124
- // let {items: contentTypes} = await client.stack({api_key: stackApiKey}).contentType().query({include_count: true}).find()
125
- let contentTypes = await getAll(client.stack({ api_key: stackApiKey }).contentType());
126
- spinner.stop();
127
- let contentTypeMap = {};
128
- contentTypes.forEach((contentType) => {
129
- contentTypeMap[contentType.title] = contentType.uid;
130
- });
131
- const contentTypeList = Object.keys(contentTypeMap);
132
- let inquirerConfig = {
133
- type: 'search-list',
134
- name: 'chosenContentType',
135
- choices: contentTypeList,
136
- message: displayMessage || 'Choose a content type',
137
- loop: false,
138
- };
139
- inquirer.prompt(inquirerConfig).then(({ chosenContentType }) => {
140
- resolve({ uid: contentTypeMap[chosenContentType], title: chosenContentType });
141
- });
142
- }
143
- catch (error) {
144
- console.error(error.message);
145
- }
146
- });
147
- }
148
- exports.chooseContentType = chooseContentType;
149
- function chooseEntry(contentTypeUid, stackApiKey, displayMessage, region) {
150
- return new Promise(async (resolve, reject) => {
151
- const client = managementAPIClient({ host: cmaHost(), authtoken: authToken() });
152
- try {
153
- const spinner = (0, ora_1.default)('Loading Entries').start();
154
- let entries = await getAll(client.stack({ api_key: stackApiKey }).contentType(contentTypeUid).entry());
155
- spinner.stop();
156
- let entryMap = {};
157
- entries.forEach((entry) => {
158
- entryMap[entry.title] = entry.uid;
159
- });
160
- const entryList = Object.keys(entryMap);
161
- let inquirerConfig = {
162
- type: 'search-list',
163
- name: 'chosenEntry',
164
- choices: entryList,
165
- message: displayMessage || 'Choose an entry',
166
- loop: false
167
- };
168
- inquirer.prompt(inquirerConfig).then(({ chosenEntry }) => {
169
- resolve({ uid: entryMap[chosenEntry], title: chosenEntry });
170
- });
171
- }
172
- catch (error) {
173
- console.error(error.message);
174
- }
175
- });
176
- }
177
- exports.chooseEntry = chooseEntry;
178
- function chooseContentTypes(stack, displayMessage) {
179
- return new Promise(async (resolve, reject) => {
180
- try {
181
- const spinner = (0, ora_1.default)('Loading Content Types').start();
182
- // let {items: contentTypes} = await client.stack({api_key: stackApiKey}).contentType().query({include_count: true}).find()
183
- let contentTypes = await getAll(stack.contentType());
184
- spinner.stop();
185
- let contentTypeMap = {};
186
- contentTypes.forEach((contentType) => {
187
- contentTypeMap[contentType.title] = contentType.uid;
188
- });
189
- const contentTypeList = Object.keys(contentTypeMap);
190
- let inquirerConfig = {
191
- type: 'search-checkbox',
192
- name: 'chosenContentTypes',
193
- choices: contentTypeList,
194
- message: displayMessage || 'Choose a content type',
195
- loop: false,
196
- };
197
- inquirer.prompt(inquirerConfig).then(({ chosenContentTypes }) => {
198
- let result = chosenContentTypes.map(ct => {
199
- let foo = { uid: contentTypeMap[ct], title: ct };
200
- return foo;
201
- });
202
- resolve(result);
203
- });
204
- }
205
- catch (error) {
206
- console.error(error.message);
207
- }
208
- });
209
- }
210
- exports.chooseContentTypes = chooseContentTypes;
211
- function chooseEnvironments(stack, displayMessage) {
212
- return new Promise(async (resolve, reject) => {
213
- try {
214
- const spinner = (0, ora_1.default)('Loading Environments').start();
215
- // let {items: contentTypes} = await client.stack({api_key: stackApiKey}).contentType().query({include_count: true}).find()
216
- let environments = await getAll(stack.environment());
217
- spinner.stop();
218
- let environmentMap = {};
219
- environments.forEach((environment) => {
220
- environmentMap[environment.name] = environment.uid;
221
- });
222
- const environmentList = Object.keys(environmentMap);
223
- let inquirerConfig = {
224
- type: 'search-checkbox',
225
- name: 'chosenEnvironments',
226
- choices: environmentList,
227
- message: displayMessage || 'Choose an environment',
228
- loop: false,
229
- validate: validations_1.shouldNotBeEmpty
230
- };
231
- inquirer.prompt(inquirerConfig).then(({ chosenEnvironments }) => {
232
- let result = chosenEnvironments.map(env => {
233
- let foo = { uid: environmentMap[env], name: env };
234
- return foo;
235
- });
236
- resolve(result);
237
- });
238
- }
239
- catch (error) {
240
- console.error(error.message);
241
- }
242
- });
243
- }
244
- exports.chooseEnvironments = chooseEnvironments;
245
- function chooseEnvironment(stack, displayMessage) {
246
- return new Promise(async (resolve, reject) => {
247
- try {
248
- const spinner = (0, ora_1.default)('Loading Environments').start();
249
- // let {items: contentTypes} = await client.stack({api_key: stackApiKey}).contentType().query({include_count: true}).find()
250
- let environments = await getAll(stack.environment());
251
- spinner.stop();
252
- let environmentMap = {};
253
- environments.forEach((environment) => {
254
- environmentMap[environment.name] = environment.uid;
255
- });
256
- const environmentList = Object.keys(environmentMap);
257
- let inquirerConfig = {
258
- type: 'search-list',
259
- name: 'chosenEnvironment',
260
- choices: environmentList,
261
- message: displayMessage || 'Choose an environment',
262
- loop: false,
263
- validate: validations_1.shouldNotBeEmpty
264
- };
265
- inquirer.prompt(inquirerConfig).then(({ chosenEnvironment }) => {
266
- let result = { uid: environmentMap[chosenEnvironment], name: chosenEnvironment };
267
- resolve(result);
268
- });
269
- }
270
- catch (error) {
271
- console.error(error.message);
272
- }
273
- });
274
- }
275
- exports.chooseEnvironment = chooseEnvironment;
276
- function chooseLocales(stack, displayMessage) {
277
- return new Promise(async (resolve, reject) => {
278
- try {
279
- const spinner = (0, ora_1.default)('Loading Locales').start();
280
- // let {items: contentTypes} = await client.stack({api_key: stackApiKey}).contentType().query({include_count: true}).find()
281
- let locales = await getAll(stack.locale());
282
- spinner.stop();
283
- let localeMap = {};
284
- locales.forEach((locale) => {
285
- localeMap[locale.name] = locale.code;
286
- });
287
- const localeList = Object.keys(localeMap);
288
- let inquirerConfig = {
289
- type: 'search-checkbox',
290
- name: 'chosenLocales',
291
- choices: localeList,
292
- message: displayMessage || 'Choose locales',
293
- loop: false,
294
- validate: validations_1.shouldNotBeEmpty,
295
- };
296
- inquirer.prompt(inquirerConfig).then(({ chosenLocales }) => {
297
- let result = chosenLocales.map(locale => {
298
- let foo = { code: localeMap[locale], name: locale };
299
- return foo;
300
- });
301
- resolve(result);
302
- });
303
- }
304
- catch (error) {
305
- console.error(error.message);
306
- }
307
- });
308
- }
309
- exports.chooseLocales = chooseLocales;
310
- function chooseLocale(stack, displayMessage, defaultLocale) {
311
- return new Promise(async (resolve, reject) => {
312
- try {
313
- const spinner = (0, ora_1.default)('Loading Locales').start();
314
- // let {items: contentTypes} = await client.stack({api_key: stackApiKey}).contentType().query({include_count: true}).find()
315
- let locales = await getAll(stack.locale());
316
- spinner.stop();
317
- let localeMap = {};
318
- locales.forEach((locale) => {
319
- localeMap[locale.name] = locale.code;
320
- });
321
- const localeList = Object.keys(localeMap);
322
- let inquirerConfig = {
323
- type: 'search-list',
324
- name: 'chosenLocale',
325
- choices: localeList,
326
- default: defaultLocale,
327
- message: displayMessage || 'Choose locale',
328
- loop: false,
329
- validate: validations_1.shouldNotBeEmpty
330
- };
331
- inquirer.prompt(inquirerConfig).then(({ chosenLocale }) => {
332
- let result = { code: localeMap[chosenLocale], name: chosenLocale };
333
- resolve(result);
334
- });
335
- }
336
- catch (error) {
337
- console.error(error.message);
338
- }
339
- });
340
- }
341
- exports.chooseLocale = chooseLocale;
342
- function chooseTokenAlias() {
343
- return new Promise(async (resolve, reject) => {
344
- const tokens = config_handler_1.default.get('tokens');
345
- const tokenList = Object.keys(tokens).filter((token) => tokens[token].type === 'management');
346
- let inquirerConfig = {
347
- type: 'search-list',
348
- name: 'chosenToken',
349
- choices: tokenList,
350
- message: 'Choose an alias to use',
351
- loop: false,
352
- validate: validations_1.shouldNotBeEmpty,
353
- };
354
- inquirer.prompt(inquirerConfig).then(({ chosenToken }) => {
355
- resolve({ apiKey: tokens[chosenToken].apiKey, token: tokens[chosenToken].token });
356
- });
357
- });
358
- }
359
- exports.chooseTokenAlias = chooseTokenAlias;
360
- function chooseDeliveryTokenAlias() {
361
- return new Promise(async (resolve, reject) => {
362
- const tokens = config_handler_1.default.get('tokens');
363
- const tokenList = Object.keys(tokens).filter((token) => tokens[token].type === 'delivery');
364
- let inquirerConfig = {
365
- type: 'search-list',
366
- name: 'chosenToken',
367
- choices: tokenList,
368
- message: 'Choose an alias to use',
369
- loop: false,
370
- validate: validations_1.shouldNotBeEmpty,
371
- };
372
- inquirer.prompt(inquirerConfig).then(({ chosenToken }) => {
373
- resolve({ apiKey: tokens[chosenToken].apiKey, token: tokens[chosenToken].token });
374
- });
375
- });
376
- }
377
- exports.chooseDeliveryTokenAlias = chooseDeliveryTokenAlias;
378
- async function getAll(element, skip = 0) {
379
- return new Promise(async (resolve) => {
380
- let result = [];
381
- result = await fetch(element, skip, result);
382
- resolve(result);
383
- });
384
- }
385
- async function fetch(element, skip, accumulator) {
386
- return new Promise(async (resolve) => {
387
- let queryParams = { include_count: true, skip: skip };
388
- let { items: result, count: count } = await element.query(queryParams).find();
389
- accumulator = accumulator.concat(result);
390
- skip += result.length;
391
- if (skip < count)
392
- return resolve(await fetch(element, skip, accumulator));
393
- return resolve(accumulator);
394
- });
395
- }
396
- // async function callMe() {
397
- // // let organization = await chooseOrganization()
398
- // // console.log(organization)
399
- // // let stack = await chooseStack(organization.orgUid)
400
- // // console.log(stack)
401
- // // let contentType = await chooseContentType(stack.api_key)
402
- // // console.log(contentType)
403
- // // let entry = await chooseEntry(contentType.uid, stack.api_key)
404
- // // console.log(entry)
405
- // // let entry = await chooseEntry(contentType.uid, stack.api_key)
406
- // // console.log(entry)
407
- // let token = await chooseTokenAlias()
408
- // console.log(token)
409
- // }
410
- // callMe()
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.shouldNotBeEmpty = void 0;
4
- function shouldNotBeEmpty(input) {
5
- if (input.length === 0)
6
- throw new Error('Please enter a valid value');
7
- return true;
8
- }
9
- exports.shouldNotBeEmpty = shouldNotBeEmpty;
@@ -1,54 +0,0 @@
1
- import { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
2
- import { HttpResponse } from '../src/http-client';
3
-
4
- type BodyFormat = 'json' | 'formParams';
5
-
6
- type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS';
7
-
8
- /**
9
- * CLI HttpClient
10
- */
11
- export declare class HttpClient {
12
- private request: AxiosRequestConfig;
13
- private readonly axiosInstance: AxiosInstance;
14
- constructor();
15
- static create(): HttpClient;
16
- requestConfig(): AxiosRequestConfig;
17
- resetConfig(): HttpClient;
18
- baseUrl(baseUrl: string): HttpClient;
19
- headers(headers: any): HttpClient;
20
- queryParams(queryParams: object): HttpClient;
21
- basicAuth(username: string, password: string): HttpClient;
22
- token(token: string, type: string): HttpClient;
23
- options(options: AxiosRequestConfig): HttpClient;
24
- payload(data: any): HttpClient;
25
- timeout(timeout: number): this;
26
- asJson(): HttpClient;
27
- asFormParams(): HttpClient;
28
- payloadFormat(format: BodyFormat): HttpClient;
29
- accept(accept: string): HttpClient;
30
- acceptJson(): HttpClient;
31
- contentType(contentType: string): HttpClient;
32
- get<R>(url: string, queryParams?: object): Promise<HttpResponse<R>>;
33
- post<R>(url: string, payload?: any): Promise<HttpResponse<R>>;
34
- put<R>(url: string, payload?: any): Promise<HttpResponse<R>>;
35
- patch<R>(url: string, payload?: any): Promise<HttpResponse<R>>;
36
- delete<R>(url: string, queryParams?: object): Promise<HttpResponse<R>>;
37
- send<R>(method: HttpMethod, url: string): Promise<HttpResponse<R>>;
38
- createAndSendRequest(method: HttpMethod, url: string): Promise<AxiosResponse>;
39
- prepareRequestPayload(): any;
40
- }
41
-
42
- /**
43
- * CLI HttpClient
44
- */
45
- export declare class HttpResponse {
46
- private readonly response: AxiosResponse;
47
- constructor();
48
- get status(): number;
49
- get data();
50
- get payload();
51
- get headers();
52
- }
53
-
54
- export interface HttpRequestConfig extends AxiosRequestConfig {}
@@ -1,12 +0,0 @@
1
- import { Token, selectedOrganization, Stack, ContentType, Environment, Entry, Locale } from './interfaces';
2
- export declare function chooseOrganization(client: any, displayMessage?: string, region?: string, orgUid?: string): Promise<selectedOrganization>;
3
- export declare function chooseStack(client: any, organizationId: string, displayMessage?: string, region?: string): Promise<Stack>;
4
- export declare function chooseContentType(stackApiKey: string, displayMessage?: string, region?: string): Promise<ContentType>;
5
- export declare function chooseEntry(contentTypeUid: string, stackApiKey: string, displayMessage?: string, region?: string): Promise<Entry>;
6
- export declare function chooseContentTypes(stack: any, displayMessage?: string): Promise<ContentType[]>;
7
- export declare function chooseEnvironments(stack: any, displayMessage?: string): Promise<Environment[]>;
8
- export declare function chooseEnvironment(stack: any, displayMessage?: string): Promise<Environment>;
9
- export declare function chooseLocales(stack: any, displayMessage?: string): Promise<Locale[]>;
10
- export declare function chooseLocale(stack: any, displayMessage?: string, defaultLocale?: Locale): Promise<Locale>;
11
- export declare function chooseTokenAlias(): Promise<Token>;
12
- export declare function chooseDeliveryTokenAlias(): Promise<Token>;
@@ -1,32 +0,0 @@
1
- export interface Token {
2
- token: string;
3
- apiKey: string;
4
- }
5
- export interface Organization {
6
- uid: string;
7
- name: string;
8
- }
9
- export interface selectedOrganization {
10
- orgUid: string;
11
- orgName: string;
12
- }
13
- export interface Stack {
14
- name: string;
15
- api_key: string;
16
- }
17
- export interface ContentType {
18
- uid: string;
19
- title: string;
20
- }
21
- export interface Environment {
22
- name: string;
23
- uid: string;
24
- }
25
- export interface Entry {
26
- uid: string;
27
- title: string;
28
- }
29
- export interface Locale {
30
- name: string;
31
- code: string;
32
- }
@@ -1 +0,0 @@
1
- export declare function shouldNotBeEmpty(input: any): boolean;