@contentstack/cli-utilities 1.0.2 → 1.0.4

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/src/encrypter.ts DELETED
@@ -1,70 +0,0 @@
1
- import crypto from "crypto";
2
-
3
- type CryptoConfig = {
4
- algorithm?: string;
5
- encryptionKey?: string;
6
- typeIdentifier?: string;
7
- };
8
-
9
- const defaultValues: CryptoConfig = {
10
- typeIdentifier: "◈",
11
- algorithm: "aes-192-cbc",
12
- encryptionKey: "nF2ejRQcTv",
13
- };
14
-
15
- export default class NodeCrypto {
16
- private readonly key: Buffer;
17
- private readonly algorithm: string;
18
- private readonly typeIdentifier: string;
19
-
20
- constructor(config: CryptoConfig = defaultValues) {
21
- const { algorithm, encryptionKey, typeIdentifier } = config;
22
- this.algorithm = algorithm;
23
- this.typeIdentifier = typeIdentifier;
24
- this.key = crypto.scryptSync(encryptionKey, "salt", 24);
25
- }
26
-
27
- encrypt(plainData) {
28
- const iv = crypto.randomBytes(16);
29
- const cipher = crypto.createCipheriv(this.algorithm, this.key, iv);
30
- let data = plainData;
31
-
32
- switch (typeof plainData) {
33
- case "number":
34
- data = `${String(plainData)}${this.typeIdentifier}number`;
35
- break;
36
- case "object":
37
- data = `${JSON.stringify(plainData)}${this.typeIdentifier}object`;
38
- break;
39
- }
40
-
41
- const encrypted = cipher.update(data, "utf8", "hex");
42
-
43
- return [
44
- encrypted + cipher.final("hex"),
45
- Buffer.from(iv).toString("hex"),
46
- ].join("|");
47
- }
48
-
49
- decrypt(encryptedData) {
50
- const [encrypted, iv] = encryptedData.split("|");
51
- if (!iv) throw new Error("IV not found");
52
- const decipher = crypto.createDecipheriv(
53
- this.algorithm,
54
- this.key,
55
- Buffer.from(iv, "hex")
56
- );
57
- const result =
58
- decipher.update(encrypted, "hex", "utf8") + decipher.final("utf8");
59
- const [data, type] = result.split(this.typeIdentifier);
60
-
61
- switch (type) {
62
- case "number":
63
- return Number(data);
64
- case "object":
65
- return JSON.parse(data);
66
- }
67
-
68
- return data;
69
- }
70
- }
@@ -1,41 +0,0 @@
1
- import cliux from './cli-ux';
2
-
3
- /**
4
- * checks the deprecation and prints it
5
- * @param {Array} deprecatedFlags flags to be deprecated
6
- * @param {String} customMessage [optional] a custom message
7
- * @returns flag parser
8
- */
9
- export default function (deprecatedFlags = [], suggestions = [], customMessage?: string) {
10
- return (input, command) => {
11
- const { context: { flagWarningPrintState = {} } = {} } = command
12
- let isCommandHasDeprecationFlag = false;
13
- deprecatedFlags.forEach((item) => {
14
- if (command.argv.indexOf(item) !== -1) {
15
- if (flagWarningPrintState[command.id + item]) {
16
- return input
17
- }
18
- flagWarningPrintState[command.id + item] = true
19
- isCommandHasDeprecationFlag = true;
20
- }
21
- });
22
-
23
- if (isCommandHasDeprecationFlag) {
24
- let depreactionMessage = '';
25
- if (customMessage) {
26
- depreactionMessage = customMessage;
27
- } else {
28
- depreactionMessage = `WARNING!!! You're using the old (soon to be deprecated) Contentstack CLI flags (${deprecatedFlags.join(
29
- ', ',
30
- )}).`;
31
-
32
- if (suggestions.length > 0) {
33
- depreactionMessage += ` We recommend you to use the updated flags (${suggestions.join(', ')}).`;
34
- }
35
- }
36
- cliux.print(depreactionMessage, { color: 'yellow' });
37
- }
38
-
39
- return input;
40
- };
41
- }
@@ -1,369 +0,0 @@
1
- import Axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
2
- import { HttpResponse } from './http-response';
3
-
4
- export class HttpClient {
5
- /**
6
- * The request configuration.
7
- */
8
- private request: AxiosRequestConfig;
9
-
10
- /**
11
- * The request configuration.
12
- */
13
- private readonly axiosInstance: AxiosInstance;
14
-
15
- /**
16
- * The payload format for a JSON or form-url-encoded request.
17
- */
18
- private bodyFormat: BodyFormat = 'json';
19
-
20
- /**
21
- * Createa new pending HTTP request instance.
22
- */
23
- constructor() {
24
- this.request = {};
25
- this.axiosInstance = Axios.create();
26
-
27
- // Sets payload format as json by default
28
- this.asJson();
29
- }
30
-
31
- /**
32
- * Create a reusable HttpClient instance.
33
- *
34
- * @returns {HttpClient}
35
- */
36
- static create(): HttpClient {
37
- return new this();
38
- }
39
-
40
- /**
41
- * Returns the Axios request config.
42
- *
43
- * @returns {AxiosRequestConfig}
44
- */
45
- requestConfig(): AxiosRequestConfig {
46
- return this.request;
47
- }
48
-
49
- /**
50
- * Resets the request config.
51
- *
52
- * @returns {AxiosRequestConfig}
53
- */
54
- resetConfig(): HttpClient {
55
- this.request = {};
56
- return this;
57
- }
58
-
59
- /**
60
- * Use the given `baseUrl` for all requests.
61
- *
62
- * @param {String} baseUrl
63
- *
64
- * @returns {HttpClient}
65
- */
66
- baseUrl(baseUrl: string): HttpClient {
67
- if (typeof baseUrl !== 'string') {
68
- throw new Error(`The base URL must be a string. Received "${typeof baseUrl}"`);
69
- }
70
-
71
- this.request.baseURL = baseUrl;
72
-
73
- return this;
74
- }
75
-
76
- /**
77
- * Add request headers.
78
- * @returns {HttpClient}
79
- */
80
- headers(headers: any): HttpClient {
81
- this.request.headers = { ...this.request.headers, ...headers };
82
-
83
- return this;
84
- }
85
-
86
- /**
87
- * Add query parameters to the request.
88
- *
89
- * @param {Object} queryParams
90
- *
91
- * @returns {HttpClient}
92
- */
93
- queryParams(queryParams: object): HttpClient {
94
- this.request.params = { ...this.request.params, ...queryParams };
95
-
96
- return this;
97
- }
98
-
99
- /**
100
- * Add basic authentication via `username` and `password` to the request.
101
- *
102
- * @param {String} username
103
- * @param {String} password
104
- *
105
- * @returns {HttpClient}
106
- */
107
- basicAuth(username: string, password: string): HttpClient {
108
- this.request.auth = { username, password };
109
-
110
- return this;
111
- }
112
-
113
- /**
114
- * Add an authorization `token` to the request.
115
- *
116
- * @param {String} token
117
- * @param {String} type
118
- *
119
- * @returns {HttpClient}
120
- */
121
- token(token: string, type: string = 'Bearer'): HttpClient {
122
- return this.headers({
123
- Authorization: `${type} ${token}`.trim(),
124
- });
125
- }
126
-
127
- /**
128
- * Merge your own custom Axios options into the request.
129
- *
130
- * @param {Object} options
131
- *
132
- * @returns {HttpClient}
133
- */
134
- options(options: AxiosRequestConfig = {}): HttpClient {
135
- Object.assign(this.request, options);
136
-
137
- return this;
138
- }
139
-
140
- /**
141
- * Add a request payload.
142
- *
143
- * @param {*} data
144
- *
145
- * @returns {HttpClient}
146
- */
147
- payload(data: any): HttpClient {
148
- this.request.data = data;
149
-
150
- return this;
151
- }
152
-
153
- /**
154
- * Define the request `timeout` in milliseconds.
155
- *
156
- * @param {Number} timeout
157
- *
158
- * @returns {HttpClient}
159
- */
160
- timeout(timeout: number): HttpClient {
161
- this.request.timeout = timeout;
162
-
163
- return this;
164
- }
165
-
166
- /**
167
- * Tell HttpClient to send the request as JSON payload.
168
- *
169
- * @returns {HttpClient}
170
- */
171
- asJson(): HttpClient {
172
- return this.payloadFormat('json').contentType('application/json');
173
- }
174
-
175
- /**
176
- * Tell HttpClient to send the request as form parameters,
177
- * encoded as URL query parameters.
178
- *
179
- * @returns {HttpClient}
180
- */
181
- asFormParams(): HttpClient {
182
- return this.payloadFormat('formParams').contentType('application/x-www-form-urlencoded');
183
- }
184
-
185
- /**
186
- * Set the request payload format.
187
- *
188
- * @param {String} format
189
- *
190
- * @returns {HttpClient}
191
- */
192
- payloadFormat(format: BodyFormat): HttpClient {
193
- this.bodyFormat = format;
194
-
195
- return this;
196
- }
197
-
198
- /**
199
- * Set the `Accept` request header. This indicates what
200
- * content type the server should return.
201
- *
202
- * @param {String} accept
203
- *
204
- * @returns {HttpClient}
205
- */
206
- accept(accept: string): HttpClient {
207
- return this.headers({ Accept: accept });
208
- }
209
-
210
- /**
211
- * Set the `Accept` request header to JSON. This indicates
212
- * that the server should return JSON data.
213
- *
214
- * @param {String} accept
215
- *
216
- * @returns {HttpClient}
217
- */
218
- acceptJson(): HttpClient {
219
- return this.accept('application/json');
220
- }
221
-
222
- /**
223
- * Set the `Content-Type` request header.
224
- *
225
- * @param {String} contentType
226
- *
227
- * @returns {HttpClient}
228
- */
229
- contentType(contentType: string): HttpClient {
230
- return this.headers({ 'Content-Type': contentType });
231
- }
232
-
233
- /**
234
- * Send an HTTP GET request, optionally with the given `queryParams`.
235
- *
236
- * @param {String} url
237
- * @param {Object} queryParams
238
- *
239
- * @returns {HttpResponse}
240
- *
241
- * @throws
242
- */
243
- async get<R>(url: string, queryParams: object = {}): Promise<HttpResponse<R>> {
244
- this.queryParams(queryParams);
245
-
246
- return this.send<R>('GET', url);
247
- }
248
-
249
- /**
250
- * Send an HTTP POST request, optionally with the given `payload`.
251
- *
252
- * @param {String} url
253
- * @param {Object} payload
254
- *
255
- * @returns {HttpResponse}
256
- *
257
- * @throws
258
- */
259
- async post<R>(url: string, payload?: any): Promise<HttpResponse<R>> {
260
- if (payload) {
261
- this.payload(payload);
262
- }
263
-
264
- return this.send<R>('POST', url);
265
- }
266
-
267
- /**
268
- * Send an HTTP PUT request, optionally with the given `payload`.
269
- *
270
- * @param {String} url
271
- * @param {Object} payload
272
- *
273
- * @returns {HttpResponse}
274
- *
275
- * @throws
276
- */
277
- async put<R>(url: string, payload?: any): Promise<HttpResponse<R>> {
278
- if (payload) {
279
- this.payload(payload);
280
- }
281
-
282
- return this.send<R>('PUT', url);
283
- }
284
-
285
- /**
286
- * Send an HTTP PATCH request, optionally with the given `payload`.
287
- *
288
- * @param {String} url
289
- * @param {Object} payload
290
- *
291
- * @returns {HttpResponse}
292
- *
293
- * @throws
294
- */
295
- async patch<R>(url: string, payload?: any): Promise<HttpResponse<R>> {
296
- if (payload) {
297
- this.payload(payload);
298
- }
299
-
300
- return this.send<R>('PATCH', url);
301
- }
302
-
303
- /**
304
- * Send an HTTP DELETE request, optionally with the given `queryParams`.
305
- *
306
- * @param {String} url
307
- * @param {Object} queryParams
308
- *
309
- * @returns {HttpResponse}
310
- *
311
- * @throws
312
- */
313
- async delete<R>(url: string, queryParams: object = {}): Promise<HttpResponse<R>> {
314
- this.queryParams(queryParams);
315
-
316
- return this.send<R>('DELETE', url);
317
- }
318
-
319
- /**
320
- * Send the HTTP request.
321
- *
322
- * @param {String} method
323
- * @param {String} url
324
- *
325
- * @returns {HttpResponse}
326
- *
327
- * @throws
328
- */
329
- async send<R>(method: HttpMethod, url: string): Promise<HttpResponse<R>> {
330
- try {
331
- return new HttpResponse<R>(await this.createAndSendRequest(method, url));
332
- } catch (error: any) {
333
- if (error.response) {
334
- return new HttpResponse(error.response);
335
- }
336
-
337
- throw error;
338
- }
339
- }
340
-
341
- /**
342
- * Create and send the HTTP request.
343
- *
344
- * @param {String} method
345
- * @param {String} url
346
- *
347
- * @returns {Request}
348
- */
349
- async createAndSendRequest(method: HttpMethod, url: string): Promise<AxiosResponse> {
350
- return await this.axiosInstance({
351
- url,
352
- method,
353
- withCredentials: true,
354
- ...this.request,
355
- data: this.prepareRequestPayload(),
356
- });
357
- }
358
-
359
- /**
360
- * Returns the request payload depending on the selected request payload format.
361
- */
362
- prepareRequestPayload(): any {
363
- return this.bodyFormat === 'formParams' ? new URLSearchParams(this.request.data).toString() : this.request.data;
364
- }
365
- }
366
-
367
- type BodyFormat = 'json' | 'formParams';
368
-
369
- type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS';
@@ -1,55 +0,0 @@
1
- 'use strict';
2
-
3
- import { AxiosResponse } from 'axios';
4
-
5
- export class HttpResponse<ResponseType = any> {
6
- /**
7
- * The Axios response object.
8
- */
9
- private readonly response: AxiosResponse;
10
-
11
- /**
12
- * Wrap the given Axios `response` into a new response instance.
13
- *
14
- * @param {AxiosResponse} response
15
- */
16
- constructor(response: AxiosResponse) {
17
- this.response = response;
18
- }
19
-
20
- /**
21
- * Returns the response status.
22
- *
23
- * @returns {Number}
24
- */
25
- get status() {
26
- return this.response.status;
27
- }
28
-
29
- /**
30
- * Returns the response payload. This method is an alias for `response.payload()`.
31
- *
32
- * @returns {*}
33
- */
34
- get data() {
35
- return this.payload;
36
- }
37
-
38
- /**
39
- * Returns the response payload.
40
- *
41
- * @returns {*}
42
- */
43
- get payload() {
44
- return this.response.data;
45
- }
46
-
47
- /**
48
- * Returns the response headers.
49
- *
50
- * @returns {Object}
51
- */
52
- get headers() {
53
- return this.response.headers;
54
- }
55
- }
@@ -1,7 +0,0 @@
1
- 'use strict';
2
-
3
- import { HttpClient } from './client';
4
-
5
- export default HttpClient;
6
- export * from './client';
7
- export * from './http-response';
package/src/index.ts DELETED
@@ -1,9 +0,0 @@
1
- export { default as logger } from './logger';
2
- export { default as cliux } from './cli-ux';
3
- export { default as CLIError } from './cli-error';
4
- export { default as messageHandler } from './message-handler';
5
- export { default as configHandler } from './config-handler';
6
- export { default as printFlagDeprecation } from './flag-deprecation-check';
7
- export * from './http-client';
8
- export { default as NodeCrypto } from './encrypter'
9
- export { chooseLocale as chooseLocalePrompt } from './selectors';
@@ -1,61 +0,0 @@
1
- import { IPromptOptions } from "@oclif/core/lib/cli-ux";
2
-
3
- export interface PrintOptions {
4
- color?: string;
5
- }
6
-
7
- export interface InquirePayload {
8
- type: string;
9
- name: string;
10
- message: string;
11
- choices?: Array<any>;
12
- transformer?: Function;
13
- }
14
-
15
- export interface Region {
16
- name: string;
17
- cma: string;
18
- cda: string;
19
- }
20
-
21
- export interface Token {
22
- token: string;
23
- apiKey: string;
24
- }
25
-
26
- export interface Organization {
27
- uid: string,
28
- name: string,
29
- }
30
-
31
- export interface selectedOrganization {
32
- orgUid: string,
33
- orgName: string,
34
- }
35
-
36
- export interface Stack {
37
- name: string,
38
- api_key: string,
39
- }
40
-
41
- export interface ContentType {
42
- uid: string,
43
- title: string,
44
- }
45
-
46
- export interface Environment {
47
- name: string,
48
- uid: string,
49
- }
50
-
51
- export interface Entry {
52
- uid: string,
53
- title: string,
54
- }
55
-
56
- export interface Locale {
57
- name: string;
58
- code: string;
59
- }
60
-
61
- export interface CliUXPromptOptions extends IPromptOptions {}
package/src/logger.ts DELETED
@@ -1,101 +0,0 @@
1
- import winston from 'winston';
2
- import messageHandler from './message-handler';
3
-
4
- class LoggerService {
5
- name: string;
6
- data: object | null;
7
- logger: winston.Logger;
8
-
9
- static dateFormat(): string {
10
- return new Date(Date.now()).toUTCString();
11
- }
12
- constructor(name: string) {
13
- this.data = null;
14
- this.name = null;
15
-
16
- const logger = winston.createLogger({
17
- transports: [
18
- // new winston.transports.Console(),
19
- new winston.transports.File({
20
- filename: `./logs/${name}.log`,
21
- }),
22
- ],
23
- format: winston.format.combine(
24
- winston.format.colorize(),
25
- winston.format.printf((info) => {
26
- let stringifiedParam;
27
- try {
28
- stringifiedParam = JSON.stringify(info.obj);
29
- } catch (error) {
30
- console.log('warning: failed to log the result');
31
- }
32
- // parse message
33
- info.message = messageHandler.parse(info.message);
34
- let message = `${LoggerService.dateFormat()}:${name}:${info.level}:${info.message}`;
35
- message = info.obj ? message + `:${stringifiedParam}` : message;
36
- message = this.data ? message + `:${JSON.stringify(this.data)}` : message;
37
- return message;
38
- }),
39
- ),
40
- // level: (config.get('logger.level') as string) || 'error',
41
- level: 'error',
42
- silent: true
43
- // silent: config.get('logger.enabled') && process.env.CLI_ENV !== 'TEST' ? false : false,
44
- });
45
- this.logger = logger;
46
- }
47
-
48
- init(context) {
49
- this.name = (context && context.plugin && context.plugin.name) || 'cli';
50
- }
51
-
52
- set loggerName(name: string) {
53
- this.name = name;
54
- }
55
-
56
- setLogData(data: object): void {
57
- this.data = data;
58
- }
59
-
60
- async info(message: string, param?: any): Promise<any> {
61
- if (param) {
62
- this.logger.log('info', message, {
63
- obj: param,
64
- });
65
- } else {
66
- this.logger.log('info', message);
67
- }
68
- }
69
-
70
- async debug(message: string, param?: any): Promise<any> {
71
- if (param) {
72
- this.logger.log('debug', message, {
73
- obj: param,
74
- });
75
- } else {
76
- this.logger.log('debug', message);
77
- }
78
- }
79
-
80
- async error(message: string, param?: any): Promise<any> {
81
- if (param) {
82
- this.logger.log('error', message, {
83
- obj: param,
84
- });
85
- } else {
86
- this.logger.log('error', message);
87
- }
88
- }
89
-
90
- async warn(message: string, param?: any): Promise<any> {
91
- if (param) {
92
- this.logger.log('warn', message, {
93
- obj: param,
94
- });
95
- } else {
96
- this.logger.log('warn', message);
97
- }
98
- }
99
- }
100
-
101
- export default new LoggerService('cli');