mstate-cli 0.4.3 → 0.4.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.
@@ -1,94 +1,94 @@
1
- import * as fs from 'fs';
2
- import path from 'path';
3
- import { MSTATE_URL } from '../common/constant';
4
- import { getValueFromArgs, sortJSON } from '../common/helpers';
5
- import { customLog, getSecretKey } from '../common/utils';
6
- import { Variables } from 'src/common/enum';
7
-
8
- class ActionHandler {
9
- constructor() {}
10
-
11
- async cloneActions() {
12
- const workflowName = getValueFromArgs(Variables.WORKFLOW, true);
13
- const secretKey = getSecretKey();
14
-
15
- let query = `?workflow=${workflowName}`;
16
- const url = `${MSTATE_URL}/action/config/all/${query}`;
17
-
18
- const responseJSON = await fetch(url, {
19
- headers: {
20
- 'Content-Type': 'application/json',
21
- 'secret-key': secretKey,
22
- },
23
- });
24
-
25
- const response = await responseJSON.json();
26
- if (response?.errors) {
27
- customLog.changeAndThrow(
28
- 'Invalid Parameters for Action: ',
29
- ...response?.errors,
30
- );
31
- } else {
32
- const actionConfigs = sortJSON(response?.data);
33
-
34
- const folderPath = path.resolve(workflowName, 'actions');
35
- fs.mkdirSync(folderPath, { recursive: true });
36
-
37
- actionConfigs.forEach((config: ActionConfig) => {
38
- try {
39
- const file = path.join(folderPath, `${config?.name}.json`);
40
- fs.writeFileSync(file, JSON.stringify(config, null, 2));
41
-
42
- customLog.success(
43
- 'file created at',
44
- folderPath,
45
- `${config?.name}.json`,
46
- );
47
- } catch (error: any) {
48
- customLog.error(error.message);
49
- }
50
- });
51
- }
52
- }
53
-
54
- async saveToDB() {
55
- const workflowName = getValueFromArgs(Variables.WORKFLOW, true);
56
- const secretKey = getSecretKey();
57
-
58
- const folderPath = path.resolve(workflowName, 'actions');
59
-
60
- let query = `?workflow=${workflowName}`;
61
- // loop to every folder to publish workflow
62
- fs.readdir(folderPath, (err, files) => {
63
- if (!files) return;
64
-
65
- files.forEach(async (fileName) => {
66
- const filePath = path.join(folderPath, fileName);
67
- const data = fs.readFileSync(filePath, 'utf8');
68
-
69
- const url = `${MSTATE_URL}/action/config/${query}`;
70
- const responseJSON = await fetch(url, {
71
- method: 'PUT',
72
- headers: {
73
- 'secret-key': secretKey,
74
- 'Content-Type': 'application/json',
75
- },
76
- body: data,
77
- });
78
- const response = await responseJSON.json();
79
-
80
- const actionConfig = JSON.parse(data) as ActionConfig;
81
- if (response?.errors) {
82
- customLog.error(
83
- `Invalid Parameters for Action ${actionConfig.name}: `,
84
- ...response?.errors,
85
- );
86
- } else {
87
- customLog.success(`Action ${actionConfig.name} Updated successfully`);
88
- }
89
- });
90
- });
91
- }
92
- }
93
-
94
- export const actionHandler = new ActionHandler();
1
+ import * as fs from 'fs';
2
+ import path from 'path';
3
+ import { MSTATE_URL } from '../common/constant';
4
+ import { getValueFromArgs, sortJSON } from '../common/helpers';
5
+ import { customLog, getSecretKey } from '../common/utils';
6
+ import { Variables } from 'src/common/enum';
7
+
8
+ class ActionHandler {
9
+ constructor() {}
10
+
11
+ async cloneActions() {
12
+ const workflowName = getValueFromArgs(Variables.WORKFLOW, true);
13
+ const secretKey = getSecretKey();
14
+
15
+ let query = `?workflow=${workflowName}&hasNickName=${true}`;
16
+ const url = `${MSTATE_URL}/action/config/all/${query}`;
17
+
18
+ const responseJSON = await fetch(url, {
19
+ headers: {
20
+ 'Content-Type': 'application/json',
21
+ 'secret-key': secretKey,
22
+ },
23
+ });
24
+
25
+ const response = await responseJSON.json();
26
+ if (response?.errors) {
27
+ customLog.changeAndThrow(
28
+ 'Invalid Parameters for Action: ',
29
+ ...response?.errors,
30
+ );
31
+ } else {
32
+ const actionConfigs = sortJSON(response?.data);
33
+
34
+ const folderPath = path.resolve(workflowName, 'actions');
35
+ fs.mkdirSync(folderPath, { recursive: true });
36
+
37
+ actionConfigs.forEach((config: ActionConfig) => {
38
+ try {
39
+ const file = path.join(folderPath, `${config?.name}.json`);
40
+ fs.writeFileSync(file, JSON.stringify(config, null, 2));
41
+
42
+ customLog.success(
43
+ 'file created at',
44
+ folderPath,
45
+ `${config?.name}.json`,
46
+ );
47
+ } catch (error: any) {
48
+ customLog.error(error.message);
49
+ }
50
+ });
51
+ }
52
+ }
53
+
54
+ async saveToDB() {
55
+ const workflowName = getValueFromArgs(Variables.WORKFLOW, true);
56
+ const secretKey = getSecretKey();
57
+
58
+ const folderPath = path.resolve(workflowName, 'actions');
59
+
60
+ let query = `?workflow=${workflowName}`;
61
+ // loop to every folder to publish workflow
62
+ fs.readdir(folderPath, (err, files) => {
63
+ if (!files) return;
64
+
65
+ files.forEach(async (fileName) => {
66
+ const filePath = path.join(folderPath, fileName);
67
+ const data = fs.readFileSync(filePath, 'utf8');
68
+
69
+ const url = `${MSTATE_URL}/action/config/${query}`;
70
+ const responseJSON = await fetch(url, {
71
+ method: 'PUT',
72
+ headers: {
73
+ 'secret-key': secretKey,
74
+ 'Content-Type': 'application/json',
75
+ },
76
+ body: data,
77
+ });
78
+ const response = await responseJSON.json();
79
+
80
+ const actionConfig = JSON.parse(data) as ActionConfig;
81
+ if (response?.errors) {
82
+ customLog.error(
83
+ `Invalid Parameters for Action ${actionConfig.name}: `,
84
+ ...response?.errors,
85
+ );
86
+ } else {
87
+ customLog.success(`Action ${actionConfig.name} Updated successfully`);
88
+ }
89
+ });
90
+ });
91
+ }
92
+ }
93
+
94
+ export const actionHandler = new ActionHandler();
@@ -1,202 +1,226 @@
1
- import { MSTATE_DOMAIN, MSTATE_URL } from '../common/constant';
2
- import {
3
- customLog,
4
- getSecretKey,
5
- handleUpdateSecretKey,
6
- } from '../common/utils';
7
- import { getValueFromArgs } from '../common/helpers';
8
-
9
- import open from 'open';
10
- import express from 'express';
11
- import cors from 'cors';
12
- import { Variables } from 'src/common/enum';
13
-
14
- class CompanyHandler {
15
- constructor() {}
16
-
17
- async addToken() {
18
- const pString = getValueFromArgs(Variables.PERMISSIONS).trim();
19
- const permissions = pString.split(',').map((s) => s.trim());
20
- const secretKey = getSecretKey();
21
- const user = getValueFromArgs(Variables.USER_ID, true);
22
- const companyID = getValueFromArgs(Variables.COMPANY_ID, true);
23
-
24
- if (!permissions.length && permissions[0]?.length) {
25
- customLog.changeAndThrow(`Parameter permissions is required`);
26
- return;
27
- }
28
-
29
- const url = `${MSTATE_URL}/company/permission`;
30
- const responseJSON = await fetch(url, {
31
- method: 'POST',
32
- headers: {
33
- 'secret-key': secretKey,
34
- 'Content-Type': 'application/json',
35
- },
36
- body: JSON.stringify({
37
- user,
38
- permissions,
39
- company: companyID,
40
- }),
41
- });
42
-
43
- const response = await responseJSON.json();
44
- if (response?.errors) {
45
- customLog.changeAndThrow(
46
- 'Invalid Parameters for Company: ',
47
- ...response?.errors,
48
- );
49
- } else {
50
- customLog.success('Company updated successfully \n', response?.data);
51
- }
52
- }
53
-
54
- async addUser() {
55
- const secretKey = getSecretKey();
56
- const name = getValueFromArgs(Variables.USER_ID, true);
57
- const email = getValueFromArgs(Variables.EMAIL, true);
58
- const phone = getValueFromArgs(Variables.PHONE, true);
59
-
60
- const url = `${MSTATE_URL}/um/user`;
61
- const responseJSON = await fetch(url, {
62
- method: 'POST',
63
- headers: {
64
- 'secret-key': secretKey,
65
- 'Content-Type': 'application/json',
66
- },
67
- body: JSON.stringify({
68
- name,
69
- username: name,
70
- email,
71
- password: '123',
72
- phone,
73
- }),
74
- });
75
-
76
- const response = await responseJSON.json();
77
- if (response?.errors) {
78
- customLog.changeAndThrow(
79
- 'Invalid Parameters for Company: ',
80
- ...response?.errors,
81
- );
82
- } else {
83
- customLog.success('User Updated successfully \n', response?.data);
84
- }
85
- }
86
-
87
- async revokePermission() {
88
- const pString = getValueFromArgs(Variables.PERMISSIONS);
89
- const permissions = pString.split(',').map((s) => s.trim());
90
- const secretKey = getSecretKey();
91
- const user = getValueFromArgs(Variables.USER_ID, true);
92
- const companyID = getValueFromArgs(Variables.COMPANY_ID, true);
93
-
94
- if (!permissions.length && permissions[0]?.length) {
95
- customLog.changeAndThrow(`Parameter permissions is required`);
96
- return;
97
- }
98
-
99
- const url = `${MSTATE_URL}/company/permission`;
100
- const responseJSON = await fetch(url, {
101
- method: 'DELETE',
102
- headers: {
103
- 'secret-key': secretKey,
104
- 'Content-Type': 'application/json',
105
- },
106
- body: JSON.stringify({
107
- company: companyID,
108
- user,
109
- permissions,
110
- }),
111
- });
112
-
113
- const response = await responseJSON.json();
114
- if (response?.errors) {
115
- customLog.changeAndThrow(
116
- 'Invalid Parameters for Company: ',
117
- ...response?.errors,
118
- );
119
- } else {
120
- customLog.success('Company updated successfully \n', response?.data);
121
- }
122
- }
123
-
124
- async handleLogin() {
125
- // Start the login process
126
- let port = 49152;
127
- const app = express();
128
- app.use(cors({ origin: '*' }));
129
-
130
- async function login() {
131
- console.log('Opening browser for authentication...');
132
-
133
- // Start a local server to capture the token
134
-
135
- const startServer = (port: number) => {
136
- return app.listen(port, () => {
137
- console.log(`Waiting for browser response...`);
138
- });
139
- };
140
-
141
- const server = startServer(port);
142
-
143
- server.on('error', (err: any) => {
144
- if (err.code === 'EADDRINUSE') {
145
- console.log(`Port ${port} is in use. Trying another port...`);
146
-
147
- startServer(++port);
148
- } else {
149
- console.error('Server error:', err);
150
- }
151
- });
152
-
153
- // Capture the OAuth callback
154
- app.get('/cli/mstate/login', (req, res) => {
155
- try {
156
- const { token } = req.query;
157
-
158
- if (token) {
159
- console.log('Authentication successful!');
160
-
161
- // Save the token locally
162
- handleUpdateSecretKey(token as string);
163
-
164
- res.send('<h1>Login successful! You can close this window.</h1>');
165
- } else {
166
- console.error('Authentication failed.');
167
- res.send('<h1>Authentication failed. Please try again.</h1>');
168
- }
169
- } catch (error) {
170
- } finally {
171
- server.close(); // Stop the server after handling the response
172
- }
173
- });
174
- }
175
-
176
- // Command handling
177
- login()
178
- .then(async () => {
179
- await open(
180
- MSTATE_DOMAIN +
181
- `/oauth?redirect=${encodeURIComponent(
182
- 'cli/mstate/login',
183
- )}&open=${port}&scope=profile`,
184
- );
185
- })
186
- .catch((err) => {
187
- console.error('Error during login:', err.message);
188
- process.exit(1);
189
- });
190
- }
191
-
192
- handleUpdateSavedSecretKey() {
193
- handleUpdateSecretKey(getSecretKey());
194
- }
195
-
196
- logToken() {
197
- customLog.info('MSTATE_URL', MSTATE_URL);
198
- customLog.info('Token', getSecretKey());
199
- }
200
- }
201
-
202
- export const companyHandler = new CompanyHandler();
1
+ import { MSTATE_DOMAIN, MSTATE_URL } from '../common/constant';
2
+ import {
3
+ customLog,
4
+ getSecretKey,
5
+ handleUpdateSecretKey,
6
+ } from '../common/utils';
7
+ import { getValueFromArgs } from '../common/helpers';
8
+
9
+ import open from 'open';
10
+ import express from 'express';
11
+ import cors from 'cors';
12
+ import { Variables } from 'src/common/enum';
13
+
14
+ class CompanyHandler {
15
+ constructor() {}
16
+
17
+ async addToken() {
18
+ const pString = getValueFromArgs(Variables.PERMISSIONS).trim();
19
+ const permissions = pString.split(',').map((s) => s.trim());
20
+ const secretKey = getSecretKey();
21
+ const user = getValueFromArgs(Variables.USER_ID, true);
22
+ const companyID = getValueFromArgs(Variables.COMPANY_ID, true);
23
+
24
+ if (!permissions.length && permissions[0]?.length) {
25
+ customLog.changeAndThrow(`Parameter permissions is required`);
26
+ return;
27
+ }
28
+
29
+ const url = `${MSTATE_URL}/company/permission`;
30
+ const responseJSON = await fetch(url, {
31
+ method: 'POST',
32
+ headers: {
33
+ 'secret-key': secretKey,
34
+ 'Content-Type': 'application/json',
35
+ },
36
+ body: JSON.stringify({
37
+ user,
38
+ permissions,
39
+ company: companyID,
40
+ }),
41
+ });
42
+
43
+ const response = await responseJSON.json();
44
+ if (response?.errors) {
45
+ customLog.changeAndThrow(
46
+ 'Invalid Parameters for Company: ',
47
+ ...response?.errors,
48
+ );
49
+ } else {
50
+ customLog.success('Company updated successfully \n', response?.data);
51
+ }
52
+ }
53
+
54
+ async addUser() {
55
+ const secretKey = getSecretKey();
56
+ const name = getValueFromArgs(Variables.USER_ID, true);
57
+ const email = getValueFromArgs(Variables.EMAIL, true);
58
+ const phone = getValueFromArgs(Variables.PHONE, true);
59
+
60
+ const url = `${MSTATE_URL}/um/user`;
61
+ const responseJSON = await fetch(url, {
62
+ method: 'POST',
63
+ headers: {
64
+ 'secret-key': secretKey,
65
+ 'Content-Type': 'application/json',
66
+ },
67
+ body: JSON.stringify({
68
+ name,
69
+ username: name,
70
+ email,
71
+ password: '123',
72
+ phone,
73
+ }),
74
+ });
75
+
76
+ const response = await responseJSON.json();
77
+ if (response?.errors) {
78
+ customLog.changeAndThrow(
79
+ 'Invalid Parameters for Company: ',
80
+ ...response?.errors,
81
+ );
82
+ } else {
83
+ customLog.success('User Updated successfully \n', response?.data);
84
+ }
85
+ }
86
+
87
+ async revokePermission() {
88
+ const pString = getValueFromArgs(Variables.PERMISSIONS);
89
+ const permissions = pString.split(',').map((s) => s.trim());
90
+ const secretKey = getSecretKey();
91
+ const user = getValueFromArgs(Variables.USER_ID, true);
92
+ const companyID = getValueFromArgs(Variables.COMPANY_ID, true);
93
+
94
+ if (!permissions.length && permissions[0]?.length) {
95
+ customLog.changeAndThrow(`Parameter permissions is required`);
96
+ return;
97
+ }
98
+
99
+ const url = `${MSTATE_URL}/company/permission`;
100
+ const responseJSON = await fetch(url, {
101
+ method: 'DELETE',
102
+ headers: {
103
+ 'secret-key': secretKey,
104
+ 'Content-Type': 'application/json',
105
+ },
106
+ body: JSON.stringify({
107
+ company: companyID,
108
+ user,
109
+ permissions,
110
+ }),
111
+ });
112
+
113
+ const response = await responseJSON.json();
114
+ if (response?.errors) {
115
+ customLog.changeAndThrow(
116
+ 'Invalid Parameters for Company: ',
117
+ ...response?.errors,
118
+ );
119
+ } else {
120
+ customLog.success('Company updated successfully \n', response?.data);
121
+ }
122
+ }
123
+
124
+ async handleLogin() {
125
+ // Start the login process
126
+ let port = 49152;
127
+ const app = express();
128
+ app.use(cors({ origin: '*' }));
129
+
130
+ async function login() {
131
+ console.log('Opening browser for authentication...');
132
+
133
+ // Start a local server to capture the token
134
+
135
+ const startServer = (port: number) => {
136
+ return app.listen(port, () => {
137
+ console.log(`Waiting for browser response...`);
138
+ });
139
+ };
140
+
141
+ const server = startServer(port);
142
+
143
+ server.on('error', (err: any) => {
144
+ if (err.code === 'EADDRINUSE') {
145
+ console.log(`Port ${port} is in use. Trying another port...`);
146
+
147
+ startServer(++port);
148
+ } else {
149
+ console.error('Server error:', err);
150
+ }
151
+ });
152
+
153
+ // Capture the OAuth callback
154
+ app.get('/cli/mstate/login', (req, res) => {
155
+ try {
156
+ const { token } = req.query;
157
+
158
+ if (token) {
159
+ console.log('Authentication successful!');
160
+
161
+ // Save the token locally
162
+ handleUpdateSecretKey(token as string);
163
+
164
+ res.send('<h1>Login successful! You can close this window.</h1>');
165
+ } else {
166
+ console.error('Authentication failed.');
167
+ res.send('<h1>Authentication failed. Please try again.</h1>');
168
+ }
169
+ } catch (error) {
170
+ } finally {
171
+ server.close(); // Stop the server after handling the response
172
+ }
173
+ });
174
+ }
175
+
176
+ // Command handling
177
+ login()
178
+ .then(async () => {
179
+ await open(
180
+ MSTATE_DOMAIN +
181
+ `/oauth?redirect=${encodeURIComponent(
182
+ 'cli/mstate/login',
183
+ )}&open=${port}&scope=profile`,
184
+ );
185
+ })
186
+ .catch((err) => {
187
+ console.error('Error during login:', err.message);
188
+ process.exit(1);
189
+ });
190
+ }
191
+
192
+ handleUpdateSavedSecretKey() {
193
+ handleUpdateSecretKey(getSecretKey());
194
+ }
195
+
196
+ async logInfo() {
197
+ const secretKey = getSecretKey();
198
+
199
+ try {
200
+ const url = `${MSTATE_URL}/company/info`;
201
+ const responseJSON = await fetch(url, {
202
+ headers: {
203
+ 'Content-Type': 'application/json',
204
+ 'secret-key': secretKey,
205
+ },
206
+ });
207
+
208
+ const response = await responseJSON.json();
209
+ if (response?.errors) {
210
+ customLog.changeAndThrow(
211
+ 'Invalid Parameters for Action: ',
212
+ ...response?.errors,
213
+ );
214
+ } else {
215
+ customLog.info('COMPANY', response?.data?.name);
216
+ }
217
+ } catch (error: any) {
218
+ customLog.error(error.message);
219
+ }
220
+
221
+ customLog.info('MSTATE_URL', MSTATE_URL);
222
+ customLog.info('Token', getSecretKey());
223
+ }
224
+ }
225
+
226
+ export const companyHandler = new CompanyHandler();