@opencrvs/toolkit 2.0.0-rc.d1ea58b → 2.0.0-rc.d23bb0b

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.
Files changed (101) hide show
  1. package/README.md +14 -0
  2. package/build.sh +3 -2
  3. package/create-countryconfig/index.js +50 -20
  4. package/create-countryconfig/package.json +12 -2
  5. package/dist/application-config/index.js +257 -94
  6. package/dist/cli.js +3166 -45
  7. package/dist/commons/api/router.d.ts +109 -21
  8. package/dist/commons/application-config/index.d.ts +1 -0
  9. package/dist/commons/conditionals/conditionals.d.ts +354 -4
  10. package/dist/commons/conditionals/validate.d.ts +51 -2
  11. package/dist/commons/events/ActionConfig.d.ts +28 -2
  12. package/dist/commons/events/ActionDocument.d.ts +6 -0
  13. package/dist/commons/events/ActionInput.d.ts +42 -36
  14. package/dist/commons/events/AdvancedSearchConfig.d.ts +342 -0
  15. package/dist/commons/events/CountryConfigQueryInput.d.ts +42 -0
  16. package/dist/commons/events/Draft.d.ts +2 -3
  17. package/dist/commons/events/EventDocument.d.ts +3 -0
  18. package/dist/commons/events/EventIndex.d.ts +14 -0
  19. package/dist/commons/events/FieldConfig.d.ts +378 -50
  20. package/dist/commons/events/FieldType.d.ts +1 -0
  21. package/dist/commons/events/FieldTypeMapping.d.ts +1 -1
  22. package/dist/commons/events/FieldValue.d.ts +6 -0
  23. package/dist/commons/events/WorkqueueConfig.d.ts +189 -150
  24. package/dist/commons/events/field.d.ts +53 -1
  25. package/dist/commons/events/index.d.ts +2 -0
  26. package/dist/commons/events/state/flags.d.ts +16 -0
  27. package/dist/commons/events/state/utils.d.ts +12 -287
  28. package/dist/commons/events/utils.d.ts +12 -1
  29. package/dist/conditionals/index.js +52 -1
  30. package/dist/environment/custom-types.d.ts +33 -0
  31. package/dist/environment/custom-types.d.ts.map +1 -0
  32. package/dist/environment/custom-types.js +12 -0
  33. package/dist/environment/derived-variables.d.ts +134 -0
  34. package/dist/environment/derived-variables.d.ts.map +1 -0
  35. package/dist/environment/derived-variables.js +169 -0
  36. package/dist/environment/editor-questions.d.ts +4 -0
  37. package/dist/environment/editor-questions.d.ts.map +1 -0
  38. package/dist/environment/editor-questions.js +65 -0
  39. package/dist/environment/git.d.ts +5 -0
  40. package/dist/environment/git.d.ts.map +1 -0
  41. package/dist/environment/git.js +38 -0
  42. package/dist/environment/github.d.ts +26 -0
  43. package/dist/environment/github.d.ts.map +1 -0
  44. package/dist/environment/github.js +244 -0
  45. package/dist/environment/index.d.ts +5 -0
  46. package/dist/environment/index.d.ts.map +1 -0
  47. package/dist/environment/index.js +71 -0
  48. package/dist/environment/logger.d.ts +15 -0
  49. package/dist/environment/logger.d.ts.map +1 -0
  50. package/dist/environment/logger.js +25 -0
  51. package/dist/environment/manage-users.d.ts +11 -0
  52. package/dist/environment/manage-users.d.ts.map +1 -0
  53. package/dist/environment/manage-users.js +494 -0
  54. package/dist/environment/questions-helper.d.ts +15 -0
  55. package/dist/environment/questions-helper.d.ts.map +1 -0
  56. package/dist/environment/questions-helper.js +70 -0
  57. package/dist/environment/questions.d.ts +199 -0
  58. package/dist/environment/questions.d.ts.map +1 -0
  59. package/dist/environment/questions.js +412 -0
  60. package/dist/environment/setup-environment.d.ts +2 -0
  61. package/dist/environment/setup-environment.d.ts.map +1 -0
  62. package/dist/environment/setup-environment.js +773 -0
  63. package/dist/environment/ssh-keygen.d.ts +5 -0
  64. package/dist/environment/ssh-keygen.d.ts.map +1 -0
  65. package/dist/environment/ssh-keygen.js +18 -0
  66. package/dist/environment/swarm-to-k8s.d.ts +2 -0
  67. package/dist/environment/swarm-to-k8s.d.ts.map +1 -0
  68. package/dist/environment/swarm-to-k8s.js +172 -0
  69. package/dist/environment/templates.d.ts +27 -0
  70. package/dist/environment/templates.d.ts.map +1 -0
  71. package/dist/environment/templates.js +159 -0
  72. package/dist/environment/update-workflows.d.ts +2 -0
  73. package/dist/environment/update-workflows.d.ts.map +1 -0
  74. package/dist/environment/update-workflows.js +168 -0
  75. package/dist/environment/users.d.ts +2 -0
  76. package/dist/environment/users.d.ts.map +1 -0
  77. package/dist/environment/users.js +110 -0
  78. package/dist/environment/utils.d.ts +18 -0
  79. package/dist/environment/utils.d.ts.map +1 -0
  80. package/dist/environment/utils.js +100 -0
  81. package/dist/events/index.js +1049 -233
  82. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +1 -1
  83. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  84. package/dist/migrations/v2.0/checkout-upstream-files.js +1 -1
  85. package/dist/migrations/v2.0/index.js +10 -4
  86. package/dist/notification/index.js +883 -131
  87. package/dist/scopes/index.d.ts +4 -6
  88. package/dist/scopes/index.js +9 -3
  89. package/dist/templates/charts-values/dependencies/values.override.yaml +4 -0
  90. package/dist/templates/charts-values/dependencies/values.yaml +82 -0
  91. package/dist/templates/charts-values/opencrvs-services/values.override.yaml +4 -0
  92. package/dist/templates/charts-values/opencrvs-services/values.yaml +79 -0
  93. package/dist/templates/charts-values/traefik/values.override.yaml +4 -0
  94. package/dist/templates/charts-values/traefik/values.yaml +116 -0
  95. package/dist/templates/inventory/inventory.template.yml +100 -0
  96. package/dist/templates/inventory/production.example.yml +77 -0
  97. package/dist/templates/inventory/qa.example.yml +48 -0
  98. package/opencrvs-toolkit-2.0.0-rc.d23bb0b.tgz +0 -0
  99. package/package.json +20 -2
  100. package/tsconfig.tsbuildinfo +1 -1
  101. package/opencrvs-toolkit-2.0.0-rc.d1ea58b.tgz +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/environment/logger.ts"],"names":[],"mappings":"AAcA,eAAO,MAAM,GAAG;;;CAAc,CAAA;AAC9B,eAAO,MAAM,IAAI;;;CAAe,CAAA;AAChC,eAAO,MAAM,OAAO,YAAa,GAAG,EAAE,SACI,CAAA;AAC1C,eAAO,MAAM,IAAI;;;CAAe,CAAA;AAChC,eAAO,MAAM,KAAK,YAAa,GAAG,EAAE,SAA2C,CAAA"}
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ var __importDefault = (this && this.__importDefault) || function (mod) {
13
+ return (mod && mod.__esModule) ? mod : { "default": mod };
14
+ };
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.error = exports.info = exports.success = exports.warn = exports.log = void 0;
17
+ const kleur_1 = __importDefault(require("kleur"));
18
+ /* eslint-disable no-console */
19
+ exports.log = console.log;
20
+ exports.warn = console.warn;
21
+ const success = (...args) => console.log(kleur_1.default.green(args.join(' ')));
22
+ exports.success = success;
23
+ exports.info = console.info;
24
+ const error = (...args) => console.log(kleur_1.default.red(args.join(' ')));
25
+ exports.error = error;
@@ -0,0 +1,11 @@
1
+ export interface User {
2
+ name: string;
3
+ ssh_keys: string[];
4
+ state: 'present' | 'absent';
5
+ role: 'admin' | 'operator';
6
+ }
7
+ /**
8
+ * Main function to manage users
9
+ */
10
+ export declare function manageUsers(inventoryPath: string): Promise<User[]>;
11
+ //# sourceMappingURL=manage-users.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manage-users.d.ts","sourceRoot":"","sources":["../../src/environment/manage-users.ts"],"names":[],"mappings":"AAmCA,MAAM,WAAW,IAAI;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,KAAK,EAAE,SAAS,GAAG,QAAQ,CAAC;IAC5B,IAAI,EAAE,OAAO,GAAG,UAAU,CAAC;CAC5B;AA2VD;;GAEG;AACH,wBAAsB,WAAW,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,CAoIxE"}
@@ -0,0 +1,494 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
25
+ }) : function(o, v) {
26
+ o["default"] = v;
27
+ });
28
+ var __importStar = (this && this.__importStar) || function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.manageUsers = manageUsers;
46
+ const os = __importStar(require("os"));
47
+ const fs = __importStar(require("fs"));
48
+ const path = __importStar(require("path"));
49
+ function inquirerPrompt(name, options) {
50
+ return __awaiter(this, void 0, void 0, function* () {
51
+ const inquirer = yield import('@inquirer/prompts');
52
+ return inquirer[name](options);
53
+ });
54
+ }
55
+ const input = (options) => inquirerPrompt('input', options);
56
+ const select = (options) => inquirerPrompt('select', options);
57
+ const confirm = (options) => inquirerPrompt('confirm', options);
58
+ const editor = (options) => inquirerPrompt('editor', options);
59
+ const checkbox = (options) => inquirerPrompt('checkbox', options);
60
+ const logger_1 = require("./logger");
61
+ const utils_1 = require("./utils");
62
+ const templates_1 = require("./templates");
63
+ /**
64
+ * Updates users in Ansible inventory file
65
+ *
66
+ * @param {string} filePath - Path to the inventory file
67
+ * @param {User[]} users - Users array
68
+ */
69
+ function updateInventoryFile(filePath, users) {
70
+ var _a, _b;
71
+ const data = (0, utils_1.readYamlFile)(filePath);
72
+ if (!((_b = (_a = data === null || data === void 0 ? void 0 : data.all) === null || _a === void 0 ? void 0 : _a.vars) === null || _b === void 0 ? void 0 : _b.users)) {
73
+ throw Error(`'users' section not found within inventory file: ${filePath}`);
74
+ }
75
+ data.all.vars.users = users;
76
+ (0, utils_1.writeYamlFile)(filePath, data);
77
+ }
78
+ /**
79
+ * Parses the Ansible inventory file and extracts existing users
80
+ *
81
+ * @param {string} filePath - Path to the inventory file
82
+ * @returns {User[]} Array of existing users
83
+ */
84
+ function parseInventoryFile(filePath) {
85
+ try {
86
+ const data = (0, utils_1.readYamlFile)(filePath);
87
+ return (0, templates_1.getUsers)(data);
88
+ }
89
+ catch (_a) {
90
+ return [];
91
+ }
92
+ }
93
+ /**
94
+ * Gets the current system username
95
+ *
96
+ * @returns {string} Current OS username
97
+ */
98
+ function getCurrentUsername() {
99
+ return os.userInfo().username;
100
+ }
101
+ /**
102
+ * Reads SSH public keys from the current user's .ssh directory
103
+ *
104
+ * @returns {string[]} Array of SSH public keys found
105
+ */
106
+ function getCurrentUserSSHKeys() {
107
+ const homeDir = os.homedir();
108
+ const sshDir = path.join(homeDir, '.ssh');
109
+ const keys = [];
110
+ // Common public key filenames
111
+ const keyFiles = [
112
+ 'id_rsa.pub',
113
+ 'id_ecdsa.pub',
114
+ 'id_ed25519.pub',
115
+ 'id_dsa.pub'
116
+ ];
117
+ for (const keyFile of keyFiles) {
118
+ const keyPath = path.join(sshDir, keyFile);
119
+ try {
120
+ if (fs.existsSync(keyPath)) {
121
+ const keyContent = fs.readFileSync(keyPath, 'utf8').trim();
122
+ if (keyContent) {
123
+ keys.push(keyContent);
124
+ }
125
+ }
126
+ }
127
+ catch (error) {
128
+ // Silently skip if can't read the file
129
+ continue;
130
+ }
131
+ }
132
+ return keys;
133
+ }
134
+ function selectRole() {
135
+ return __awaiter(this, void 0, void 0, function* () {
136
+ return yield select({
137
+ message: 'Select user role:',
138
+ choices: [
139
+ { name: 'Admin (full access to OS and Kubernetes)', value: 'admin' },
140
+ { name: 'Operator (read-only OS, full Kubernetes)', value: 'operator' }
141
+ ]
142
+ });
143
+ });
144
+ }
145
+ function selectState() {
146
+ return __awaiter(this, void 0, void 0, function* () {
147
+ return yield select({
148
+ message: 'Select user state:',
149
+ choices: [
150
+ { name: 'Present (user is allowed to login)', value: 'present' },
151
+ { name: 'Absent (user account is disabled)', value: 'absent' }
152
+ ]
153
+ });
154
+ });
155
+ }
156
+ /**
157
+ * Asks if user wants to add current system user as the first user
158
+ *
159
+ * @returns {Promise<User | null>} User object if accepted, null if declined
160
+ */
161
+ function askToAddCurrentUser(existingUsers) {
162
+ return __awaiter(this, void 0, void 0, function* () {
163
+ const currentUsername = getCurrentUsername();
164
+ const currentKeys = getCurrentUserSSHKeys();
165
+ // Check if user already exists
166
+ if (existingUsers.find(u => u.name === currentUsername)) {
167
+ (0, logger_1.info)(`ā„¹ļø User "${currentUsername}" already exists in inventory.`);
168
+ return null;
169
+ }
170
+ if (currentKeys.length === 0) {
171
+ // No SSH keys found for current user
172
+ return null;
173
+ }
174
+ const addCurrentUser = yield confirm({
175
+ message: `Add current user "${currentUsername}" with ${currentKeys.length} SSH key(s)?`,
176
+ default: true
177
+ });
178
+ if (!addCurrentUser) {
179
+ return null;
180
+ }
181
+ // Ask for role
182
+ const role = yield selectRole();
183
+ return {
184
+ name: currentUsername,
185
+ ssh_keys: currentKeys,
186
+ state: 'present',
187
+ role: role
188
+ };
189
+ });
190
+ }
191
+ /**
192
+ * Add a new user
193
+ */
194
+ function addNewUser(existingUsers) {
195
+ return __awaiter(this, void 0, void 0, function* () {
196
+ const name = yield input({
197
+ message: 'Enter username:',
198
+ validate: (value) => {
199
+ if (!value.trim()) {
200
+ return 'Username required';
201
+ }
202
+ if (existingUsers.find(u => u.name === value.trim())) {
203
+ return `User "${value}" already exists`;
204
+ }
205
+ if (!/^[a-z_][a-z0-9_-]*[$]?$/.test(value.trim())) {
206
+ return 'Invalid username format (use lowercase, numbers, underscore, hyphen)';
207
+ }
208
+ return true;
209
+ }
210
+ });
211
+ const keysInput = yield editor({
212
+ message: 'Paste SSH public key(s) (one per line):',
213
+ default: ''
214
+ });
215
+ const ssh_keys = keysInput
216
+ .split('\n')
217
+ .map((key) => key.trim())
218
+ .filter((key) => key && !key.startsWith('#'));
219
+ if (ssh_keys.length === 0) {
220
+ (0, logger_1.warn)('āš ļø Warning: No SSH keys provided. User will not be able to login remotely.');
221
+ }
222
+ const role = yield selectRole();
223
+ // New users always active
224
+ const state = "present";
225
+ return {
226
+ name: name.trim(),
227
+ ssh_keys,
228
+ state,
229
+ role
230
+ };
231
+ });
232
+ }
233
+ /**
234
+ * Display user summary
235
+ */
236
+ function displayUserSummary(users) {
237
+ if (users.length === 0) {
238
+ console.log('\nšŸ“‹ No users configured.\n');
239
+ return;
240
+ }
241
+ console.log('\n' + '='.repeat(70));
242
+ console.log(`šŸ“‹ User Configuration Summary - Total users: ${users.length}`);
243
+ console.log('='.repeat(70));
244
+ users.forEach((user, index) => {
245
+ const stateIcon = user.state === 'present' ? 'āœ…' : 'āŒ';
246
+ const roleIcon = user.role === 'admin' ? 'šŸ‘‘' : 'šŸ‘¤';
247
+ console.log(`${index + 1}. ${stateIcon} ${roleIcon} ${user.name.padEnd(20)} ` +
248
+ `Role: ${user.role.padEnd(10)} State: ${user.state.padEnd(10)} ` +
249
+ `SSH Keys: ${user.ssh_keys.length}`);
250
+ });
251
+ console.log('='.repeat(70) + '\n');
252
+ }
253
+ /**
254
+ * Edit an existing user with screen clearing for better UX
255
+ */
256
+ function editUser(user) {
257
+ return __awaiter(this, void 0, void 0, function* () {
258
+ const updatedUser = Object.assign({}, user);
259
+ let continueEditing = true;
260
+ // Function to clear screen and move cursor to top
261
+ const clearScreen = () => {
262
+ process.stdout.write('\x1Bc'); // Clear entire screen
263
+ // Alternative: process.stdout.write('\x1B[2J\x1B[0f'); // Clear screen + move cursor to top
264
+ };
265
+ // Function to display current user state
266
+ const displayUserState = () => {
267
+ clearScreen();
268
+ console.log('─'.repeat(70));
269
+ console.log(`šŸ“ Editing user: ${updatedUser.name}`);
270
+ console.log('─'.repeat(70));
271
+ console.log(`Current Role: ${updatedUser.role === 'admin' ? 'šŸ‘‘ admin' : 'šŸ‘¤ operator'}`);
272
+ console.log(`Current State: ${updatedUser.state === 'present' ? 'āœ… present' : 'āŒ absent'}`);
273
+ console.log(`Current SSH Keys: ${updatedUser.ssh_keys.length} key(s)`);
274
+ if (updatedUser.ssh_keys.length > 0) {
275
+ updatedUser.ssh_keys.forEach((key, idx) => {
276
+ const keyPreview = key.length > 50 ? key.substring(0, 47) + '...' : key;
277
+ console.log(` ${idx + 1}. ${keyPreview}`);
278
+ });
279
+ }
280
+ console.log('─'.repeat(70));
281
+ console.log(''); // Empty line for spacing
282
+ };
283
+ while (continueEditing) {
284
+ displayUserState();
285
+ const action = yield select({
286
+ message: 'What would you like to modify?',
287
+ choices: [
288
+ {
289
+ name: `Change role (current: ${updatedUser.role})`,
290
+ value: 'role'
291
+ },
292
+ {
293
+ name: `Change state (current: ${updatedUser.state})`,
294
+ value: 'state'
295
+ },
296
+ {
297
+ name: `Update SSH keys (current: ${updatedUser.ssh_keys.length} key(s))`,
298
+ value: 'keys'
299
+ },
300
+ {
301
+ name: 'šŸ’¾ Save changes and return',
302
+ value: 'save'
303
+ },
304
+ {
305
+ name: '🚫 Cancel and discard changes',
306
+ value: 'cancel'
307
+ }
308
+ ]
309
+ });
310
+ switch (action) {
311
+ case 'role':
312
+ const newRole = yield selectRole();
313
+ if (newRole !== updatedUser.role) {
314
+ updatedUser.role = newRole;
315
+ }
316
+ break;
317
+ case 'state':
318
+ const newState = yield selectState();
319
+ if (newState !== updatedUser.state) {
320
+ updatedUser.state = newState;
321
+ }
322
+ break;
323
+ case 'keys':
324
+ const keysInput = yield editor({
325
+ message: 'Update SSH public key(s) (one per line):',
326
+ default: updatedUser.ssh_keys.join('\n')
327
+ });
328
+ const newKeys = keysInput
329
+ .split('\n')
330
+ .map((key) => key.trim())
331
+ .filter((key) => key && !key.startsWith('#'));
332
+ if (newKeys.length === 0) {
333
+ clearScreen();
334
+ displayUserState();
335
+ const confirmRemoveKeys = yield confirm({
336
+ message: 'āš ļø Warning: All SSH keys will be removed. Continue with no SSH keys?',
337
+ default: false
338
+ });
339
+ if (confirmRemoveKeys) {
340
+ updatedUser.ssh_keys = [];
341
+ }
342
+ }
343
+ else {
344
+ updatedUser.ssh_keys = newKeys;
345
+ }
346
+ break;
347
+ case 'save':
348
+ const hasChanges = updatedUser.role !== user.role ||
349
+ updatedUser.state !== user.state ||
350
+ JSON.stringify(updatedUser.ssh_keys) !== JSON.stringify(user.ssh_keys);
351
+ clearScreen();
352
+ if (hasChanges) {
353
+ console.log('\nāœ… Changes saved for user:', updatedUser.name, '\n');
354
+ }
355
+ else {
356
+ console.log('\nā„¹ļø No changes made\n');
357
+ }
358
+ continueEditing = false;
359
+ break;
360
+ case 'cancel':
361
+ clearScreen();
362
+ const confirmCancel = yield confirm({
363
+ message: 'Discard all changes?',
364
+ default: false
365
+ });
366
+ if (confirmCancel) {
367
+ console.log('\n🚫 Changes discarded\n');
368
+ return user; // Return original user
369
+ }
370
+ break;
371
+ }
372
+ }
373
+ return updatedUser;
374
+ });
375
+ }
376
+ /**
377
+ * Main function to manage users
378
+ */
379
+ function manageUsers(inventoryPath) {
380
+ return __awaiter(this, void 0, void 0, function* () {
381
+ let users = fs.existsSync(inventoryPath) ? parseInventoryFile(inventoryPath) : [];
382
+ if (users.length > 0) {
383
+ displayUserSummary(users);
384
+ }
385
+ let continueManaging = true;
386
+ while (continueManaging) {
387
+ const action = yield select({
388
+ message: 'What would you like to do?',
389
+ choices: [
390
+ { name: 'āž• Add new user', value: 'add' },
391
+ { name: 'āœļø Edit existing user', value: 'edit' },
392
+ { name: 'šŸ—‘ļø Remove user', value: 'remove' },
393
+ { name: 'šŸ‘¤ Add current system user', value: 'add-current' },
394
+ { name: 'šŸ“‹ View all users', value: 'view' },
395
+ { name: 'šŸ’¾ Save and exit', value: 'save' },
396
+ { name: '🚪 Exit without saving', value: 'exit' }
397
+ ]
398
+ });
399
+ switch (action) {
400
+ case 'add':
401
+ const newUser = yield addNewUser(users);
402
+ if (newUser) {
403
+ users.push(newUser);
404
+ console.log(`āœ… User "${newUser.name}" added.\n`);
405
+ }
406
+ break;
407
+ case 'add-current':
408
+ const currentUser = yield askToAddCurrentUser(users);
409
+ if (currentUser) {
410
+ users.push(currentUser);
411
+ console.log(`āœ… Current user "${currentUser.name}" added.\n`);
412
+ }
413
+ break;
414
+ case 'edit':
415
+ if (users.length === 0) {
416
+ console.log('āš ļø No users to edit.\n');
417
+ break;
418
+ }
419
+ const userToEdit = yield select({
420
+ message: 'Select user to edit:',
421
+ choices: users.map(u => ({
422
+ name: `${u.name} (${u.role}, ${u.state})`,
423
+ value: u.name
424
+ }))
425
+ });
426
+ const userIndex = users.findIndex(u => u.name === userToEdit);
427
+ if (userIndex !== -1) {
428
+ users[userIndex] = yield editUser(users[userIndex]);
429
+ console.log(`āœ… User "${userToEdit}" updated.\n`);
430
+ }
431
+ break;
432
+ case 'remove':
433
+ if (users.length === 0) {
434
+ console.log('āš ļø No users to remove.\n');
435
+ break;
436
+ }
437
+ const usersToRemove = yield checkbox({
438
+ message: 'Select user(s) to remove:',
439
+ choices: users.map(u => ({
440
+ name: `${u.name} (${u.role}, ${u.state})`,
441
+ value: u.name
442
+ }))
443
+ });
444
+ if (usersToRemove.length > 0) {
445
+ const confirmRemove = yield confirm({
446
+ message: `Remove ${usersToRemove.length} user(s)?`,
447
+ default: false
448
+ });
449
+ if (confirmRemove) {
450
+ users = users.filter(u => !usersToRemove.includes(u.name));
451
+ console.log(`āœ… Removed ${usersToRemove.length} user(s).\n`);
452
+ }
453
+ }
454
+ break;
455
+ case 'view':
456
+ displayUserSummary(users);
457
+ break;
458
+ case 'save':
459
+ if (users.length === 0) {
460
+ (0, logger_1.info)('\nšŸ“‹ No users configured.\n');
461
+ continueManaging = false;
462
+ break;
463
+ }
464
+ displayUserSummary(users);
465
+ const confirmSave = yield confirm({
466
+ message: 'Save changes end exit?',
467
+ default: true
468
+ });
469
+ if (confirmSave && fs.existsSync(inventoryPath)) {
470
+ updateInventoryFile(inventoryPath, users);
471
+ console.log(`\nāœ… Changes saved to ${inventoryPath}\n`);
472
+ }
473
+ continueManaging = false;
474
+ break;
475
+ case 'exit':
476
+ if (users.length === 0) {
477
+ (0, logger_1.info)('\nšŸ“‹ No users configured.\n');
478
+ continueManaging = false;
479
+ break;
480
+ }
481
+ const confirmExit = yield confirm({
482
+ message: 'Exit without saving changes?',
483
+ default: false
484
+ });
485
+ if (confirmExit) {
486
+ console.log('šŸ‘‹ Exited without saving.\n');
487
+ continueManaging = false;
488
+ }
489
+ break;
490
+ }
491
+ }
492
+ return users;
493
+ });
494
+ }
@@ -0,0 +1,15 @@
1
+ import { Choice } from 'prompts';
2
+ export declare function getIndexFromChoices(choices: Choice[], value: string): number;
3
+ type SelectWithCustomOptions = {
4
+ message: string;
5
+ choices: readonly {
6
+ name: string;
7
+ value: string;
8
+ }[];
9
+ customLabel?: string;
10
+ customInputMessage?: string;
11
+ initial?: string;
12
+ };
13
+ export declare function selectWithCustom(config: SelectWithCustomOptions): Promise<string>;
14
+ export {};
15
+ //# sourceMappingURL=questions-helper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"questions-helper.d.ts","sourceRoot":"","sources":["../../src/environment/questions-helper.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAajC,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,MAAM,UASnE;AAED,KAAK,uBAAuB,GAAG;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,SAAS;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACpD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,wBAAsB,gBAAgB,CAClC,MAAM,EAAE,uBAAuB,GAChC,OAAO,CAAC,MAAM,CAAC,CAkCjB"}
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14
+ return new (P || (P = Promise))(function (resolve, reject) {
15
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
19
+ });
20
+ };
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.getIndexFromChoices = getIndexFromChoices;
23
+ exports.selectWithCustom = selectWithCustom;
24
+ function input(options) {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ const inquirer = yield import('@inquirer/prompts');
27
+ return inquirer.input(options);
28
+ });
29
+ }
30
+ function select(options) {
31
+ return __awaiter(this, void 0, void 0, function* () {
32
+ const inquirer = yield import('@inquirer/prompts');
33
+ return inquirer.select(options);
34
+ });
35
+ }
36
+ function getIndexFromChoices(choices, value) {
37
+ let idx = 0;
38
+ for (const choice of choices) {
39
+ if (choice.value === value) {
40
+ return idx;
41
+ }
42
+ idx++;
43
+ }
44
+ return 0;
45
+ }
46
+ function selectWithCustom(config) {
47
+ return __awaiter(this, void 0, void 0, function* () {
48
+ const { message, choices, initial = undefined, customLabel = 'Other...', customInputMessage = 'Enter custom value:', } = config;
49
+ const CUSTOM = '__custom__';
50
+ const selected = yield select({
51
+ message,
52
+ choices: [
53
+ ...choices,
54
+ {
55
+ value: CUSTOM,
56
+ name: customLabel,
57
+ },
58
+ ],
59
+ default: initial,
60
+ });
61
+ if (selected === CUSTOM) {
62
+ const customValue = yield input({
63
+ message: customInputMessage,
64
+ validate: (value) => value.trim().length > 0 ? true : 'Value cannot be empty',
65
+ });
66
+ return customValue;
67
+ }
68
+ return selected;
69
+ });
70
+ }