@opencrvs/toolkit 2.0.0-rc.edee239 → 2.0.0-rc.ee0e51b

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 (120) hide show
  1. package/README.md +14 -0
  2. package/build.sh +1 -0
  3. package/create-countryconfig/index.js +103 -0
  4. package/create-countryconfig/package.json +21 -0
  5. package/dist/application-config/index.js +276 -122
  6. package/dist/cli.js +3544 -168
  7. package/dist/commons/api/router.d.ts +3377 -237
  8. package/dist/commons/application-config/index.d.ts +1 -0
  9. package/dist/commons/conditionals/conditionals.d.ts +357 -7
  10. package/dist/commons/conditionals/validate.d.ts +52 -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 +114 -0
  14. package/dist/commons/events/AdvancedSearchConfig.d.ts +342 -0
  15. package/dist/commons/events/Draft.d.ts +4 -2
  16. package/dist/commons/events/EventDocument.d.ts +3 -0
  17. package/dist/commons/events/EventIndex.d.ts +0 -3
  18. package/dist/commons/events/EventMetadata.d.ts +0 -7
  19. package/dist/commons/events/FieldConfig.d.ts +383 -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 +150 -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/locations.d.ts +21 -0
  27. package/dist/commons/events/mocks.test.utils.d.ts +19 -0
  28. package/dist/commons/events/scopes.d.ts +24 -1
  29. package/dist/commons/events/state/flags.d.ts +16 -0
  30. package/dist/commons/events/state/index.d.ts +0 -4
  31. package/dist/commons/events/state/utils.d.ts +12 -289
  32. package/dist/commons/events/utils.d.ts +13 -2
  33. package/dist/conditionals/index.js +60 -5
  34. package/dist/environment/custom-types.d.ts +33 -0
  35. package/dist/environment/custom-types.d.ts.map +1 -0
  36. package/dist/environment/custom-types.js +12 -0
  37. package/dist/environment/derived-variables.d.ts +134 -0
  38. package/dist/environment/derived-variables.d.ts.map +1 -0
  39. package/dist/environment/derived-variables.js +169 -0
  40. package/dist/environment/editor-questions.d.ts +4 -0
  41. package/dist/environment/editor-questions.d.ts.map +1 -0
  42. package/dist/environment/editor-questions.js +65 -0
  43. package/dist/environment/git.d.ts +5 -0
  44. package/dist/environment/git.d.ts.map +1 -0
  45. package/dist/environment/git.js +38 -0
  46. package/dist/environment/github.d.ts +26 -0
  47. package/dist/environment/github.d.ts.map +1 -0
  48. package/dist/environment/github.js +244 -0
  49. package/dist/environment/index.d.ts +5 -0
  50. package/dist/environment/index.d.ts.map +1 -0
  51. package/dist/environment/index.js +70 -0
  52. package/dist/environment/logger.d.ts +15 -0
  53. package/dist/environment/logger.d.ts.map +1 -0
  54. package/dist/environment/logger.js +25 -0
  55. package/dist/environment/manage-users.d.ts +11 -0
  56. package/dist/environment/manage-users.d.ts.map +1 -0
  57. package/dist/environment/manage-users.js +494 -0
  58. package/dist/environment/questions-helper.d.ts +15 -0
  59. package/dist/environment/questions-helper.d.ts.map +1 -0
  60. package/dist/environment/questions-helper.js +70 -0
  61. package/dist/environment/questions.d.ts +199 -0
  62. package/dist/environment/questions.d.ts.map +1 -0
  63. package/dist/environment/questions.js +412 -0
  64. package/dist/environment/setup-environment.d.ts +2 -0
  65. package/dist/environment/setup-environment.d.ts.map +1 -0
  66. package/dist/environment/setup-environment.js +773 -0
  67. package/dist/environment/ssh-keygen.d.ts +5 -0
  68. package/dist/environment/ssh-keygen.d.ts.map +1 -0
  69. package/dist/environment/ssh-keygen.js +18 -0
  70. package/dist/environment/swarm-to-k8s.d.ts +2 -0
  71. package/dist/environment/swarm-to-k8s.d.ts.map +1 -0
  72. package/dist/environment/swarm-to-k8s.js +172 -0
  73. package/dist/environment/templates/charts-values/dependencies/values.override.yaml +4 -0
  74. package/dist/environment/templates/charts-values/dependencies/values.yaml +82 -0
  75. package/dist/environment/templates/charts-values/opencrvs-services/values.override.yaml +4 -0
  76. package/dist/environment/templates/charts-values/opencrvs-services/values.yaml +79 -0
  77. package/dist/environment/templates/charts-values/traefik/values.override.yaml +4 -0
  78. package/dist/environment/templates/charts-values/traefik/values.yaml +116 -0
  79. package/dist/environment/templates/inventory/inventory.template.yml +100 -0
  80. package/dist/environment/templates/inventory/production.example.yml +77 -0
  81. package/dist/environment/templates/inventory/qa.example.yml +48 -0
  82. package/dist/environment/templates.d.ts +27 -0
  83. package/dist/environment/templates.d.ts.map +1 -0
  84. package/dist/environment/templates.js +159 -0
  85. package/dist/environment/update-workflows.d.ts +2 -0
  86. package/dist/environment/update-workflows.d.ts.map +1 -0
  87. package/dist/environment/update-workflows.js +168 -0
  88. package/dist/environment/users.d.ts +2 -0
  89. package/dist/environment/users.d.ts.map +1 -0
  90. package/dist/environment/users.js +102 -0
  91. package/dist/environment/utils.d.ts +18 -0
  92. package/dist/environment/utils.d.ts.map +1 -0
  93. package/dist/environment/utils.js +100 -0
  94. package/dist/events/index.js +1135 -287
  95. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +1 -1
  96. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  97. package/dist/migrations/v2.0/checkout-upstream-files.js +1 -2
  98. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +9 -1
  99. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +1 -1
  100. package/dist/migrations/v2.0/delete-infrastructure-directory.js +66 -20
  101. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +3 -0
  102. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +1 -0
  103. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +110 -0
  104. package/dist/migrations/v2.0/index.d.ts +5 -3
  105. package/dist/migrations/v2.0/index.d.ts.map +1 -1
  106. package/dist/migrations/v2.0/index.js +404 -132
  107. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +11 -1
  108. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +1 -1
  109. package/dist/migrations/v2.0/merge-infrastructure-directory.js +17 -16
  110. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -1
  111. package/dist/migrations/v2.0/migrate-scopes.js +54 -30
  112. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -1
  113. package/dist/migrations/v2.0/migrate-workqueue-configs.js +140 -59
  114. package/dist/notification/index.js +904 -158
  115. package/dist/scopes/index.d.ts +10 -7
  116. package/dist/scopes/index.js +17 -7
  117. package/opencrvs-toolkit-2.0.0-rc.ee0e51b.tgz +0 -0
  118. package/package.json +20 -2
  119. package/tsconfig.tsbuildinfo +1 -1
  120. package/opencrvs-toolkit-2.0.0-rc.edee239.tgz +0 -0
package/dist/cli.js CHANGED
@@ -6,22 +6,3061 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
9
16
  var __copyProps = (to, from, except, desc) => {
10
17
  if (from && typeof from === "object" || typeof from === "function") {
11
18
  for (let key of __getOwnPropNames(from))
12
19
  if (!__hasOwnProp.call(to, key) && key !== except)
13
20
  __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
21
  }
15
- return to;
16
- };
17
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
- // If the importer is in node compatibility mode or this is not an ESM
19
- // file that has been converted to a CommonJS file using a Babel-
20
- // compatible transform (i.e. "__esModule" has not been set), then set
21
- // "default" to the CommonJS "module.exports" for node compatibility.
22
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
- mod
24
- ));
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ // src/environment/logger.ts
34
+ var import_kleur, log, warn, success, info, error;
35
+ var init_logger = __esm({
36
+ "src/environment/logger.ts"() {
37
+ "use strict";
38
+ import_kleur = __toESM(require("kleur"));
39
+ log = console.log;
40
+ warn = console.warn;
41
+ success = (...args2) => console.log(import_kleur.default.green(args2.join(" ")));
42
+ info = console.info;
43
+ error = (...args2) => console.log(import_kleur.default.red(args2.join(" ")));
44
+ }
45
+ });
46
+
47
+ // src/environment/github.ts
48
+ async function createEnvironmentVariable(octokit, repositoryId, environment, name, value) {
49
+ await octokit.request(
50
+ `POST /repositories/${repositoryId}/environments/${environment}/variables`,
51
+ {
52
+ repository_id: repositoryId,
53
+ environment_name: environment,
54
+ name,
55
+ value,
56
+ headers: {
57
+ "X-GitHub-Api-Version": "2022-11-28"
58
+ }
59
+ }
60
+ );
61
+ }
62
+ async function updateEnvironmentVariable(octokit, repositoryId, environment, name, value) {
63
+ await octokit.request(
64
+ `PATCH /repositories/${repositoryId}/environments/${environment}/variables/${name}`,
65
+ {
66
+ repository_id: repositoryId,
67
+ environment_name: environment,
68
+ name,
69
+ value,
70
+ headers: {
71
+ "X-GitHub-Api-Version": "2022-11-28"
72
+ }
73
+ }
74
+ );
75
+ }
76
+ async function createRepositoryVariable(octokit, repositoryId, name, value) {
77
+ await octokit.request(
78
+ `POST /repositories/${repositoryId}/actions/variables`,
79
+ {
80
+ repository_id: repositoryId,
81
+ name,
82
+ value,
83
+ headers: {
84
+ "X-GitHub-Api-Version": "2022-11-28"
85
+ }
86
+ }
87
+ );
88
+ }
89
+ async function updateRepositoryVariable(octokit, repositoryId, name, value) {
90
+ await octokit.request(
91
+ `PATCH /repositories/${repositoryId}/actions/variables/${name}`,
92
+ {
93
+ repository_id: repositoryId,
94
+ name,
95
+ value,
96
+ headers: {
97
+ "X-GitHub-Api-Version": "2022-11-28"
98
+ }
99
+ }
100
+ );
101
+ }
102
+ async function getRepositoryId(octokit, owner, repo) {
103
+ const response = await octokit.request("GET /repos/{owner}/{repo}", {
104
+ owner,
105
+ repo
106
+ });
107
+ return response.data.id;
108
+ }
109
+ async function getRepositoryPublicKey(octokit, owner, repo) {
110
+ const res = await octokit.request(
111
+ "GET /repos/{owner}/{repo}/actions/secrets/public-key",
112
+ {
113
+ owner,
114
+ repo
115
+ }
116
+ );
117
+ return res.data;
118
+ }
119
+ async function getPublicKey(octokit, environment, ORGANISATION, REPOSITORY_NAME) {
120
+ const repositoryId = await getRepositoryId(
121
+ octokit,
122
+ ORGANISATION,
123
+ REPOSITORY_NAME
124
+ );
125
+ await octokit.request(
126
+ `PUT /repos/${ORGANISATION}/${REPOSITORY_NAME}/environments/${environment}`,
127
+ {
128
+ headers: {
129
+ "X-GitHub-Api-Version": "2022-11-28"
130
+ }
131
+ }
132
+ );
133
+ const res = await octokit.request(
134
+ `GET /repositories/${repositoryId}/environments/${environment}/secrets/public-key`,
135
+ {
136
+ owner: ORGANISATION,
137
+ repo: REPOSITORY_NAME,
138
+ headers: {
139
+ "X-GitHub-Api-Version": "2022-11-28"
140
+ }
141
+ }
142
+ );
143
+ return res.data;
144
+ }
145
+ async function createEnvironmentSecret(octokit, repositoryId, environment, name, secret, organisationName, repositoryName) {
146
+ await sodium.ready;
147
+ const { key, key_id } = await getPublicKey(
148
+ octokit,
149
+ environment,
150
+ organisationName,
151
+ repositoryName
152
+ );
153
+ const binkey = sodium.from_base64(key, sodium.base64_variants.ORIGINAL);
154
+ const binsec = sodium.from_string(secret);
155
+ const encBytes = sodium.crypto_box_seal(binsec, binkey);
156
+ const encryptedValue = sodium.to_base64(
157
+ encBytes,
158
+ sodium.base64_variants.ORIGINAL
159
+ );
160
+ await octokit.request(
161
+ `PUT /repositories/${repositoryId}/environments/${environment}/secrets/${name}`,
162
+ {
163
+ repository_id: repositoryId,
164
+ environment_name: environment,
165
+ secret_name: name,
166
+ encrypted_value: encryptedValue,
167
+ key_id,
168
+ headers: {
169
+ "X-GitHub-Api-Version": "2022-11-28"
170
+ }
171
+ }
172
+ );
173
+ }
174
+ async function createRepositorySecret(octokit, repositoryId, name, secret, organisationName, repositoryName) {
175
+ await sodium.ready;
176
+ const { key, key_id } = await getRepositoryPublicKey(
177
+ octokit,
178
+ organisationName,
179
+ repositoryName
180
+ );
181
+ const binkey = sodium.from_base64(key, sodium.base64_variants.ORIGINAL);
182
+ const binsec = sodium.from_string(secret);
183
+ const encBytes = sodium.crypto_box_seal(binsec, binkey);
184
+ const encryptedValue = sodium.to_base64(
185
+ encBytes,
186
+ sodium.base64_variants.ORIGINAL
187
+ );
188
+ await octokit.request(
189
+ `PUT /repositories/${repositoryId}/actions/secrets/${name}`,
190
+ {
191
+ encrypted_value: encryptedValue,
192
+ key_id,
193
+ headers: {
194
+ "X-GitHub-Api-Version": "2022-11-28"
195
+ }
196
+ }
197
+ );
198
+ }
199
+ async function getRepositoryEnvironments(octokit, githubOrganisation, repository) {
200
+ const response = await octokit.request("GET /repos/{githubOrganisation}/{repository}/environments", {
201
+ githubOrganisation,
202
+ repository
203
+ });
204
+ const environments = (response.data.environments ?? []).map(
205
+ (env) => env.name
206
+ );
207
+ return environments;
208
+ }
209
+ async function createEnvironment(octokit, environment, ORGANISATION, REPOSITORY_NAME) {
210
+ try {
211
+ await octokit.request(
212
+ `PUT /repos/${ORGANISATION}/${REPOSITORY_NAME}/environments/${environment}`,
213
+ {
214
+ headers: {
215
+ "X-GitHub-Api-Version": "2022-11-28"
216
+ }
217
+ }
218
+ );
219
+ return true;
220
+ } catch (err) {
221
+ error(
222
+ `Cannot create environment: [${err.status}] ${err.response?.data?.message}`
223
+ );
224
+ throw new Error(
225
+ `Cannot create environment: [${err.status}] ${err.response?.data?.message}`
226
+ );
227
+ }
228
+ }
229
+ async function listEnvironmentSecrets(octokit, owner, repositoryId, environmentName) {
230
+ const response = await octokit.request(
231
+ "GET /repositories/{repository_id}/environments/{environment_name}/secrets",
232
+ {
233
+ owner,
234
+ repository_id: repositoryId,
235
+ environment_name: environmentName,
236
+ per_page: 100
237
+ }
238
+ );
239
+ return response.data.secrets.map((secret) => ({
240
+ ...secret,
241
+ type: "SECRET",
242
+ scope: "ENVIRONMENT"
243
+ }));
244
+ }
245
+ async function listRepositorySecrets(octokit, owner, repositoryName) {
246
+ const response = await octokit.request(
247
+ "GET /repos/{owner}/{repo}/actions/secrets",
248
+ {
249
+ owner,
250
+ repo: repositoryName,
251
+ per_page: 100
252
+ }
253
+ );
254
+ return response.data.secrets.map((secret) => ({
255
+ ...secret,
256
+ type: "SECRET",
257
+ scope: "REPOSITORY"
258
+ }));
259
+ }
260
+ async function listEnvironmentVariables(octokit, repositoryId, environmentName) {
261
+ const response = await octokit.request(
262
+ "GET /repositories/{repository_id}/environments/{environment_name}/variables",
263
+ {
264
+ repository_id: repositoryId,
265
+ environment_name: environmentName,
266
+ per_page: 100,
267
+ headers: {
268
+ "X-GitHub-Api-Version": "2022-11-28"
269
+ }
270
+ }
271
+ );
272
+ return response.data.variables.map((variable) => ({
273
+ ...variable,
274
+ type: "VARIABLE",
275
+ scope: "ENVIRONMENT"
276
+ })).filter((variable) => variable.name !== "ACTIONS_RUNNER_DEBUG");
277
+ }
278
+ async function listRepositoryVariables(octokit, owner, repositoryName) {
279
+ const response = await octokit.request(
280
+ "GET /repos/{owner}/{repo}/actions/variables",
281
+ {
282
+ owner,
283
+ repo: repositoryName,
284
+ per_page: 100
285
+ }
286
+ );
287
+ return response.data.variables.map((variable) => ({
288
+ ...variable,
289
+ type: "VARIABLE",
290
+ scope: "REPOSITORY"
291
+ }));
292
+ }
293
+ var sodium;
294
+ var init_github = __esm({
295
+ "src/environment/github.ts"() {
296
+ "use strict";
297
+ init_logger();
298
+ sodium = require("libsodium-wrappers");
299
+ }
300
+ });
301
+
302
+ // src/environment/derived-variables.ts
303
+ var derivedVariables;
304
+ var init_derived_variables = __esm({
305
+ "src/environment/derived-variables.ts"() {
306
+ "use strict";
307
+ derivedVariables = [
308
+ {
309
+ name: "ACTIVATE_USERS",
310
+ valueLabel: "ACTIVATE_USERS",
311
+ valueType: "VARIABLE",
312
+ type: "disabled",
313
+ scope: "ENVIRONMENT"
314
+ },
315
+ {
316
+ name: "COUNTRY_CONFIG_HOST",
317
+ valueLabel: "COUNTRY_CONFIG_HOST",
318
+ valueType: "VARIABLE",
319
+ type: "disabled",
320
+ scope: "ENVIRONMENT"
321
+ },
322
+ {
323
+ name: "GATEWAY_HOST",
324
+ valueLabel: "GATEWAY_HOST",
325
+ valueType: "VARIABLE",
326
+ type: "disabled",
327
+ scope: "ENVIRONMENT"
328
+ },
329
+ {
330
+ name: "CONTENT_SECURITY_POLICY_WILDCARD",
331
+ valueLabel: "CONTENT_SECURITY_POLICY_WILDCARD",
332
+ valueType: "VARIABLE",
333
+ type: "disabled",
334
+ scope: "ENVIRONMENT"
335
+ },
336
+ {
337
+ name: "CLIENT_APP_URL",
338
+ valueLabel: "CLIENT_APP_URL",
339
+ valueType: "VARIABLE",
340
+ type: "disabled",
341
+ scope: "ENVIRONMENT"
342
+ },
343
+ {
344
+ name: "LOGIN_URL",
345
+ valueLabel: "LOGIN_URL",
346
+ valueType: "VARIABLE",
347
+ type: "disabled",
348
+ scope: "ENVIRONMENT"
349
+ },
350
+ {
351
+ name: "ELASTICSEARCH_SUPERUSER_PASSWORD",
352
+ valueLabel: "ELASTICSEARCH_SUPERUSER_PASSWORD",
353
+ valueType: "SECRET",
354
+ type: "disabled",
355
+ scope: "ENVIRONMENT"
356
+ },
357
+ {
358
+ name: "KIBANA_SYSTEM_PASSWORD",
359
+ valueLabel: "KIBANA_SYSTEM_PASSWORD",
360
+ valueType: "SECRET",
361
+ type: "disabled",
362
+ scope: "ENVIRONMENT"
363
+ },
364
+ {
365
+ name: "MINIO_ROOT_USER",
366
+ valueLabel: "MINIO_ROOT_USER",
367
+ valueType: "SECRET",
368
+ type: "disabled",
369
+ scope: "ENVIRONMENT"
370
+ },
371
+ {
372
+ name: "MINIO_ROOT_PASSWORD",
373
+ valueLabel: "MINIO_ROOT_PASSWORD",
374
+ valueType: "SECRET",
375
+ type: "disabled",
376
+ scope: "ENVIRONMENT"
377
+ },
378
+ {
379
+ name: "MONGODB_ADMIN_USER",
380
+ valueLabel: "MONGODB_ADMIN_USER",
381
+ valueType: "SECRET",
382
+ type: "disabled",
383
+ scope: "ENVIRONMENT"
384
+ },
385
+ {
386
+ name: "MONGODB_ADMIN_PASSWORD",
387
+ valueLabel: "MONGODB_ADMIN_PASSWORD",
388
+ valueType: "SECRET",
389
+ type: "disabled",
390
+ scope: "ENVIRONMENT"
391
+ },
392
+ {
393
+ name: "POSTGRES_USER",
394
+ valueLabel: "POSTGRES_USER",
395
+ valueType: "SECRET",
396
+ type: "disabled",
397
+ scope: "ENVIRONMENT"
398
+ },
399
+ {
400
+ name: "POSTGRES_PASSWORD",
401
+ valueLabel: "POSTGRES_PASSWORD",
402
+ valueType: "SECRET",
403
+ type: "disabled",
404
+ scope: "ENVIRONMENT"
405
+ },
406
+ {
407
+ name: "SUPER_USER_PASSWORD",
408
+ valueLabel: "SUPER_USER_PASSWORD",
409
+ valueType: "SECRET",
410
+ type: "disabled",
411
+ scope: "ENVIRONMENT"
412
+ },
413
+ {
414
+ name: "ENCRYPTION_KEY",
415
+ valueLabel: "ENCRYPTION_KEY",
416
+ valueType: "SECRET",
417
+ type: "disabled",
418
+ scope: "ENVIRONMENT"
419
+ },
420
+ {
421
+ name: "GH_ENCRYPTION_PASSWORD",
422
+ valueLabel: "GH_ENCRYPTION_PASSWORD",
423
+ valueType: "SECRET",
424
+ type: "disabled",
425
+ scope: "REPOSITORY"
426
+ },
427
+ {
428
+ name: "BACKUP_ENCRYPTION_PASSPHRASE",
429
+ valueLabel: "BACKUP_ENCRYPTION_PASSPHRASE",
430
+ valueType: "SECRET",
431
+ type: "disabled",
432
+ scope: "ENVIRONMENT"
433
+ },
434
+ {
435
+ name: "BACKUP_HOST_PRIVATE_KEY",
436
+ valueLabel: "BACKUP_HOST_PRIVATE_KEY",
437
+ valueType: "SECRET",
438
+ type: "disabled",
439
+ scope: "ENVIRONMENT"
440
+ },
441
+ {
442
+ name: "BACKUP_HOST_PUBLIC_KEY",
443
+ valueLabel: "BACKUP_HOST_PUBLIC_KEY",
444
+ valueType: "SECRET",
445
+ type: "disabled",
446
+ scope: "ENVIRONMENT"
447
+ },
448
+ {
449
+ name: "RESTORE_ENVIRONMENT_NAME",
450
+ valueLabel: "RESTORE_ENVIRONMENT_NAME",
451
+ valueType: "VARIABLE",
452
+ type: "disabled",
453
+ scope: "ENVIRONMENT"
454
+ },
455
+ {
456
+ name: "NOTIFICATION_TRANSPORT",
457
+ valueLabel: "NOTIFICATION_TRANSPORT",
458
+ valueType: "VARIABLE",
459
+ type: "disabled",
460
+ scope: "ENVIRONMENT"
461
+ }
462
+ ];
463
+ }
464
+ });
465
+
466
+ // src/environment/utils.ts
467
+ function generateLongPassword() {
468
+ const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
469
+ let result = "";
470
+ for (let i = 16; i > 0; --i)
471
+ result += chars[Math.floor(Math.random() * chars.length)];
472
+ return result;
473
+ }
474
+ function findExistingValue(name, type, scope, existingValues) {
475
+ return existingValues.find(
476
+ (value) => value.name === name && value.type === type && value.scope === scope
477
+ );
478
+ }
479
+ function storeSecrets(environment, answers) {
480
+ let envConfig = {};
481
+ try {
482
+ envConfig = import_dotenv.default.parse(
483
+ (0, import_fs7.readFileSync)(`${process.cwd()}/.env.${environment}`)
484
+ );
485
+ } catch (error4) {
486
+ envConfig = {};
487
+ }
488
+ const linesFromAnswers = answers.map(
489
+ (update) => `${update.name}="${update.value}"`
490
+ );
491
+ const linesFromEnvConfig = Object.entries(envConfig).filter(([name]) => !answers.find((update) => update.name === name)).map(([name, value]) => `${name}="${value}"`);
492
+ const allLines = [...linesFromEnvConfig, ...linesFromAnswers].sort();
493
+ (0, import_fs7.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
494
+ }
495
+ function readYamlFile(filePath) {
496
+ const fileContent = import_fs7.default.readFileSync(filePath, "utf8");
497
+ return yaml.load(fileContent);
498
+ }
499
+ function writeYamlFile(filePath, data) {
500
+ try {
501
+ const yamlContent = yaml.dump(data, {
502
+ indent: 2,
503
+ lineWidth: -1,
504
+ flowLevel: -1,
505
+ // Prevent flow style for arrays/objects
506
+ noRefs: true,
507
+ sortKeys: false
508
+ });
509
+ import_fs7.default.writeFileSync(filePath, yamlContent, "utf8");
510
+ } catch (error4) {
511
+ throw new Error(`Failed to write inventory file: ${error4}`);
512
+ }
513
+ }
514
+ var import_fs7, yaml, import_dotenv;
515
+ var init_utils = __esm({
516
+ "src/environment/utils.ts"() {
517
+ "use strict";
518
+ import_fs7 = __toESM(require("fs"));
519
+ yaml = __toESM(require("js-yaml"));
520
+ import_dotenv = __toESM(require("dotenv"));
521
+ }
522
+ });
523
+
524
+ // src/environment/templates.ts
525
+ function getUsers(data) {
526
+ if (!data?.all?.vars?.users) {
527
+ return { users: [] };
528
+ }
529
+ return data.all.vars.users;
530
+ }
531
+ function extractAndModifyUsers(data) {
532
+ if (!data?.all?.vars?.users) {
533
+ return { users: [] };
534
+ }
535
+ const users = data.all.vars.users.map((user) => {
536
+ const { sudoer, ...rest } = user;
537
+ return {
538
+ ...rest,
539
+ role: sudoer ? "admin" : "operator"
540
+ };
541
+ });
542
+ return users;
543
+ }
544
+ function dockerManagerFirst(data) {
545
+ if (!data?.["docker-manager-first"]?.hosts) {
546
+ throw new Error("Invalid YAML structure: missing docker-manager-first.hosts");
547
+ }
548
+ const hosts = data["docker-manager-first"].hosts;
549
+ const dockerManagerFirst2 = Object.values(hosts).filter((host) => host.ansible_host).map((host) => host.ansible_host);
550
+ return dockerManagerFirst2.length === 1 ? dockerManagerFirst2[0] : "";
551
+ }
552
+ function extractBackupNode(data) {
553
+ if (!data?.["backups"]?.hosts) {
554
+ return "";
555
+ }
556
+ const hosts = data["backups"].hosts;
557
+ const backupHostEntry = Object.values(hosts).filter((host) => host.ansible_host).map((host) => host.ansible_host);
558
+ return backupHostEntry.length === 1 ? backupHostEntry[0] : "";
559
+ }
560
+ function extractWorkerNodes(data) {
561
+ if (!data?.["docker-workers"]?.hosts) {
562
+ return [];
563
+ }
564
+ const hosts = data["docker-workers"].hosts;
565
+ const worker_hosts = Object.values(hosts).filter((host) => host.ansible_host).map((host) => host.ansible_host);
566
+ return worker_hosts;
567
+ }
568
+ function copyChartsValues(env, values) {
569
+ const srcDir = import_path27.default.resolve(__dirname, "templates", "charts-values");
570
+ const destDir = import_path27.default.resolve(process.cwd(), "environments", env);
571
+ import_fs8.default.mkdirSync(destDir, { recursive: true });
572
+ values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
573
+ values["static_ssl"] = values["traefik_mode"] === "static_ssl";
574
+ function copyRecursive(src, dest) {
575
+ const stat = import_fs8.default.statSync(src);
576
+ if (stat.isDirectory()) {
577
+ import_fs8.default.mkdirSync(dest, { recursive: true });
578
+ for (const item of import_fs8.default.readdirSync(src)) {
579
+ copyRecursive(import_path27.default.join(src, item), import_path27.default.join(dest, item));
580
+ }
581
+ } else {
582
+ const content = import_fs8.default.readFileSync(src, "utf8");
583
+ const template = import_handlebars.default.compile(content);
584
+ const updated = template(values);
585
+ const isOverridesFile = dest.endsWith("override.yaml");
586
+ if (isOverridesFile && import_fs8.default.existsSync(dest)) {
587
+ log(` \u21B7 Skipped existing overrides file: ${dest}`);
588
+ return;
589
+ }
590
+ import_fs8.default.writeFileSync(dest, updated, "utf8");
591
+ log(` \u2713 Created: ${dest}`);
592
+ }
593
+ }
594
+ log(`
595
+ \u{1F4CB} Copying charts-values templates to ${destDir}:`);
596
+ copyRecursive(srcDir, destDir);
597
+ success(`\u2705 Completed copying charts-values.
598
+ `);
599
+ }
600
+ function generateInventory(env, values) {
601
+ const templatePath = import_path27.default.join(__dirname, "templates", "inventory", "inventory.template.yml");
602
+ const outputPath = import_path27.default.join(process.cwd(), "infrastructure", "server-setup", "inventory", `${env}.yml`);
603
+ const templateFile = import_fs8.default.readFileSync(templatePath, "utf-8");
604
+ const template = import_handlebars.default.compile(templateFile);
605
+ values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
606
+ const updated = template(values);
607
+ import_fs8.default.mkdirSync(import_path27.default.dirname(outputPath), { recursive: true });
608
+ import_fs8.default.writeFileSync(outputPath, updated);
609
+ log(`
610
+ \u2705 Generated inventory file at ${outputPath}
611
+ `);
612
+ }
613
+ var import_fs8, import_path27, import_handlebars;
614
+ var init_templates = __esm({
615
+ "src/environment/templates.ts"() {
616
+ "use strict";
617
+ import_fs8 = __toESM(require("fs"));
618
+ import_path27 = __toESM(require("path"));
619
+ init_logger();
620
+ import_handlebars = __toESM(require("handlebars"));
621
+ import_handlebars.default.registerHelper("data_label_idx", function(value) {
622
+ return parseInt(value) + 2;
623
+ });
624
+ }
625
+ });
626
+
627
+ // src/environment/ssh-keygen.ts
628
+ function generateSSHKeyPair() {
629
+ let keys = import_ssh2.utils.generateKeyPairSync("ed25519");
630
+ return { publicKey: keys.public.toString(), privateKey: keys.private.toString() };
631
+ }
632
+ var import_ssh2;
633
+ var init_ssh_keygen = __esm({
634
+ "src/environment/ssh-keygen.ts"() {
635
+ "use strict";
636
+ import_ssh2 = require("ssh2");
637
+ }
638
+ });
639
+
640
+ // src/environment/git.ts
641
+ function getRepoInfo() {
642
+ try {
643
+ const remoteUrl = (0, import_child_process3.execSync)("git config --get remote.origin.url", {
644
+ stdio: ["ignore", "pipe", "ignore"]
645
+ }).toString().trim();
646
+ const match = remoteUrl.match(/github\.com[:/](.+?)\/(.+?)(\.git)?$/);
647
+ if (!match) {
648
+ return { organization: "", repository: "" };
649
+ }
650
+ return {
651
+ organization: match[1],
652
+ repository: match[2]
653
+ };
654
+ } catch {
655
+ return {
656
+ organization: "",
657
+ repository: ""
658
+ };
659
+ }
660
+ }
661
+ var import_child_process3;
662
+ var init_git = __esm({
663
+ "src/environment/git.ts"() {
664
+ "use strict";
665
+ import_child_process3 = require("child_process");
666
+ }
667
+ });
668
+
669
+ // src/environment/questions.ts
670
+ function validateCIDR(input3) {
671
+ if (!input3.trim()) {
672
+ return true;
673
+ }
674
+ const cidrRegex = /^((25[0-5]|(2[0-4]|1\d|[1-9]?\d)\d?)\.){3}(25[0-5]|(2[0-4]|1\d|[1-9]?\d)\d?)\/([0-9]|[12][0-9]|3[0-2])$/;
675
+ return cidrRegex.test(input3.trim()) ? true : "Please enter a valid CIDR (e.g. 10.0.0.0/24)";
676
+ }
677
+ function validateCIDRs(input3) {
678
+ if (!input3.trim()) {
679
+ return true;
680
+ }
681
+ const cidrs = input3.split(",").map((v) => v.trim());
682
+ for (const cidr of cidrs) {
683
+ const result = validateCIDR(cidr);
684
+ if (result !== true) {
685
+ return `Invalid CIDR: ${cidr}`;
686
+ }
687
+ }
688
+ return true;
689
+ }
690
+ var import_kleur2, notEmpty, dockerhubQuestions, githubQuestions, githubOtherQuestions, githubTokenQuestion, countryQuestions, infrastructureQuestions, staticSSLCertQuestions, backupQuestions, diskQuestions, databaseAndMonitoringQuestions, emailQuestions, sentryQuestions, metabaseAdminQuestions;
691
+ var init_questions = __esm({
692
+ "src/environment/questions.ts"() {
693
+ "use strict";
694
+ import_kleur2 = __toESM(require("kleur"));
695
+ init_utils();
696
+ init_git();
697
+ notEmpty = (value) => value.toString().trim().length > 0 ? true : "Please enter a value";
698
+ dockerhubQuestions = [
699
+ {
700
+ name: "dockerhubOrganisation",
701
+ type: "text",
702
+ message: "What is the name of your Docker Hub organisation?",
703
+ valueType: "SECRET",
704
+ valueLabel: "DOCKERHUB_ACCOUNT",
705
+ validate: notEmpty,
706
+ initial: process.env.DOCKER_ORGANISATION,
707
+ scope: "REPOSITORY"
708
+ },
709
+ {
710
+ name: "dockerhubRepository",
711
+ type: "text",
712
+ message: "What is the name of your private Docker Hub repository?",
713
+ valueType: "SECRET",
714
+ valueLabel: "DOCKERHUB_REPO",
715
+ validate: notEmpty,
716
+ initial: process.env.DOCKER_REPO,
717
+ scope: "REPOSITORY"
718
+ },
719
+ {
720
+ name: "dockerhubUsername",
721
+ type: "text",
722
+ message: "What is the Docker Hub username the the target server should be using?",
723
+ valueType: "SECRET",
724
+ valueLabel: "DOCKER_USERNAME",
725
+ validate: notEmpty,
726
+ initial: process.env.DOCKER_USERNAME,
727
+ scope: "REPOSITORY"
728
+ },
729
+ {
730
+ name: "dockerhubToken",
731
+ type: "text",
732
+ message: "What is the token of this Docker Hub account?",
733
+ valueType: "SECRET",
734
+ valueLabel: "DOCKER_TOKEN",
735
+ validate: notEmpty,
736
+ initial: process.env.DOCKER_TOKEN,
737
+ scope: "REPOSITORY"
738
+ }
739
+ ];
740
+ githubQuestions = [
741
+ {
742
+ name: "githubOrganisation",
743
+ type: "text",
744
+ message: "What is the name of your Github organisation?",
745
+ validate: notEmpty,
746
+ initial: process.env.GITHUB_ORGANISATION || getRepoInfo().organization,
747
+ scope: "REPOSITORY"
748
+ },
749
+ {
750
+ name: "githubRepository",
751
+ type: "text",
752
+ message: "What is your Github infrastructure repository?",
753
+ validate: notEmpty,
754
+ initial: process.env.GITHUB_REPOSITORY || getRepoInfo().repository,
755
+ scope: "REPOSITORY"
756
+ }
757
+ ];
758
+ githubOtherQuestions = [
759
+ {
760
+ name: "githubApprovers",
761
+ type: "text",
762
+ message: "Please provide/update list of production approvers?",
763
+ initial: process.env.GH_APPROVERS,
764
+ valueType: "VARIABLE",
765
+ valueLabel: "GH_APPROVERS",
766
+ scope: "REPOSITORY"
767
+ },
768
+ {
769
+ name: "approvalRequired",
770
+ type: "select",
771
+ message: "Would you like to enable approvals process for GitHub action workflows?",
772
+ choices: [
773
+ {
774
+ title: "True",
775
+ value: "true"
776
+ },
777
+ {
778
+ title: "False",
779
+ value: "false"
780
+ }
781
+ ],
782
+ valueType: "VARIABLE",
783
+ validate: notEmpty,
784
+ valueLabel: "APPROVAL_REQUIRED",
785
+ initial: process.env.APPROVAL_REQUIRED,
786
+ scope: "ENVIRONMENT"
787
+ }
788
+ ];
789
+ githubTokenQuestion = [
790
+ {
791
+ name: "githubToken",
792
+ type: "text",
793
+ message: "What is your Github token?",
794
+ validate: notEmpty,
795
+ initial: process.env.GITHUB_TOKEN,
796
+ valueType: "SECRET",
797
+ scope: "REPOSITORY",
798
+ valueLabel: "GH_TOKEN"
799
+ }
800
+ ];
801
+ countryQuestions = [
802
+ {
803
+ name: "country",
804
+ type: "text",
805
+ message: 'What is the ISO 3166-1 alpha-3 country-code? (e.g. "NZL" for New Zealand) Reference: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3',
806
+ valueType: "VARIABLE",
807
+ valueLabel: "COUNTRY",
808
+ initial: process.env.COUNTRY,
809
+ scope: "REPOSITORY"
810
+ }
811
+ ];
812
+ infrastructureQuestions = [
813
+ {
814
+ name: "domain",
815
+ type: "text",
816
+ message: "What is the web domain applied after all subdomains in URLs?",
817
+ valueType: "VARIABLE",
818
+ validate: notEmpty,
819
+ valueLabel: "DOMAIN",
820
+ initial: process.env.DOMAIN,
821
+ scope: "ENVIRONMENT"
822
+ },
823
+ {
824
+ name: "kubeAPIHost",
825
+ type: "text",
826
+ message: `Kubernetes API endpoint (default: auto-detect)`,
827
+ valueType: "VARIABLE",
828
+ // validate: notEmpty,
829
+ valueLabel: "KUBE_API_HOST",
830
+ initial: process.env.KUBE_API_HOST,
831
+ scope: "ENVIRONMENT"
832
+ },
833
+ {
834
+ name: "kubeApiAllowedCidrs",
835
+ type: "text",
836
+ message: `Allowed CIDRs for Kubernetes API access (default: KUBE_API_HOST)`,
837
+ valueType: "VARIABLE",
838
+ validate: validateCIDRs,
839
+ valueLabel: "KUBE_API_ALLOWED_CIDRS",
840
+ initial: process.env.KUBE_API_ALLOWED_CIDRS || "",
841
+ scope: "ENVIRONMENT"
842
+ },
843
+ {
844
+ name: "kubeWorkerNodes",
845
+ type: "text",
846
+ message: `Kubernetes worker node hostnames or IPs (comma-separated, default: no worker nodes)`,
847
+ valueType: "VARIABLE",
848
+ // validate: notEmpty,
849
+ valueLabel: "KUBE_WORKER_NODES",
850
+ initial: process.env.KUBE_WORKER_NODES || "",
851
+ scope: "ENVIRONMENT"
852
+ }
853
+ ];
854
+ staticSSLCertQuestions = [
855
+ {
856
+ name: "sslCrt",
857
+ type: "text",
858
+ message: "Provide SSL Certificate or Certificate chain:",
859
+ valueType: "SECRET",
860
+ validate: notEmpty,
861
+ valueLabel: "SSL_CRT",
862
+ initial: process.env.SSL_CRT,
863
+ scope: "ENVIRONMENT"
864
+ },
865
+ {
866
+ name: "sslKey",
867
+ type: "text",
868
+ message: "Provide SSL Certificate key",
869
+ valueType: "SECRET",
870
+ validate: notEmpty,
871
+ valueLabel: "SSL_KEY",
872
+ initial: process.env.SSL_KEY,
873
+ scope: "ENVIRONMENT"
874
+ }
875
+ ];
876
+ backupQuestions = [
877
+ {
878
+ name: "backupHost",
879
+ type: "text",
880
+ message: `Please enter backup server host/IP address, (default: no backup):`,
881
+ valueType: "VARIABLE",
882
+ // validate: notEmpty,
883
+ valueLabel: "BACKUP_HOST",
884
+ initial: process.env.BACKUP_HOST || "",
885
+ scope: "ENVIRONMENT"
886
+ },
887
+ {
888
+ name: "backupUser",
889
+ type: "text",
890
+ message: `Please enter backup server user name:`,
891
+ valueType: "SECRET",
892
+ validate: notEmpty,
893
+ valueLabel: "BACKUP_SERVER_USER",
894
+ initial: process.env.BACKUP_SERVER_USER || "backup",
895
+ scope: "ENVIRONMENT"
896
+ },
897
+ {
898
+ name: "backupType",
899
+ type: "select",
900
+ message: "Select environment backup mode",
901
+ choices: [
902
+ {
903
+ title: "Full dump (daily full database backup)",
904
+ value: "dump"
905
+ },
906
+ {
907
+ title: "Differential (weekly full, daily diff backup)",
908
+ value: "differential"
909
+ }
910
+ ],
911
+ valueType: "VARIABLE",
912
+ validate: notEmpty,
913
+ valueLabel: "BACKUP_ENVIRONMENT_MODE",
914
+ initial: process.env.BACKUP_ENVIRONMENT_MODE,
915
+ scope: "ENVIRONMENT"
916
+ }
917
+ ];
918
+ diskQuestions = [
919
+ {
920
+ name: "diskSpace",
921
+ type: "text",
922
+ message: `What is the amount of diskspace that should be dedicated to OpenCRVS data and will become the size of an encrypted cryptfs data directory.
923
+
924
+ ${import_kleur2.default.red("DO NOT USE ALL DISKSPACE FOR OPENCRVS!")}
925
+
926
+ Leave at least 50g available for OS use.`,
927
+ valueType: "VARIABLE",
928
+ validate: notEmpty,
929
+ valueLabel: "DISK_SPACE",
930
+ initial: process.env.DISK_SPACE || "200g",
931
+ scope: "ENVIRONMENT"
932
+ }
933
+ ];
934
+ databaseAndMonitoringQuestions = [
935
+ {
936
+ name: "kibanaUsername",
937
+ type: "text",
938
+ message: "Input the username for logging in to Kibana",
939
+ valueType: "SECRET",
940
+ validate: notEmpty,
941
+ valueLabel: "KIBANA_USERNAME",
942
+ initial: process.env.KIBANA_USERNAME || "opencrvs-admin",
943
+ scope: "ENVIRONMENT"
944
+ },
945
+ {
946
+ name: "kibanaPassword",
947
+ type: "text",
948
+ message: "Input the password for logging in to Kibana",
949
+ valueType: "SECRET",
950
+ validate: notEmpty,
951
+ valueLabel: "KIBANA_PASSWORD",
952
+ initial: process.env.KIBANA_PASSWORD || generateLongPassword(),
953
+ scope: "ENVIRONMENT"
954
+ }
955
+ ];
956
+ emailQuestions = [
957
+ {
958
+ name: "smtpHost",
959
+ type: "text",
960
+ message: "What is your SMTP host?",
961
+ valueType: "SECRET",
962
+ validate: notEmpty,
963
+ valueLabel: "SMTP_HOST",
964
+ initial: process.env.SMTP_HOST,
965
+ scope: "ENVIRONMENT"
966
+ },
967
+ {
968
+ name: "smtpUsername",
969
+ type: "text",
970
+ message: "What is your SMTP username?",
971
+ valueType: "SECRET",
972
+ validate: notEmpty,
973
+ valueLabel: "SMTP_USERNAME",
974
+ initial: process.env.SMTP_USERNAME,
975
+ scope: "ENVIRONMENT"
976
+ },
977
+ {
978
+ name: "smtpPassword",
979
+ type: "text",
980
+ message: "What is your SMTP password?",
981
+ valueType: "SECRET",
982
+ validate: notEmpty,
983
+ valueLabel: "SMTP_PASSWORD",
984
+ initial: process.env.SMTP_PASSWORD,
985
+ scope: "ENVIRONMENT"
986
+ },
987
+ {
988
+ name: "smtpPort",
989
+ type: "text",
990
+ message: "What is your SMTP port?",
991
+ valueType: "SECRET",
992
+ validate: notEmpty,
993
+ valueLabel: "SMTP_PORT",
994
+ initial: process.env.SMTP_PORT,
995
+ scope: "ENVIRONMENT"
996
+ },
997
+ {
998
+ name: "smtpSecure",
999
+ type: "select",
1000
+ message: "Is the SMTP connection made securely using TLS?",
1001
+ choices: [
1002
+ {
1003
+ title: "True",
1004
+ value: "true"
1005
+ },
1006
+ {
1007
+ title: "False",
1008
+ value: "false"
1009
+ }
1010
+ ],
1011
+ valueType: "SECRET",
1012
+ validate: notEmpty,
1013
+ valueLabel: "SMTP_SECURE",
1014
+ initial: process.env.SMTP_SECURE,
1015
+ scope: "ENVIRONMENT"
1016
+ },
1017
+ {
1018
+ name: "senderEmailAddress",
1019
+ type: "text",
1020
+ message: "What is your sender email address?",
1021
+ valueType: "SECRET",
1022
+ validate: notEmpty,
1023
+ valueLabel: "SENDER_EMAIL_ADDRESS",
1024
+ initial: process.env.SENDER_EMAIL_ADDRESS,
1025
+ scope: "ENVIRONMENT"
1026
+ },
1027
+ {
1028
+ name: "alertEmail",
1029
+ type: "text",
1030
+ message: "What is the email address to receive alert emails or a Slack channel email link?",
1031
+ valueType: "SECRET",
1032
+ validate: notEmpty,
1033
+ valueLabel: "ALERT_EMAIL",
1034
+ initial: process.env.ALERT_EMAIL,
1035
+ scope: "ENVIRONMENT"
1036
+ }
1037
+ ];
1038
+ sentryQuestions = [
1039
+ {
1040
+ name: "sentryDsn",
1041
+ type: "text",
1042
+ message: "What is your Sentry DSN?",
1043
+ valueType: "SECRET",
1044
+ validate: notEmpty,
1045
+ valueLabel: "SENTRY_DSN",
1046
+ initial: process.env.SENTRY_DSN,
1047
+ scope: "ENVIRONMENT"
1048
+ }
1049
+ ];
1050
+ metabaseAdminQuestions = [
1051
+ {
1052
+ valueType: "SECRET",
1053
+ name: "OPENCRVS_METABASE_ADMIN_EMAIL",
1054
+ type: "text",
1055
+ message: "Email for Metabase super admin. Used as a username when logging in to the dashboard",
1056
+ valueLabel: "OPENCRVS_METABASE_ADMIN_EMAIL",
1057
+ scope: "ENVIRONMENT",
1058
+ initial: "user@opencrvs.org"
1059
+ },
1060
+ {
1061
+ valueType: "SECRET",
1062
+ name: "OPENCRVS_METABASE_ADMIN_PASSWORD",
1063
+ type: "text",
1064
+ message: "Password for Metabase super admin.",
1065
+ valueLabel: "OPENCRVS_METABASE_ADMIN_PASSWORD",
1066
+ scope: "ENVIRONMENT",
1067
+ initial: generateLongPassword()
1068
+ }
1069
+ ];
1070
+ }
1071
+ });
1072
+
1073
+ // src/environment/editor-questions.ts
1074
+ function editorQuestion(question) {
1075
+ return import("@inquirer/prompts").then(
1076
+ ({ editor: editor2 }) => editor2({ message: question })
1077
+ );
1078
+ }
1079
+ async function askQuestionWithEditor(questions, existingValues) {
1080
+ let answers = [];
1081
+ for (const question of questions) {
1082
+ const questionWithVariableLabel = {
1083
+ ...question,
1084
+ message: `${import_kleur3.default.cyan(question.valueLabel || "")}: ${question.message}`
1085
+ };
1086
+ if (!questionWithVariableLabel.valueLabel) {
1087
+ throw Error("Undefined Label");
1088
+ }
1089
+ const existingSecret = findExistingValue(
1090
+ questionWithVariableLabel.valueLabel,
1091
+ "SECRET",
1092
+ questionWithVariableLabel.scope,
1093
+ existingValues
1094
+ );
1095
+ let updateSecret = true;
1096
+ if (existingSecret) {
1097
+ updateSecret = (await (0, import_prompts.default)([{
1098
+ name: "overWrite",
1099
+ type: "confirm",
1100
+ message: `${import_kleur3.default.yellow(
1101
+ `${existingSecret.scope === "REPOSITORY" ? "Repository secret" : "Secret"} ${import_kleur3.default.cyan(
1102
+ existingSecret.name
1103
+ )} already exists in Github. Do you want to update it?`
1104
+ )}`
1105
+ }])).overWrite;
1106
+ }
1107
+ if (!existingSecret || updateSecret === true) {
1108
+ const question_answer = await editorQuestion(questionWithVariableLabel.message);
1109
+ const answer = {
1110
+ type: "SECRET",
1111
+ scope: "ENVIRONMENT",
1112
+ name: questionWithVariableLabel.valueLabel,
1113
+ value: question_answer,
1114
+ didExist: existingSecret
1115
+ };
1116
+ answers.push(answer);
1117
+ }
1118
+ }
1119
+ return answers;
1120
+ }
1121
+ var import_kleur3, import_prompts;
1122
+ var init_editor_questions = __esm({
1123
+ "src/environment/editor-questions.ts"() {
1124
+ "use strict";
1125
+ init_utils();
1126
+ import_kleur3 = __toESM(require("kleur"));
1127
+ import_prompts = __toESM(require("prompts"));
1128
+ }
1129
+ });
1130
+
1131
+ // src/environment/questions-helper.ts
1132
+ async function input(options) {
1133
+ const inquirer = await import("@inquirer/prompts");
1134
+ return inquirer.input(options);
1135
+ }
1136
+ async function select(options) {
1137
+ const inquirer = await import("@inquirer/prompts");
1138
+ return inquirer.select(options);
1139
+ }
1140
+ function getIndexFromChoices(choices, value) {
1141
+ let idx = 0;
1142
+ for (const choice of choices) {
1143
+ if (choice.value === value) {
1144
+ return idx;
1145
+ }
1146
+ idx++;
1147
+ }
1148
+ return 0;
1149
+ }
1150
+ async function selectWithCustom(config) {
1151
+ const {
1152
+ message,
1153
+ choices,
1154
+ initial = void 0,
1155
+ customLabel = "Other...",
1156
+ customInputMessage = "Enter custom value:"
1157
+ } = config;
1158
+ const CUSTOM = "__custom__";
1159
+ const selected = await select({
1160
+ message,
1161
+ choices: [
1162
+ ...choices,
1163
+ {
1164
+ value: CUSTOM,
1165
+ name: customLabel
1166
+ }
1167
+ ],
1168
+ default: initial
1169
+ });
1170
+ if (selected === CUSTOM) {
1171
+ const customValue = await input({
1172
+ message: customInputMessage,
1173
+ validate: (value) => value.trim().length > 0 ? true : "Value cannot be empty"
1174
+ });
1175
+ return customValue;
1176
+ }
1177
+ return selected;
1178
+ }
1179
+ var init_questions_helper = __esm({
1180
+ "src/environment/questions-helper.ts"() {
1181
+ "use strict";
1182
+ }
1183
+ });
1184
+
1185
+ // src/environment/manage-users.ts
1186
+ async function inquirerPrompt(name, options) {
1187
+ const inquirer = await import("@inquirer/prompts");
1188
+ return inquirer[name](options);
1189
+ }
1190
+ function updateInventoryFile(filePath, users) {
1191
+ const data = readYamlFile(filePath);
1192
+ if (!data?.all?.vars?.users) {
1193
+ throw Error(`'users' section not found within inventory file: ${filePath}`);
1194
+ }
1195
+ data.all.vars.users = users;
1196
+ writeYamlFile(filePath, data);
1197
+ }
1198
+ function parseInventoryFile(filePath) {
1199
+ try {
1200
+ const data = readYamlFile(filePath);
1201
+ return getUsers(data);
1202
+ } catch {
1203
+ return [];
1204
+ }
1205
+ }
1206
+ function getCurrentUsername() {
1207
+ return os.userInfo().username;
1208
+ }
1209
+ function getCurrentUserSSHKeys() {
1210
+ const homeDir = os.homedir();
1211
+ const sshDir = path25.join(homeDir, ".ssh");
1212
+ const keys = [];
1213
+ const keyFiles = [
1214
+ "id_rsa.pub",
1215
+ "id_ecdsa.pub",
1216
+ "id_ed25519.pub",
1217
+ "id_dsa.pub"
1218
+ ];
1219
+ for (const keyFile of keyFiles) {
1220
+ const keyPath = path25.join(sshDir, keyFile);
1221
+ try {
1222
+ if (fs7.existsSync(keyPath)) {
1223
+ const keyContent = fs7.readFileSync(keyPath, "utf8").trim();
1224
+ if (keyContent) {
1225
+ keys.push(keyContent);
1226
+ }
1227
+ }
1228
+ } catch (error4) {
1229
+ continue;
1230
+ }
1231
+ }
1232
+ return keys;
1233
+ }
1234
+ async function selectRole() {
1235
+ return await select2({
1236
+ message: "Select user role:",
1237
+ choices: [
1238
+ { name: "Admin (full access to OS and Kubernetes)", value: "admin" },
1239
+ { name: "Operator (read-only OS, full Kubernetes)", value: "operator" }
1240
+ ]
1241
+ });
1242
+ }
1243
+ async function selectState() {
1244
+ return await select2({
1245
+ message: "Select user state:",
1246
+ choices: [
1247
+ { name: "Present (user is allowed to login)", value: "present" },
1248
+ { name: "Absent (user account is disabled)", value: "absent" }
1249
+ ]
1250
+ });
1251
+ }
1252
+ async function askToAddCurrentUser(existingUsers) {
1253
+ const currentUsername = getCurrentUsername();
1254
+ const currentKeys = getCurrentUserSSHKeys();
1255
+ if (existingUsers.find((u) => u.name === currentUsername)) {
1256
+ info(`\u2139\uFE0F User "${currentUsername}" already exists in inventory.`);
1257
+ return null;
1258
+ }
1259
+ if (currentKeys.length === 0) {
1260
+ return null;
1261
+ }
1262
+ const addCurrentUser = await confirm({
1263
+ message: `Add current user "${currentUsername}" with ${currentKeys.length} SSH key(s)?`,
1264
+ default: true
1265
+ });
1266
+ if (!addCurrentUser) {
1267
+ return null;
1268
+ }
1269
+ const role = await selectRole();
1270
+ return {
1271
+ name: currentUsername,
1272
+ ssh_keys: currentKeys,
1273
+ state: "present",
1274
+ role
1275
+ };
1276
+ }
1277
+ async function addNewUser(existingUsers) {
1278
+ const name = await input2({
1279
+ message: "Enter username:",
1280
+ validate: (value) => {
1281
+ if (!value.trim()) {
1282
+ return "Username required";
1283
+ }
1284
+ if (existingUsers.find((u) => u.name === value.trim())) {
1285
+ return `User "${value}" already exists`;
1286
+ }
1287
+ if (!/^[a-z_][a-z0-9_-]*[$]?$/.test(value.trim())) {
1288
+ return "Invalid username format (use lowercase, numbers, underscore, hyphen)";
1289
+ }
1290
+ return true;
1291
+ }
1292
+ });
1293
+ const keysInput = await editor({
1294
+ message: "Paste SSH public key(s) (one per line):",
1295
+ default: ""
1296
+ });
1297
+ const ssh_keys = keysInput.split("\n").map((key) => key.trim()).filter((key) => key && !key.startsWith("#"));
1298
+ if (ssh_keys.length === 0) {
1299
+ warn("\u26A0\uFE0F Warning: No SSH keys provided. User will not be able to login remotely.");
1300
+ }
1301
+ const role = await selectRole();
1302
+ const state = "present";
1303
+ return {
1304
+ name: name.trim(),
1305
+ ssh_keys,
1306
+ state,
1307
+ role
1308
+ };
1309
+ }
1310
+ function displayUserSummary(users) {
1311
+ if (users.length === 0) {
1312
+ console.log("\n\u{1F4CB} No users configured.\n");
1313
+ return;
1314
+ }
1315
+ console.log("\n" + "=".repeat(70));
1316
+ console.log(`\u{1F4CB} User Configuration Summary - Total users: ${users.length}`);
1317
+ console.log("=".repeat(70));
1318
+ users.forEach((user, index) => {
1319
+ const stateIcon = user.state === "present" ? "\u2705" : "\u274C";
1320
+ const roleIcon = user.role === "admin" ? "\u{1F451}" : "\u{1F464}";
1321
+ console.log(
1322
+ `${index + 1}. ${stateIcon} ${roleIcon} ${user.name.padEnd(20)} Role: ${user.role.padEnd(10)} State: ${user.state.padEnd(10)} SSH Keys: ${user.ssh_keys.length}`
1323
+ );
1324
+ });
1325
+ console.log("=".repeat(70) + "\n");
1326
+ }
1327
+ async function editUser(user) {
1328
+ const updatedUser = { ...user };
1329
+ let continueEditing = true;
1330
+ const clearScreen = () => {
1331
+ process.stdout.write("\x1Bc");
1332
+ };
1333
+ const displayUserState = () => {
1334
+ clearScreen();
1335
+ console.log("\u2500".repeat(70));
1336
+ console.log(`\u{1F4DD} Editing user: ${updatedUser.name}`);
1337
+ console.log("\u2500".repeat(70));
1338
+ console.log(`Current Role: ${updatedUser.role === "admin" ? "\u{1F451} admin" : "\u{1F464} operator"}`);
1339
+ console.log(`Current State: ${updatedUser.state === "present" ? "\u2705 present" : "\u274C absent"}`);
1340
+ console.log(`Current SSH Keys: ${updatedUser.ssh_keys.length} key(s)`);
1341
+ if (updatedUser.ssh_keys.length > 0) {
1342
+ updatedUser.ssh_keys.forEach((key, idx) => {
1343
+ const keyPreview = key.length > 50 ? key.substring(0, 47) + "..." : key;
1344
+ console.log(` ${idx + 1}. ${keyPreview}`);
1345
+ });
1346
+ }
1347
+ console.log("\u2500".repeat(70));
1348
+ console.log("");
1349
+ };
1350
+ while (continueEditing) {
1351
+ displayUserState();
1352
+ const action = await select2({
1353
+ message: "What would you like to modify?",
1354
+ choices: [
1355
+ {
1356
+ name: `Change role (current: ${updatedUser.role})`,
1357
+ value: "role"
1358
+ },
1359
+ {
1360
+ name: `Change state (current: ${updatedUser.state})`,
1361
+ value: "state"
1362
+ },
1363
+ {
1364
+ name: `Update SSH keys (current: ${updatedUser.ssh_keys.length} key(s))`,
1365
+ value: "keys"
1366
+ },
1367
+ {
1368
+ name: "\u{1F4BE} Save changes and return",
1369
+ value: "save"
1370
+ },
1371
+ {
1372
+ name: "\u{1F6AB} Cancel and discard changes",
1373
+ value: "cancel"
1374
+ }
1375
+ ]
1376
+ });
1377
+ switch (action) {
1378
+ case "role":
1379
+ const newRole = await selectRole();
1380
+ if (newRole !== updatedUser.role) {
1381
+ updatedUser.role = newRole;
1382
+ }
1383
+ break;
1384
+ case "state":
1385
+ const newState = await selectState();
1386
+ if (newState !== updatedUser.state) {
1387
+ updatedUser.state = newState;
1388
+ }
1389
+ break;
1390
+ case "keys":
1391
+ const keysInput = await editor({
1392
+ message: "Update SSH public key(s) (one per line):",
1393
+ default: updatedUser.ssh_keys.join("\n")
1394
+ });
1395
+ const newKeys = keysInput.split("\n").map((key) => key.trim()).filter((key) => key && !key.startsWith("#"));
1396
+ if (newKeys.length === 0) {
1397
+ clearScreen();
1398
+ displayUserState();
1399
+ const confirmRemoveKeys = await confirm({
1400
+ message: "\u26A0\uFE0F Warning: All SSH keys will be removed. Continue with no SSH keys?",
1401
+ default: false
1402
+ });
1403
+ if (confirmRemoveKeys) {
1404
+ updatedUser.ssh_keys = [];
1405
+ }
1406
+ } else {
1407
+ updatedUser.ssh_keys = newKeys;
1408
+ }
1409
+ break;
1410
+ case "save":
1411
+ const hasChanges = updatedUser.role !== user.role || updatedUser.state !== user.state || JSON.stringify(updatedUser.ssh_keys) !== JSON.stringify(user.ssh_keys);
1412
+ clearScreen();
1413
+ if (hasChanges) {
1414
+ console.log("\n\u2705 Changes saved for user:", updatedUser.name, "\n");
1415
+ } else {
1416
+ console.log("\n\u2139\uFE0F No changes made\n");
1417
+ }
1418
+ continueEditing = false;
1419
+ break;
1420
+ case "cancel":
1421
+ clearScreen();
1422
+ const confirmCancel = await confirm({
1423
+ message: "Discard all changes?",
1424
+ default: false
1425
+ });
1426
+ if (confirmCancel) {
1427
+ console.log("\n\u{1F6AB} Changes discarded\n");
1428
+ return user;
1429
+ }
1430
+ break;
1431
+ }
1432
+ }
1433
+ return updatedUser;
1434
+ }
1435
+ async function manageUsers(inventoryPath) {
1436
+ let users = fs7.existsSync(inventoryPath) ? parseInventoryFile(inventoryPath) : [];
1437
+ if (users.length > 0) {
1438
+ displayUserSummary(users);
1439
+ }
1440
+ let continueManaging = true;
1441
+ while (continueManaging) {
1442
+ const action = await select2({
1443
+ message: "What would you like to do?",
1444
+ choices: [
1445
+ { name: "\u2795 Add new user", value: "add" },
1446
+ { name: "\u270F\uFE0F Edit existing user", value: "edit" },
1447
+ { name: "\u{1F5D1}\uFE0F Remove user", value: "remove" },
1448
+ { name: "\u{1F464} Add current system user", value: "add-current" },
1449
+ { name: "\u{1F4CB} View all users", value: "view" },
1450
+ { name: "\u{1F4BE} Save and exit", value: "save" },
1451
+ { name: "\u{1F6AA} Exit without saving", value: "exit" }
1452
+ ]
1453
+ });
1454
+ switch (action) {
1455
+ case "add":
1456
+ const newUser = await addNewUser(users);
1457
+ if (newUser) {
1458
+ users.push(newUser);
1459
+ console.log(`\u2705 User "${newUser.name}" added.
1460
+ `);
1461
+ }
1462
+ break;
1463
+ case "add-current":
1464
+ const currentUser = await askToAddCurrentUser(users);
1465
+ if (currentUser) {
1466
+ users.push(currentUser);
1467
+ console.log(`\u2705 Current user "${currentUser.name}" added.
1468
+ `);
1469
+ }
1470
+ break;
1471
+ case "edit":
1472
+ if (users.length === 0) {
1473
+ console.log("\u26A0\uFE0F No users to edit.\n");
1474
+ break;
1475
+ }
1476
+ const userToEdit = await select2({
1477
+ message: "Select user to edit:",
1478
+ choices: users.map((u) => ({
1479
+ name: `${u.name} (${u.role}, ${u.state})`,
1480
+ value: u.name
1481
+ }))
1482
+ });
1483
+ const userIndex = users.findIndex((u) => u.name === userToEdit);
1484
+ if (userIndex !== -1) {
1485
+ users[userIndex] = await editUser(users[userIndex]);
1486
+ console.log(`\u2705 User "${userToEdit}" updated.
1487
+ `);
1488
+ }
1489
+ break;
1490
+ case "remove":
1491
+ if (users.length === 0) {
1492
+ console.log("\u26A0\uFE0F No users to remove.\n");
1493
+ break;
1494
+ }
1495
+ const usersToRemove = await checkbox({
1496
+ message: "Select user(s) to remove:",
1497
+ choices: users.map((u) => ({
1498
+ name: `${u.name} (${u.role}, ${u.state})`,
1499
+ value: u.name
1500
+ }))
1501
+ });
1502
+ if (usersToRemove.length > 0) {
1503
+ const confirmRemove = await confirm({
1504
+ message: `Remove ${usersToRemove.length} user(s)?`,
1505
+ default: false
1506
+ });
1507
+ if (confirmRemove) {
1508
+ users = users.filter((u) => !usersToRemove.includes(u.name));
1509
+ console.log(`\u2705 Removed ${usersToRemove.length} user(s).
1510
+ `);
1511
+ }
1512
+ }
1513
+ break;
1514
+ case "view":
1515
+ displayUserSummary(users);
1516
+ break;
1517
+ case "save":
1518
+ if (users.length === 0) {
1519
+ info("\n\u{1F4CB} No users configured.\n");
1520
+ continueManaging = false;
1521
+ break;
1522
+ }
1523
+ displayUserSummary(users);
1524
+ const confirmSave = await confirm({
1525
+ message: "Save changes end exit?",
1526
+ default: true
1527
+ });
1528
+ if (confirmSave && fs7.existsSync(inventoryPath)) {
1529
+ updateInventoryFile(inventoryPath, users);
1530
+ console.log(`
1531
+ \u2705 Changes saved to ${inventoryPath}
1532
+ `);
1533
+ }
1534
+ continueManaging = false;
1535
+ break;
1536
+ case "exit":
1537
+ if (users.length === 0) {
1538
+ info("\n\u{1F4CB} No users configured.\n");
1539
+ continueManaging = false;
1540
+ break;
1541
+ }
1542
+ const confirmExit = await confirm({
1543
+ message: "Exit without saving changes?",
1544
+ default: false
1545
+ });
1546
+ if (confirmExit) {
1547
+ console.log("\u{1F44B} Exited without saving.\n");
1548
+ continueManaging = false;
1549
+ }
1550
+ break;
1551
+ }
1552
+ }
1553
+ return users;
1554
+ }
1555
+ var os, fs7, path25, input2, select2, confirm, editor, checkbox;
1556
+ var init_manage_users = __esm({
1557
+ "src/environment/manage-users.ts"() {
1558
+ "use strict";
1559
+ os = __toESM(require("os"));
1560
+ fs7 = __toESM(require("fs"));
1561
+ path25 = __toESM(require("path"));
1562
+ init_logger();
1563
+ init_utils();
1564
+ init_templates();
1565
+ input2 = (options) => inquirerPrompt("input", options);
1566
+ select2 = (options) => inquirerPrompt("select", options);
1567
+ confirm = (options) => inquirerPrompt("confirm", options);
1568
+ editor = (options) => inquirerPrompt("editor", options);
1569
+ checkbox = (options) => inquirerPrompt("checkbox", options);
1570
+ }
1571
+ });
1572
+
1573
+ // src/environment/setup-environment.ts
1574
+ var setup_environment_exports = {};
1575
+ async function confirm2(options) {
1576
+ const inquirer = await import("@inquirer/prompts");
1577
+ return inquirer.confirm(options);
1578
+ }
1579
+ async function select3(options) {
1580
+ const inquirer = await import("@inquirer/prompts");
1581
+ return inquirer.select(options);
1582
+ }
1583
+ function questionToPrompt({
1584
+ // eslint-disable-next-line no-unused-vars
1585
+ valueType,
1586
+ // eslint-disable-next-line no-unused-vars
1587
+ valueLabel,
1588
+ // eslint-disable-next-line no-unused-vars
1589
+ scope,
1590
+ ...promptOptions
1591
+ }) {
1592
+ return promptOptions;
1593
+ }
1594
+ function getAnswers(existingValues) {
1595
+ return ALL_ANSWERS.flatMap((answerObject) => {
1596
+ const questionsThatAreSecretsOrVariables = Object.entries(
1597
+ answerObject
1598
+ ).filter(([key, value]) => {
1599
+ if (value === "") {
1600
+ return false;
1601
+ }
1602
+ const existingQuestion = ALL_QUESTIONS.find(
1603
+ (question) => question.name === key
1604
+ );
1605
+ const valueType = existingQuestion?.valueType;
1606
+ return valueType === "VARIABLE" || valueType === "SECRET";
1607
+ });
1608
+ return questionsThatAreSecretsOrVariables.map(([key, value]) => {
1609
+ const existingQuestion = ALL_QUESTIONS.find(
1610
+ (question) => question.name === key
1611
+ );
1612
+ const valueType = existingQuestion.valueType;
1613
+ if (valueType === "SECRET") {
1614
+ const existingSecret = findExistingValue(
1615
+ existingQuestion.valueLabel,
1616
+ "SECRET",
1617
+ existingQuestion?.scope,
1618
+ existingValues
1619
+ );
1620
+ return {
1621
+ type: valueType,
1622
+ name: existingQuestion?.valueLabel,
1623
+ value: value.toString(),
1624
+ didExist: existingSecret,
1625
+ scope: existingQuestion.scope
1626
+ };
1627
+ }
1628
+ const existingVariable = findExistingValue(
1629
+ existingQuestion?.valueLabel,
1630
+ valueType,
1631
+ existingQuestion?.scope,
1632
+ existingValues
1633
+ );
1634
+ return {
1635
+ type: valueType,
1636
+ name: existingQuestion?.valueLabel,
1637
+ didExist: findExistingValue(
1638
+ existingQuestion?.valueLabel,
1639
+ valueType,
1640
+ existingQuestion?.scope,
1641
+ existingValues
1642
+ ),
1643
+ value: value.toString() || existingVariable?.value || "",
1644
+ scope: existingQuestion.scope
1645
+ };
1646
+ });
1647
+ });
1648
+ }
1649
+ async function promptAndStoreAnswer(environment, questions, existingValues) {
1650
+ log("");
1651
+ const processedQuestions = questions.flatMap((question) => {
1652
+ const questionWithVariableLabel = {
1653
+ ...question,
1654
+ message: `${import_kleur4.default.cyan(question.valueLabel || "")}: ${question.message}`
1655
+ };
1656
+ if (!questionWithVariableLabel.valueLabel) {
1657
+ return questionWithVariableLabel;
1658
+ }
1659
+ if (questionWithVariableLabel.valueType === "VARIABLE") {
1660
+ const existingVariable = findExistingValue(
1661
+ questionWithVariableLabel.valueLabel,
1662
+ "VARIABLE",
1663
+ questionWithVariableLabel.scope,
1664
+ existingValues
1665
+ );
1666
+ if (existingVariable) {
1667
+ let initial_value = existingVariable.value;
1668
+ if (questionWithVariableLabel.type === "select" && Array.isArray(questionWithVariableLabel.choices)) {
1669
+ initial_value = getIndexFromChoices(questionWithVariableLabel.choices, existingVariable.value);
1670
+ }
1671
+ return [
1672
+ {
1673
+ name: "overWrite" + questionWithVariableLabel.name,
1674
+ type: "confirm",
1675
+ scope: questionWithVariableLabel.scope,
1676
+ message: `${import_kleur4.default.yellow(
1677
+ `Variable ${import_kleur4.default.cyan(
1678
+ existingVariable.name
1679
+ )} already exists in Github. Do you want to update it?`
1680
+ )}`
1681
+ },
1682
+ {
1683
+ ...questionWithVariableLabel,
1684
+ type: (prev) => prev ? questionWithVariableLabel.type : null,
1685
+ initial: initial_value
1686
+ }
1687
+ ];
1688
+ }
1689
+ }
1690
+ if (questionWithVariableLabel.valueType === "SECRET") {
1691
+ const existingSecret = findExistingValue(
1692
+ questionWithVariableLabel.valueLabel,
1693
+ "SECRET",
1694
+ questionWithVariableLabel.scope,
1695
+ existingValues
1696
+ );
1697
+ if (existingSecret) {
1698
+ return [
1699
+ {
1700
+ name: "overWrite" + questionWithVariableLabel.name,
1701
+ type: "confirm",
1702
+ scope: questionWithVariableLabel.scope,
1703
+ message: `${import_kleur4.default.yellow(
1704
+ `${existingSecret.scope === "REPOSITORY" ? "Repository secret" : "Secret"} ${import_kleur4.default.cyan(
1705
+ existingSecret.name
1706
+ )} already exists in Github. Do you want to update it?`
1707
+ )}`
1708
+ },
1709
+ {
1710
+ ...questionWithVariableLabel,
1711
+ type: (prev) => prev ? questionWithVariableLabel.type : null
1712
+ }
1713
+ ];
1714
+ }
1715
+ }
1716
+ return questionWithVariableLabel;
1717
+ });
1718
+ const promptQuestions = processedQuestions.map(questionToPrompt);
1719
+ const result = await (0, import_prompts2.default)(promptQuestions, {
1720
+ onCancel: () => {
1721
+ process.exit(1);
1722
+ }
1723
+ });
1724
+ ALL_ANSWERS.push(result);
1725
+ storeSecrets(environment, getAnswers(existingValues));
1726
+ const existingValuesForQuestions = questions.filter((question) => question.valueType === "VARIABLE").map((question) => [
1727
+ question.name,
1728
+ findExistingValue(
1729
+ question.valueLabel,
1730
+ "VARIABLE",
1731
+ question.scope,
1732
+ existingValues
1733
+ )?.value
1734
+ ]);
1735
+ return { ...Object.fromEntries(existingValuesForQuestions), ...result };
1736
+ }
1737
+ var import_core, import_dotenv2, import_kleur4, import_prompts2, ALL_QUESTIONS, ALL_ANSWERS;
1738
+ var init_setup_environment = __esm({
1739
+ "src/environment/setup-environment.ts"() {
1740
+ "use strict";
1741
+ import_core = require("@octokit/core");
1742
+ import_dotenv2 = __toESM(require("dotenv"));
1743
+ import_kleur4 = __toESM(require("kleur"));
1744
+ import_prompts2 = __toESM(require("prompts"));
1745
+ init_github();
1746
+ init_derived_variables();
1747
+ init_utils();
1748
+ init_logger();
1749
+ init_templates();
1750
+ init_ssh_keygen();
1751
+ init_questions();
1752
+ init_editor_questions();
1753
+ init_questions_helper();
1754
+ init_manage_users();
1755
+ ALL_QUESTIONS = [];
1756
+ ALL_ANSWERS = [];
1757
+ ALL_QUESTIONS.push(
1758
+ ...githubTokenQuestion,
1759
+ ...githubOtherQuestions,
1760
+ ...dockerhubQuestions,
1761
+ ...diskQuestions,
1762
+ ...infrastructureQuestions,
1763
+ ...backupQuestions,
1764
+ ...countryQuestions,
1765
+ ...databaseAndMonitoringQuestions,
1766
+ ...emailQuestions,
1767
+ ...sentryQuestions,
1768
+ ...derivedVariables,
1769
+ ...metabaseAdminQuestions
1770
+ );
1771
+ (async () => {
1772
+ log("\n", import_kleur4.default.bold().underline("Github"), "\n");
1773
+ const { githubOrganisation, githubRepository } = await (0, import_prompts2.default)(
1774
+ githubQuestions.map(questionToPrompt),
1775
+ {
1776
+ onCancel: () => {
1777
+ process.exit(1);
1778
+ }
1779
+ }
1780
+ );
1781
+ const { githubToken } = await promptAndStoreAnswer(
1782
+ "",
1783
+ githubTokenQuestion,
1784
+ []
1785
+ );
1786
+ const octokit = new import_core.Octokit({
1787
+ auth: githubToken
1788
+ });
1789
+ log(import_kleur4.default.green("\nSuccessfully logged in to Github\n"));
1790
+ let existingEnvironments = await getRepositoryEnvironments(octokit, githubOrganisation, githubRepository);
1791
+ let defaultChoices = [
1792
+ { name: "Development", value: "development" },
1793
+ { name: "Quality assurance (no PII data)", value: "qa" },
1794
+ {
1795
+ name: "Staging (hosts PII data, no backups)",
1796
+ value: "staging"
1797
+ },
1798
+ {
1799
+ name: "Production (hosts PII data, requires frequent backups)",
1800
+ value: "production"
1801
+ }
1802
+ ];
1803
+ const choices = [
1804
+ ...defaultChoices,
1805
+ ...existingEnvironments.filter(
1806
+ (env) => !defaultChoices.some((choice) => choice.value === env)
1807
+ ).map((env) => ({
1808
+ name: env,
1809
+ value: env
1810
+ }))
1811
+ ];
1812
+ const environment = await selectWithCustom(
1813
+ {
1814
+ message: "Choose a name and purpose for the environment?",
1815
+ choices
1816
+ }
1817
+ );
1818
+ let environment_type = "non-production";
1819
+ if (["development", "qa"].includes(environment)) {
1820
+ environment_type = "non-production";
1821
+ } else if (["staging", "production"].includes(environment)) {
1822
+ environment_type = "production";
1823
+ } else {
1824
+ environment_type = await select3(
1825
+ {
1826
+ message: "Purpose for the environment?",
1827
+ choices: [
1828
+ { name: "Development/Quality assurance/Testing (no PII data)", value: "non-production" },
1829
+ { name: "Staging/Production (hosts PII data, requires frequent backups)", value: "production" }
1830
+ ]
1831
+ }
1832
+ );
1833
+ }
1834
+ const environment_exists = existingEnvironments.map((e) => e.trim()).includes(environment);
1835
+ if (!environment) {
1836
+ process.exit(1);
1837
+ }
1838
+ import_dotenv2.default.config({
1839
+ path: `${process.cwd()}/.env.${environment}`
1840
+ });
1841
+ await createEnvironment(
1842
+ octokit,
1843
+ environment,
1844
+ githubOrganisation,
1845
+ githubRepository
1846
+ );
1847
+ const repositoryId = await getRepositoryId(
1848
+ octokit,
1849
+ githubOrganisation,
1850
+ githubRepository
1851
+ );
1852
+ const existingRepositorySecrets = await listRepositorySecrets(
1853
+ octokit,
1854
+ githubOrganisation,
1855
+ githubRepository
1856
+ );
1857
+ const existingRepositoryVariables = await listRepositoryVariables(
1858
+ octokit,
1859
+ githubOrganisation,
1860
+ githubRepository
1861
+ );
1862
+ const existingEnvironmentVariables = await listEnvironmentVariables(
1863
+ octokit,
1864
+ repositoryId,
1865
+ environment
1866
+ );
1867
+ const existingEnvironmentSecrets = await listEnvironmentSecrets(
1868
+ octokit,
1869
+ githubOrganisation,
1870
+ repositoryId,
1871
+ environment
1872
+ );
1873
+ const existingValues = [
1874
+ ...existingEnvironmentVariables,
1875
+ ...existingRepositoryVariables,
1876
+ ...existingRepositorySecrets,
1877
+ ...existingEnvironmentSecrets
1878
+ ];
1879
+ if (existingEnvironmentVariables.length > 0 || existingEnvironmentSecrets.length > 0) {
1880
+ log(
1881
+ "\nEnvironment with the name",
1882
+ environment,
1883
+ "already exists in Github.",
1884
+ "\nFound",
1885
+ existingEnvironmentVariables.length,
1886
+ "existing variables and",
1887
+ existingEnvironmentSecrets.length,
1888
+ "secrets"
1889
+ );
1890
+ }
1891
+ if (environment_type === "production") {
1892
+ log("\n", import_kleur4.default.yellow().bold(
1893
+ "WARNING! You are setting up a production environment.\n Make sure you have read the deployment guide carefully before proceeding.\n"
1894
+ ));
1895
+ await promptAndStoreAnswer(environment, githubOtherQuestions, existingValues);
1896
+ }
1897
+ log("\n", import_kleur4.default.bold().underline("Docker Hub"));
1898
+ await promptAndStoreAnswer(environment, dockerhubQuestions, existingValues);
1899
+ log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
1900
+ const infrastructure = await promptAndStoreAnswer(
1901
+ environment,
1902
+ infrastructureQuestions,
1903
+ existingValues
1904
+ );
1905
+ const kubeWorkerNodes = infrastructure.kubeWorkerNodes ? infrastructure.kubeWorkerNodes.split(",").map((ip) => ip.trim()) : [];
1906
+ log("\n", import_kleur4.default.bold().underline("SSH Users"), "\n");
1907
+ const users = await manageUsers(`infrastructure/server-setup/inventory/${environment}.yml`);
1908
+ log("\n", import_kleur4.default.bold().underline("Traefik SSL Certificate"), "\n");
1909
+ const sslCertExists = findExistingValue(
1910
+ "SSL_CRT",
1911
+ "SECRET",
1912
+ "ENVIRONMENT",
1913
+ existingValues
1914
+ );
1915
+ let ssl_answers = [];
1916
+ const traefikConfOption = (await (0, import_prompts2.default)(
1917
+ [
1918
+ {
1919
+ name: "traefikConfOption",
1920
+ type: "select",
1921
+ message: "Choose option to configure Traefik SSL Certificate",
1922
+ choices: [
1923
+ { title: "Let's Encrypt certificate", value: "lets_encrypt" },
1924
+ { title: "Static SSL certificate", value: "static_ssl" },
1925
+ { title: "Custom configuration", value: "custom" }
1926
+ ],
1927
+ initial: sslCertExists ? 1 : 0
1928
+ }
1929
+ ]
1930
+ )).traefikConfOption;
1931
+ if (traefikConfOption === "static_ssl") {
1932
+ ssl_answers = await askQuestionWithEditor(staticSSLCertQuestions, existingEnvironmentSecrets);
1933
+ }
1934
+ log("\n", import_kleur4.default.bold().underline("Storage"), "\n");
1935
+ let enableEncryption = false;
1936
+ const encryption_key_defined = findExistingValue(
1937
+ "ENCRYPTION_KEY",
1938
+ "SECRET",
1939
+ "ENVIRONMENT",
1940
+ existingValues
1941
+ );
1942
+ if (!encryption_key_defined && !environment_exists) {
1943
+ const answers_enable_encryption = await (0, import_prompts2.default)(
1944
+ [
1945
+ {
1946
+ name: "enableEncryption",
1947
+ type: "confirm",
1948
+ message: "Do you want to enable disk encryption?",
1949
+ scope: "ENVIRONMENT",
1950
+ initial: Boolean(process.env.ENABLE_ENCRYPTION)
1951
+ }
1952
+ ].map(questionToPrompt)
1953
+ );
1954
+ enableEncryption = answers_enable_encryption.enableEncryption;
1955
+ }
1956
+ if (enableEncryption && !encryption_key_defined && !environment_exists) {
1957
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow(" Disk encryption is enabled"));
1958
+ await promptAndStoreAnswer(environment, diskQuestions, existingValues);
1959
+ } else {
1960
+ if (!enableEncryption && !encryption_key_defined && environment_exists) {
1961
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().grey(`Environment ${environment} is already configured, skipping disk encryption question`));
1962
+ }
1963
+ const DISK_SPACE = findExistingValue(
1964
+ "DISK_SPACE",
1965
+ "VARIABLE",
1966
+ "ENVIRONMENT",
1967
+ existingValues
1968
+ );
1969
+ if (!DISK_SPACE) {
1970
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().grey("All available disk space at /data will be used"));
1971
+ } else {
1972
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Variable DISK_SPACE is read-only, allocated space:"), DISK_SPACE?.value);
1973
+ }
1974
+ }
1975
+ let backupHost = findExistingValue(
1976
+ "BACKUP_HOST",
1977
+ "VARIABLE",
1978
+ "ENVIRONMENT",
1979
+ existingValues
1980
+ )?.value || "";
1981
+ let backupType = "";
1982
+ let restoreEnvironmentName = findExistingValue(
1983
+ "RESTORE_ENVIRONMENT_NAME",
1984
+ "VARIABLE",
1985
+ "ENVIRONMENT",
1986
+ existingValues
1987
+ )?.value;
1988
+ let restoreType = findExistingValue(
1989
+ "RESTORE_ENVIRONMENT_MODE",
1990
+ "VARIABLE",
1991
+ "ENVIRONMENT",
1992
+ existingValues
1993
+ )?.value || process.env.RESTORE_ENVIRONMENT_MODE || "dump";
1994
+ log("\n", import_kleur4.default.bold().underline("Backup"));
1995
+ let configureBackup = backupHost ? true : false;
1996
+ if (!configureBackup && !restoreEnvironmentName) {
1997
+ configureBackup = await confirm2({
1998
+ message: "Do you want to configure backup?",
1999
+ default: Boolean(process.env.CONFIGURE_BACKUP)
2000
+ });
2001
+ }
2002
+ let backupHostPrivateKey = "";
2003
+ let backupHostPublicKey = "";
2004
+ if (configureBackup) {
2005
+ const backupAnswers = await promptAndStoreAnswer(
2006
+ environment,
2007
+ backupQuestions,
2008
+ existingValues
2009
+ );
2010
+ let backupHostPrivateKeyExists = findExistingValue(
2011
+ "BACKUP_HOST_PRIVATE_KEY",
2012
+ "SECRET",
2013
+ "ENVIRONMENT",
2014
+ existingValues
2015
+ );
2016
+ backupType = backupAnswers.backupType;
2017
+ backupHost = backupAnswers.backupHost || backupHost;
2018
+ if (!backupHostPrivateKeyExists) {
2019
+ const { publicKey, privateKey } = generateSSHKeyPair();
2020
+ backupHostPublicKey = publicKey;
2021
+ backupHostPrivateKey = privateKey;
2022
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow(`Generated new SSH key pair for backup host: ${backupHost}`));
2023
+ }
2024
+ } else {
2025
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Backup is disabled"));
2026
+ }
2027
+ log("\n", import_kleur4.default.bold().underline("Restore"));
2028
+ let configureRestore = restoreEnvironmentName ? true : false;
2029
+ if (!restoreEnvironmentName && !configureBackup) {
2030
+ configureRestore = await confirm2({
2031
+ message: "Do you want to configure restore?",
2032
+ default: Boolean(process.env.CONFIGURE_RESTORE)
2033
+ });
2034
+ }
2035
+ if (configureRestore) {
2036
+ const env_list_filtered = existingEnvironments.filter((env) => env !== environment);
2037
+ restoreEnvironmentName = await selectWithCustom(
2038
+ {
2039
+ message: "What is the name of your environment to restore?",
2040
+ choices: env_list_filtered.map((env) => ({
2041
+ name: env,
2042
+ value: env
2043
+ })),
2044
+ initial: restoreEnvironmentName
2045
+ }
2046
+ );
2047
+ restoreType = await select3(
2048
+ {
2049
+ message: `Select ${import_kleur4.default.yellow().bold(restoreEnvironmentName)} environment backup mode`,
2050
+ choices: [
2051
+ {
2052
+ name: "Full dump (daily full database backup)",
2053
+ value: "dump"
2054
+ },
2055
+ {
2056
+ name: "Differential (weekly full, daily diff backup)",
2057
+ value: "differential"
2058
+ }
2059
+ ]
2060
+ }
2061
+ );
2062
+ } else {
2063
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2064
+ }
2065
+ log("\n", import_kleur4.default.bold().underline("Monitoring"));
2066
+ await promptAndStoreAnswer(
2067
+ environment,
2068
+ databaseAndMonitoringQuestions,
2069
+ existingValues
2070
+ );
2071
+ const sentryDSNExists = findExistingValue(
2072
+ "SENTRY_DSN",
2073
+ "SECRET",
2074
+ "ENVIRONMENT",
2075
+ existingValues
2076
+ );
2077
+ log("\n", import_kleur4.default.bold().underline("Sentry"));
2078
+ if (sentryDSNExists) {
2079
+ await promptAndStoreAnswer(environment, sentryQuestions, existingValues);
2080
+ } else {
2081
+ const { useSentry } = await (0, import_prompts2.default)(
2082
+ [
2083
+ {
2084
+ name: "useSentry",
2085
+ type: "confirm",
2086
+ message: "Do you want to use Sentry?",
2087
+ initial: Boolean(process.env.SENTRY_DNS)
2088
+ }
2089
+ ]
2090
+ );
2091
+ if (useSentry) {
2092
+ await promptAndStoreAnswer(environment, sentryQuestions, existingValues);
2093
+ }
2094
+ }
2095
+ log("\n", import_kleur4.default.bold().underline("METABASE ADMIN"));
2096
+ await promptAndStoreAnswer(
2097
+ environment,
2098
+ metabaseAdminQuestions,
2099
+ existingValues
2100
+ );
2101
+ log("\n", import_kleur4.default.bold().underline("SMTP"));
2102
+ await promptAndStoreAnswer(environment, emailQuestions, existingValues);
2103
+ const allAnswers = ALL_ANSWERS.reduce((acc, answer) => {
2104
+ return { ...acc, ...answer };
2105
+ });
2106
+ const answerOrExisting = (variable, existingValue, fn) => fn(variable || existingValue?.value) || "";
2107
+ function findExistingOrDefine(name, type, scope, newValue) {
2108
+ return findExistingValue(name, type, scope, existingValues) ? null : process.env[name] || newValue;
2109
+ }
2110
+ const derivedUpdates = [
2111
+ {
2112
+ name: "GH_ENCRYPTION_PASSWORD",
2113
+ type: "SECRET",
2114
+ didExist: findExistingValue(
2115
+ "GH_ENCRYPTION_PASSWORD",
2116
+ "SECRET",
2117
+ "REPOSITORY",
2118
+ existingValues
2119
+ ),
2120
+ value: findExistingOrDefine(
2121
+ "GH_ENCRYPTION_PASSWORD",
2122
+ "SECRET",
2123
+ "REPOSITORY",
2124
+ generateLongPassword()
2125
+ ),
2126
+ scope: "REPOSITORY"
2127
+ }
2128
+ ];
2129
+ derivedUpdates.push({
2130
+ name: "NOTIFICATION_TRANSPORT",
2131
+ type: "VARIABLE",
2132
+ didExist: findExistingValue(
2133
+ "NOTIFICATION_TRANSPORT",
2134
+ "VARIABLE",
2135
+ "ENVIRONMENT",
2136
+ existingValues
2137
+ ),
2138
+ value: findExistingOrDefine(
2139
+ "NOTIFICATION_TRANSPORT",
2140
+ "VARIABLE",
2141
+ "ENVIRONMENT",
2142
+ "email"
2143
+ ),
2144
+ scope: "ENVIRONMENT"
2145
+ });
2146
+ derivedUpdates.push(...ssl_answers);
2147
+ if (configureBackup) {
2148
+ derivedUpdates.push({
2149
+ name: "BACKUP_ENCRYPTION_PASSPHRASE",
2150
+ type: "SECRET",
2151
+ didExist: findExistingValue(
2152
+ "BACKUP_ENCRYPTION_PASSPHRASE",
2153
+ "SECRET",
2154
+ "ENVIRONMENT",
2155
+ existingValues
2156
+ ),
2157
+ value: findExistingOrDefine(
2158
+ "BACKUP_ENCRYPTION_PASSPHRASE",
2159
+ "SECRET",
2160
+ "ENVIRONMENT",
2161
+ generateLongPassword()
2162
+ ),
2163
+ scope: "ENVIRONMENT"
2164
+ });
2165
+ }
2166
+ const applicationServerUpdates = [
2167
+ {
2168
+ name: "ELASTICSEARCH_SUPERUSER_PASSWORD",
2169
+ type: "SECRET",
2170
+ didExist: findExistingValue(
2171
+ "ELASTICSEARCH_SUPERUSER_PASSWORD",
2172
+ "SECRET",
2173
+ "ENVIRONMENT",
2174
+ existingValues
2175
+ ),
2176
+ value: findExistingOrDefine(
2177
+ "ELASTICSEARCH_SUPERUSER_PASSWORD",
2178
+ "SECRET",
2179
+ "ENVIRONMENT",
2180
+ generateLongPassword()
2181
+ ),
2182
+ scope: "ENVIRONMENT"
2183
+ },
2184
+ {
2185
+ name: "KIBANA_SYSTEM_PASSWORD",
2186
+ type: "SECRET",
2187
+ didExist: findExistingValue(
2188
+ "KIBANA_SYSTEM_PASSWORD",
2189
+ "SECRET",
2190
+ "ENVIRONMENT",
2191
+ existingValues
2192
+ ),
2193
+ value: findExistingOrDefine(
2194
+ "KIBANA_SYSTEM_PASSWORD",
2195
+ "SECRET",
2196
+ "ENVIRONMENT",
2197
+ generateLongPassword()
2198
+ ),
2199
+ scope: "ENVIRONMENT"
2200
+ },
2201
+ {
2202
+ name: "MINIO_ROOT_USER",
2203
+ type: "SECRET",
2204
+ didExist: findExistingValue(
2205
+ "MINIO_ROOT_USER",
2206
+ "SECRET",
2207
+ "ENVIRONMENT",
2208
+ existingValues
2209
+ ),
2210
+ value: findExistingOrDefine(
2211
+ "MINIO_ROOT_USER",
2212
+ "SECRET",
2213
+ "ENVIRONMENT",
2214
+ generateLongPassword()
2215
+ ),
2216
+ scope: "ENVIRONMENT"
2217
+ },
2218
+ {
2219
+ name: "MINIO_ROOT_PASSWORD",
2220
+ type: "SECRET",
2221
+ didExist: findExistingValue(
2222
+ "MINIO_ROOT_PASSWORD",
2223
+ "SECRET",
2224
+ "ENVIRONMENT",
2225
+ existingValues
2226
+ ),
2227
+ value: findExistingOrDefine(
2228
+ "MINIO_ROOT_PASSWORD",
2229
+ "SECRET",
2230
+ "ENVIRONMENT",
2231
+ generateLongPassword()
2232
+ ),
2233
+ scope: "ENVIRONMENT"
2234
+ },
2235
+ {
2236
+ name: "MONGODB_ADMIN_USER",
2237
+ type: "SECRET",
2238
+ didExist: findExistingValue(
2239
+ "MONGODB_ADMIN_USER",
2240
+ "SECRET",
2241
+ "ENVIRONMENT",
2242
+ existingValues
2243
+ ),
2244
+ value: findExistingOrDefine(
2245
+ "MONGODB_ADMIN_USER",
2246
+ "SECRET",
2247
+ "ENVIRONMENT",
2248
+ generateLongPassword()
2249
+ ),
2250
+ scope: "ENVIRONMENT"
2251
+ },
2252
+ {
2253
+ name: "MONGODB_ADMIN_PASSWORD",
2254
+ type: "SECRET",
2255
+ didExist: findExistingValue(
2256
+ "MONGODB_ADMIN_PASSWORD",
2257
+ "SECRET",
2258
+ "ENVIRONMENT",
2259
+ existingValues
2260
+ ),
2261
+ value: findExistingOrDefine(
2262
+ "MONGODB_ADMIN_PASSWORD",
2263
+ "SECRET",
2264
+ "ENVIRONMENT",
2265
+ generateLongPassword()
2266
+ ),
2267
+ scope: "ENVIRONMENT"
2268
+ },
2269
+ {
2270
+ name: "POSTGRES_USER",
2271
+ type: "SECRET",
2272
+ didExist: findExistingValue(
2273
+ "POSTGRES_USER",
2274
+ "SECRET",
2275
+ "ENVIRONMENT",
2276
+ existingValues
2277
+ ),
2278
+ value: findExistingOrDefine(
2279
+ "POSTGRES_USER",
2280
+ "SECRET",
2281
+ "ENVIRONMENT",
2282
+ generateLongPassword()
2283
+ ),
2284
+ scope: "ENVIRONMENT"
2285
+ },
2286
+ {
2287
+ name: "POSTGRES_PASSWORD",
2288
+ type: "SECRET",
2289
+ didExist: findExistingValue(
2290
+ "POSTGRES_PASSWORD",
2291
+ "SECRET",
2292
+ "ENVIRONMENT",
2293
+ existingValues
2294
+ ),
2295
+ value: findExistingOrDefine(
2296
+ "POSTGRES_PASSWORD",
2297
+ "SECRET",
2298
+ "ENVIRONMENT",
2299
+ generateLongPassword()
2300
+ ),
2301
+ scope: "ENVIRONMENT"
2302
+ },
2303
+ {
2304
+ name: "SUPER_USER_PASSWORD",
2305
+ type: "SECRET",
2306
+ didExist: findExistingValue(
2307
+ "SUPER_USER_PASSWORD",
2308
+ "SECRET",
2309
+ "ENVIRONMENT",
2310
+ existingValues
2311
+ ),
2312
+ value: findExistingOrDefine(
2313
+ "SUPER_USER_PASSWORD",
2314
+ "SECRET",
2315
+ "ENVIRONMENT",
2316
+ generateLongPassword()
2317
+ ),
2318
+ scope: "ENVIRONMENT"
2319
+ },
2320
+ {
2321
+ type: "VARIABLE",
2322
+ name: "ACTIVATE_USERS",
2323
+ value: "production" === environment_type ? "false" : "true",
2324
+ didExist: findExistingValue(
2325
+ "ACTIVATE_USERS",
2326
+ "VARIABLE",
2327
+ "ENVIRONMENT",
2328
+ existingValues
2329
+ ),
2330
+ scope: "ENVIRONMENT"
2331
+ },
2332
+ {
2333
+ type: "VARIABLE",
2334
+ name: "COUNTRY_CONFIG_HOST",
2335
+ value: answerOrExisting(
2336
+ allAnswers.domain,
2337
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2338
+ (val) => `https://countryconfig.${val}`
2339
+ ),
2340
+ didExist: findExistingValue(
2341
+ "COUNTRY_CONFIG_HOST",
2342
+ "VARIABLE",
2343
+ "ENVIRONMENT",
2344
+ existingValues
2345
+ ),
2346
+ scope: "ENVIRONMENT"
2347
+ },
2348
+ {
2349
+ type: "VARIABLE",
2350
+ name: "GATEWAY_HOST",
2351
+ value: answerOrExisting(
2352
+ allAnswers.domain,
2353
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2354
+ (val) => `https://gateway.${val}`
2355
+ ),
2356
+ didExist: findExistingValue(
2357
+ "GATEWAY_HOST",
2358
+ "VARIABLE",
2359
+ "ENVIRONMENT",
2360
+ existingValues
2361
+ ),
2362
+ scope: "ENVIRONMENT"
2363
+ },
2364
+ {
2365
+ type: "VARIABLE",
2366
+ name: "CONTENT_SECURITY_POLICY_WILDCARD",
2367
+ value: answerOrExisting(
2368
+ allAnswers.domain,
2369
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2370
+ (val) => `*.${val}`
2371
+ ),
2372
+ didExist: findExistingValue(
2373
+ "CONTENT_SECURITY_POLICY_WILDCARD",
2374
+ "VARIABLE",
2375
+ "ENVIRONMENT",
2376
+ existingValues
2377
+ ),
2378
+ scope: "ENVIRONMENT"
2379
+ },
2380
+ {
2381
+ type: "VARIABLE",
2382
+ name: "CLIENT_APP_URL",
2383
+ value: answerOrExisting(
2384
+ allAnswers.domain,
2385
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2386
+ (val) => `https://register.${val}`
2387
+ ),
2388
+ didExist: findExistingValue(
2389
+ "CLIENT_APP_URL",
2390
+ "VARIABLE",
2391
+ "ENVIRONMENT",
2392
+ existingValues
2393
+ ),
2394
+ scope: "ENVIRONMENT"
2395
+ },
2396
+ {
2397
+ type: "VARIABLE",
2398
+ name: "LOGIN_URL",
2399
+ value: answerOrExisting(
2400
+ allAnswers.domain,
2401
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2402
+ (val) => `https://login.${val}`
2403
+ ),
2404
+ didExist: findExistingValue(
2405
+ "LOGIN_URL",
2406
+ "VARIABLE",
2407
+ "ENVIRONMENT",
2408
+ existingValues
2409
+ ),
2410
+ scope: "ENVIRONMENT"
2411
+ },
2412
+ {
2413
+ type: "VARIABLE",
2414
+ name: "RESTORE_ENVIRONMENT_NAME",
2415
+ value: answerOrExisting(restoreEnvironmentName, findExistingValue(
2416
+ "RESTORE_ENVIRONMENT_NAME",
2417
+ "VARIABLE",
2418
+ "ENVIRONMENT",
2419
+ existingValues
2420
+ ), (val) => val || ""),
2421
+ didExist: findExistingValue(
2422
+ "RESTORE_ENVIRONMENT_NAME",
2423
+ "VARIABLE",
2424
+ "ENVIRONMENT",
2425
+ existingValues
2426
+ ),
2427
+ scope: "ENVIRONMENT"
2428
+ }
2429
+ ];
2430
+ if (enableEncryption) {
2431
+ applicationServerUpdates.push({
2432
+ name: "ENCRYPTION_KEY",
2433
+ type: "SECRET",
2434
+ didExist: findExistingValue(
2435
+ "ENCRYPTION_KEY",
2436
+ "SECRET",
2437
+ "ENVIRONMENT",
2438
+ existingValues
2439
+ ),
2440
+ value: findExistingOrDefine(
2441
+ "ENCRYPTION_KEY",
2442
+ "SECRET",
2443
+ "ENVIRONMENT",
2444
+ generateLongPassword()
2445
+ ),
2446
+ scope: "ENVIRONMENT"
2447
+ });
2448
+ }
2449
+ if (configureBackup && backupHostPrivateKey && backupHostPublicKey) {
2450
+ applicationServerUpdates.push({
2451
+ name: "BACKUP_HOST_PRIVATE_KEY",
2452
+ type: "SECRET",
2453
+ didExist: void 0,
2454
+ value: backupHostPrivateKey,
2455
+ scope: "ENVIRONMENT"
2456
+ });
2457
+ applicationServerUpdates.push({
2458
+ name: "BACKUP_HOST_PUBLIC_KEY",
2459
+ type: "SECRET",
2460
+ didExist: void 0,
2461
+ value: backupHostPublicKey,
2462
+ scope: "ENVIRONMENT"
2463
+ });
2464
+ }
2465
+ derivedUpdates.push(...applicationServerUpdates);
2466
+ const updates = getAnswers(existingValues).concat(
2467
+ ...derivedUpdates.filter(
2468
+ (update) => update.value !== null
2469
+ )
2470
+ ).filter(
2471
+ (variable) => Boolean(variable.value) && // Only update values that changed
2472
+ (variable.type !== "VARIABLE" || variable.value !== variable.didExist?.value)
2473
+ );
2474
+ storeSecrets(environment, updates);
2475
+ const newSecrets = updates.filter(
2476
+ (update) => update.type === "SECRET" && !update.didExist
2477
+ );
2478
+ const updatedSecrets = updates.filter(
2479
+ (update) => update.type === "SECRET" && Boolean(update.didExist)
2480
+ );
2481
+ const newVariables = updates.filter(
2482
+ (update) => update.type === "VARIABLE" && !update.didExist
2483
+ );
2484
+ const updatedVariables = updates.filter(
2485
+ (update) => update.type === "VARIABLE" && Boolean(update.didExist)
2486
+ );
2487
+ const unknownVariables = existingValues.filter((value) => {
2488
+ return !ALL_QUESTIONS.find(
2489
+ (question) => question.valueLabel === value.name && question.valueType === value.type && question.scope === value.scope
2490
+ );
2491
+ });
2492
+ log("");
2493
+ if (newSecrets.length > 0) {
2494
+ log(
2495
+ import_kleur4.default.yellow(
2496
+ `The following secrets will be added to Github for environment ${environment}:`
2497
+ )
2498
+ );
2499
+ newSecrets.filter(({ scope }) => scope === "ENVIRONMENT").forEach((secret) => {
2500
+ log(secret.name, "=", secret.value);
2501
+ });
2502
+ log("");
2503
+ log(
2504
+ import_kleur4.default.yellow(`The following secrets will be added to Github repository:`)
2505
+ );
2506
+ newSecrets.filter(({ scope }) => scope === "REPOSITORY").forEach((secret) => {
2507
+ log(secret.name, "=", secret.value);
2508
+ });
2509
+ log("");
2510
+ }
2511
+ if (updatedSecrets.length > 0) {
2512
+ log(
2513
+ import_kleur4.default.yellow(
2514
+ `The following secrets will be updated in Github for environment ${environment}:`
2515
+ )
2516
+ );
2517
+ updatedSecrets.forEach((secret) => {
2518
+ log(secret.name, "=", secret.value);
2519
+ });
2520
+ log("");
2521
+ }
2522
+ if (newVariables.length > 0) {
2523
+ log(
2524
+ import_kleur4.default.yellow(
2525
+ `The following variables will be added to Github for environment ${environment}:`
2526
+ )
2527
+ );
2528
+ newVariables.forEach((variable) => {
2529
+ log(variable.name, "=", variable.value);
2530
+ });
2531
+ log("");
2532
+ }
2533
+ if (updatedVariables.length > 0) {
2534
+ log(
2535
+ import_kleur4.default.yellow(
2536
+ `The following variables will be updated in Github for environment ${environment}:`
2537
+ )
2538
+ );
2539
+ updatedVariables.forEach((variable) => {
2540
+ log(
2541
+ variable.name,
2542
+ "=",
2543
+ variable.value,
2544
+ `(was ${variable.didExist?.value})`
2545
+ );
2546
+ });
2547
+ log("");
2548
+ }
2549
+ if (unknownVariables.length > 0) {
2550
+ log(
2551
+ import_kleur4.default.yellow(
2552
+ `The following unknown variables/secrets were stored in Github are not managed by this script:`
2553
+ )
2554
+ );
2555
+ log("");
2556
+ log(import_kleur4.default.blue(`Repository:`));
2557
+ unknownVariables.filter(({ scope }) => scope === "REPOSITORY").forEach((variable) => {
2558
+ log(import_kleur4.default.cyan(variable.type) + ":", variable.name);
2559
+ });
2560
+ log("");
2561
+ log(import_kleur4.default.blue(`Environment:`));
2562
+ unknownVariables.filter(({ scope }) => scope === "ENVIRONMENT").forEach((variable) => {
2563
+ log(import_kleur4.default.cyan(variable.type) + ":", variable.name);
2564
+ });
2565
+ log("");
2566
+ log(
2567
+ import_kleur4.default.yellow(
2568
+ `These variables will not be updated by this script. If you want to update them, you will need to do so manually.`
2569
+ )
2570
+ );
2571
+ log("");
2572
+ }
2573
+ if ([].concat(newSecrets).concat(updatedSecrets).concat(newVariables).concat(updatedVariables).length === 0) {
2574
+ process.exit(0);
2575
+ }
2576
+ const saveChanges = await confirm2({
2577
+ message: "Do you want to continue?",
2578
+ default: true
2579
+ });
2580
+ if (!saveChanges) {
2581
+ process.exit(0);
2582
+ }
2583
+ for (const newSecret of newSecrets) {
2584
+ log(`Creating secret ${newSecret.name} with value ${newSecret.value}`);
2585
+ if (newSecret.scope === "ENVIRONMENT") {
2586
+ await createEnvironmentSecret(
2587
+ octokit,
2588
+ repositoryId,
2589
+ environment,
2590
+ newSecret.name,
2591
+ newSecret.value,
2592
+ githubOrganisation,
2593
+ githubRepository
2594
+ );
2595
+ } else {
2596
+ await createRepositorySecret(
2597
+ octokit,
2598
+ repositoryId,
2599
+ newSecret.name,
2600
+ newSecret.value,
2601
+ githubOrganisation,
2602
+ githubRepository
2603
+ );
2604
+ }
2605
+ }
2606
+ for (const updatedSecret of updatedSecrets) {
2607
+ log(
2608
+ `Updating secret ${updatedSecret.name} with value ${updatedSecret.value}`
2609
+ );
2610
+ if (updatedSecret.scope === "ENVIRONMENT") {
2611
+ await createEnvironmentSecret(
2612
+ octokit,
2613
+ repositoryId,
2614
+ environment,
2615
+ updatedSecret.name,
2616
+ updatedSecret.value,
2617
+ githubOrganisation,
2618
+ githubRepository
2619
+ );
2620
+ } else {
2621
+ await createRepositorySecret(
2622
+ octokit,
2623
+ repositoryId,
2624
+ updatedSecret.name,
2625
+ updatedSecret.value,
2626
+ githubOrganisation,
2627
+ githubRepository
2628
+ );
2629
+ }
2630
+ }
2631
+ for (const newVariable of newVariables) {
2632
+ log(`Creating variable ${newVariable.name} with value ${newVariable.value}`);
2633
+ if (newVariable.scope === "ENVIRONMENT") {
2634
+ await createEnvironmentVariable(
2635
+ octokit,
2636
+ repositoryId,
2637
+ environment,
2638
+ newVariable.name,
2639
+ newVariable.value
2640
+ );
2641
+ } else {
2642
+ await createRepositoryVariable(
2643
+ octokit,
2644
+ repositoryId,
2645
+ newVariable.name,
2646
+ newVariable.value
2647
+ );
2648
+ }
2649
+ }
2650
+ for (const updatedVariable of updatedVariables) {
2651
+ log(
2652
+ `Updating variable ${updatedVariable.name} with value ${updatedVariable.value}`
2653
+ );
2654
+ if (updatedVariable.scope === "ENVIRONMENT") {
2655
+ await updateEnvironmentVariable(
2656
+ octokit,
2657
+ repositoryId,
2658
+ environment,
2659
+ updatedVariable.name,
2660
+ updatedVariable.value
2661
+ );
2662
+ } else {
2663
+ await updateRepositoryVariable(
2664
+ octokit,
2665
+ repositoryId,
2666
+ updatedVariable.name,
2667
+ updatedVariable.value
2668
+ );
2669
+ }
2670
+ }
2671
+ log(
2672
+ import_kleur4.default.green(
2673
+ `Successfully updated Github secrets and variables for environment ${environment}`
2674
+ )
2675
+ );
2676
+ log("\n", import_kleur4.default.bold().underline("Running configuration files updates"));
2677
+ generateInventory(
2678
+ environment,
2679
+ {
2680
+ kube_worker_nodes: kubeWorkerNodes,
2681
+ kube_api_host: infrastructure.kubeAPIHost || "",
2682
+ backup_host: backupHost || "",
2683
+ users
2684
+ }
2685
+ );
2686
+ copyChartsValues(
2687
+ environment,
2688
+ {
2689
+ env: environment,
2690
+ environment_type,
2691
+ // FIXME: In general that should be environment_type,
2692
+ // Hardcode like this blocks us from being generic:
2693
+ // https://github.com/opencrvs/opencrvs-core/issues/11171
2694
+ two_fa_enabled: environment !== "production" ? false : true,
2695
+ backup_enabled: configureBackup ? true : false,
2696
+ restore_enabled: restoreEnvironmentName ? true : false,
2697
+ restore_environment_name: restoreEnvironmentName || "",
2698
+ restore_type: restoreType,
2699
+ traefik_mode: traefikConfOption,
2700
+ backup_type: backupType
2701
+ }
2702
+ );
2703
+ let addon_message = kubeWorkerNodes.length > 0 || configureBackup ? `--------------------------------------------------------------------------------------------
2704
+
2705
+ \u27A1\uFE0F ${import_kleur4.default.bold().yellow("COPY the SSH public key from the master VM to your clipboard")}
2706
+ --------------------------------------------------------------------------------------------
2707
+ ` : "";
2708
+ addon_message += kubeWorkerNodes.length > 0 ? `\u27A1\uFE0F ${import_kleur4.default.bold().yellow("Run following command on Kubernetes worker VM to create provision user and setup SSH key:")}
2709
+
2710
+ curl -sfL https://raw.githubusercontent.com/opencrvs/infrastructure/refs/heads/develop/scripts/bootstrap/opencrvs-bootstrap.sh -o opencrvs-bootstrap.sh && \\
2711
+ bash opencrvs-bootstrap.sh --ssh-public-key "${import_kleur4.default.bold("[PUT PROVISION USER PUBLIC KEY FROM MASTER NODE]")}"
2712
+ ` : "";
2713
+ addon_message += configureBackup ? `
2714
+ \u27A1\uFE0F ${import_kleur4.default.bold().yellow("Run following command on backup server to create provision user and setup SSH key:")}
2715
+ curl -sfL https://raw.githubusercontent.com/opencrvs/infrastructure/refs/heads/develop/scripts/bootstrap/opencrvs-bootstrap.sh -o opencrvs-bootstrap.sh && \\
2716
+ bash opencrvs-bootstrap.sh --ssh-public-key "${import_kleur4.default.bold("[PUT PROVISION USER PUBLIC KEY FROM MASTER NODE]")}"` : "";
2717
+ log(`
2718
+ ${import_kleur4.default.yellow("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}
2719
+ Follow the steps below to complete the setup of your environment:
2720
+ ${import_kleur4.default.yellow("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}
2721
+ \u27A1\uFE0F ${import_kleur4.default.bold().yellow("Run following command on Kubernetes master VM to bootstrap self-hosted runner:")}
2722
+
2723
+ curl -sfL https://raw.githubusercontent.com/opencrvs/infrastructure/refs/heads/develop/scripts/bootstrap/opencrvs-bootstrap.sh -o opencrvs-bootstrap.sh && \\
2724
+ bash opencrvs-bootstrap.sh --owner ${githubOrganisation} \\
2725
+ --repo ${githubRepository} \\
2726
+ --env ${environment} \\
2727
+ --token ${githubToken} \\
2728
+ --enable-runner
2729
+
2730
+ ${addon_message}
2731
+
2732
+ ${import_kleur4.default.yellow("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}
2733
+ ${import_kleur4.default.yellow("Please KINDLY read hints above")}
2734
+ `);
2735
+ log("\nAll variables stored in", import_kleur4.default.cyan(`.env.${environment}`));
2736
+ log(import_kleur4.default.bold().yellow("DO NOT COMMIT THIS FILE TO GIT!"));
2737
+ })();
2738
+ }
2739
+ });
2740
+
2741
+ // src/environment/update-workflows.ts
2742
+ var update_workflows_exports = {};
2743
+ __export(update_workflows_exports, {
2744
+ updateWorkflowEnvironments: () => updateWorkflowEnvironments
2745
+ });
2746
+ async function extractInfrastructureNames() {
2747
+ const files = glob.sync("infrastructure/server-setup/inventory/*.yml");
2748
+ const infraEnvironments = files.map((file) => (0, import_path28.basename)(file, ".yml"));
2749
+ if (infraEnvironments.length === 0) {
2750
+ console.log("\u26A0\uFE0F Warning: No environment directories found in infrastructure/server-setup/inventory/");
2751
+ return [];
2752
+ }
2753
+ log("\u{1F50D} Found infrastructure configurations:", infraEnvironments.join(", "));
2754
+ return infraEnvironments;
2755
+ }
2756
+ async function extractEnvironmentNames() {
2757
+ const entries = await (0, import_promises.readdir)("environments");
2758
+ const environments = entries.filter((entry) => {
2759
+ const fullPath = (0, import_path28.join)("environments", entry);
2760
+ return (0, import_fs9.statSync)(fullPath).isDirectory();
2761
+ });
2762
+ if (environments.length === 0) {
2763
+ console.log("\u26A0\uFE0F Warning: No environment directories found in environments/");
2764
+ return [];
2765
+ }
2766
+ log("\u{1F50D} Found OpenCRVS configurations:", environments.join(", "));
2767
+ return environments;
2768
+ }
2769
+ function updateOptionsInYaml(content, envList) {
2770
+ const optionsRegex = /([ ]*options:[ ]*\n)((?:[ ]*-[^\n]*\n)+)/;
2771
+ const match = content.match(optionsRegex);
2772
+ if (!match) {
2773
+ throw new Error("Could not find options array in workflow file");
2774
+ }
2775
+ const firstItemMatch = match[2].match(/^([ ]*)-/);
2776
+ const itemIndent = firstItemMatch ? firstItemMatch[1] : " ";
2777
+ const newOptions = match[1] + envList.map((env) => `${itemIndent}- ${env}`).join("\n") + "\n";
2778
+ return content.replace(optionsRegex, newOptions);
2779
+ }
2780
+ async function updateWorkflows(envList, config) {
2781
+ const { workflows } = config;
2782
+ for (const workflowPath of workflows) {
2783
+ try {
2784
+ const fileContents = (0, import_fs9.readFileSync)(workflowPath, "utf8");
2785
+ const workflowData = yaml2.load(fileContents);
2786
+ if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
2787
+ throw new Error("Workflow does not have the expected structure: on.workflow_dispatch.inputs.environment.options");
2788
+ }
2789
+ const updatedContent = updateOptionsInYaml(fileContents, envList);
2790
+ (0, import_fs9.writeFileSync)(workflowPath, updatedContent, "utf8");
2791
+ log(` \u2713 Successfully updated ${workflowPath}`);
2792
+ } catch (error4) {
2793
+ console.error(`
2794
+ \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`);
2795
+ console.error(`\u2717 Failed to update ${workflowPath}:`, error4);
2796
+ throw error4;
2797
+ }
2798
+ }
2799
+ }
2800
+ async function updateWorkflowEnvironments() {
2801
+ try {
2802
+ let didUpdateWorkflows = false;
2803
+ const infraEnvironments = await extractInfrastructureNames();
2804
+ if (infraEnvironments.length > 0) {
2805
+ console.log("\u{1F504} Updating infrastructure workflows:");
2806
+ await updateWorkflows(infraEnvironments, {
2807
+ workflows: [
2808
+ ".github/workflows/provision.yml",
2809
+ ".github/workflows/reset-2fa.yml"
2810
+ ],
2811
+ path: "on.workflow_dispatch.inputs.environment.options"
2812
+ });
2813
+ didUpdateWorkflows = true;
2814
+ }
2815
+ const environments = await extractEnvironmentNames();
2816
+ if (environments.length > 0) {
2817
+ const workflows = [
2818
+ ".github/workflows/deploy-dependencies.yml",
2819
+ ".github/workflows/deploy-opencrvs.yml",
2820
+ ".github/workflows/clear-all-data.yml",
2821
+ ".github/workflows/seed-data.yml",
2822
+ ".github/workflows/reindex.yml",
2823
+ ".github/workflows/github-to-k8s-sync-env.yml"
2824
+ ];
2825
+ log("\u{1F4CB} Updating OpenCRVS application workflows:");
2826
+ await updateWorkflows(environments, {
2827
+ workflows,
2828
+ path: "on.workflow_dispatch.inputs.environment.options"
2829
+ });
2830
+ didUpdateWorkflows = true;
2831
+ }
2832
+ if (didUpdateWorkflows) {
2833
+ success("\u2705 Workflow updates completed successfully!");
2834
+ } else {
2835
+ log("\u2139\uFE0F No workflows were updated.");
2836
+ }
2837
+ } catch (error4) {
2838
+ console.error("\n\u274C Error updating workflows:", error4);
2839
+ process.exit(1);
2840
+ }
2841
+ }
2842
+ var import_promises, import_fs9, import_path28, glob, yaml2;
2843
+ var init_update_workflows = __esm({
2844
+ "src/environment/update-workflows.ts"() {
2845
+ "use strict";
2846
+ import_promises = require("fs/promises");
2847
+ import_fs9 = require("fs");
2848
+ import_path28 = require("path");
2849
+ glob = __toESM(require("glob"));
2850
+ yaml2 = __toESM(require("js-yaml"));
2851
+ init_logger();
2852
+ }
2853
+ });
2854
+
2855
+ // src/environment/users.ts
2856
+ var users_exports = {};
2857
+ async function select4(options) {
2858
+ const inquirer = await import("@inquirer/prompts");
2859
+ return inquirer.select(options);
2860
+ }
2861
+ async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inventory/") {
2862
+ if (!fs8.existsSync(dirPath)) {
2863
+ throw Error(`Directory ${dirPath} doesn't exist`);
2864
+ }
2865
+ const files = fs8.readdirSync(dirPath).filter((file) => {
2866
+ const filePath = path26.join(dirPath, file);
2867
+ const isFile = fs8.statSync(filePath).isFile();
2868
+ const ext = path26.extname(file).slice(1).toLowerCase();
2869
+ return isFile && (ext === "yml" || ext === "yaml");
2870
+ }).sort();
2871
+ if (files.length === 0) {
2872
+ throw Error(`No environment configuration files found at ${dirPath}`);
2873
+ }
2874
+ const choices = files.map((file) => ({
2875
+ name: path26.basename(file, path26.extname(file)),
2876
+ value: path26.join(dirPath, file)
2877
+ }));
2878
+ const selectedFile = await select4({
2879
+ message: "Select environment (inventory file) to load users:",
2880
+ choices
2881
+ });
2882
+ return selectedFile;
2883
+ }
2884
+ async function manageUsersStandalone() {
2885
+ console.log("\n", import_kleur5.default.bold().underline("Manage users"), "\n");
2886
+ const inventory_file = await selectInventoryFile();
2887
+ manageUsers(inventory_file);
2888
+ }
2889
+ var fs8, path26, import_kleur5;
2890
+ var init_users = __esm({
2891
+ "src/environment/users.ts"() {
2892
+ "use strict";
2893
+ fs8 = __toESM(require("fs"));
2894
+ path26 = __toESM(require("path"));
2895
+ import_kleur5 = __toESM(require("kleur"));
2896
+ init_manage_users();
2897
+ manageUsersStandalone();
2898
+ }
2899
+ });
2900
+
2901
+ // src/environment/swarm-to-k8s.ts
2902
+ var swarm_to_k8s_exports = {};
2903
+ var path27, import_kleur6, import_core2;
2904
+ var init_swarm_to_k8s = __esm({
2905
+ "src/environment/swarm-to-k8s.ts"() {
2906
+ "use strict";
2907
+ path27 = __toESM(require("path"));
2908
+ import_kleur6 = __toESM(require("kleur"));
2909
+ init_logger();
2910
+ init_utils();
2911
+ init_templates();
2912
+ import_core2 = require("@octokit/core");
2913
+ init_ssh_keygen();
2914
+ init_github();
2915
+ (async () => {
2916
+ log(import_kleur6.default.bold(
2917
+ "------------------------------------------------\nOpenCRVS Infrastructure migration script: \nMigrating Swarm configurations to Kubernetes\n------------------------------------------------\n"
2918
+ ));
2919
+ const environment_type = process.env.ENVIRONMENT_TYPE || "production";
2920
+ const environment = process.env.ENVIRONMENT || "";
2921
+ const githubToken = process.env.INFRA_TOKEN || "";
2922
+ const githubOrganisation = process.env.INFRA_ORGANISATION || "";
2923
+ const githubRepository = process.env.INFRA_REPOSITORY || "";
2924
+ if (!environment) {
2925
+ error("\n", "Environment variable ENVIRONMENT is not set. Exiting.");
2926
+ process.exit(1);
2927
+ }
2928
+ if (!githubToken) {
2929
+ error("\n", "Environment variable GITHUB_TOKEN is not set. Exiting.");
2930
+ process.exit(1);
2931
+ }
2932
+ if (!githubOrganisation) {
2933
+ error("\n", "Environment variable INFRA_ORGANISATION is not set. Exiting.");
2934
+ process.exit(1);
2935
+ }
2936
+ if (!githubRepository) {
2937
+ error("\n", "Environment variable INFRA_REPOSITORY is not set. Exiting.");
2938
+ process.exit(1);
2939
+ }
2940
+ if (["backup", "jumpbox"].includes(environment)) {
2941
+ info(` > ${environment} environment will not be migrated, see migration notes`);
2942
+ process.exit(0);
2943
+ }
2944
+ log(import_kleur6.default.bold().underline("Migration properties:"));
2945
+ log(` \u2713 Environment: ${environment}`);
2946
+ const old_inventory_path = process.env.OLD_INVENTORY_PATH || "";
2947
+ if (!old_inventory_path) {
2948
+ error("\n", "Environment variable OLD_INVENTORY_PATH is not set. Exiting.");
2949
+ log("\n", "Old inventory path is required to read existing Swarm configurations.");
2950
+ process.exit(1);
2951
+ }
2952
+ const ansible_inventory = path27.join(old_inventory_path, environment + ".yml");
2953
+ const data = readYamlFile(ansible_inventory);
2954
+ log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
2955
+ const master = dockerManagerFirst(data) || "";
2956
+ log(` \u2713 Kubernetes API Host (Docker Manager): ${master}`);
2957
+ const users = extractAndModifyUsers(data);
2958
+ const kube_worker_nodes = extractWorkerNodes(data);
2959
+ log(` \u2713 Worker nodes: ${kube_worker_nodes.join(", ")}`);
2960
+ const backup_host = extractBackupNode(data);
2961
+ log(` \u2713 Backup host: ${backup_host}`);
2962
+ generateInventory(
2963
+ environment,
2964
+ {
2965
+ kube_worker_nodes,
2966
+ users,
2967
+ backup_host: environment === "production" ? backup_host : "",
2968
+ kube_api_host: master
2969
+ }
2970
+ );
2971
+ copyChartsValues(
2972
+ environment,
2973
+ {
2974
+ env: environment,
2975
+ environment_type,
2976
+ // FIXME: In general that should be environment_type,
2977
+ // Hardcode like this blocks us from being generic:
2978
+ // https://github.com/opencrvs/opencrvs-core/issues/11171
2979
+ two_fa_enabled: environment !== "production" ? false : true,
2980
+ backup_enabled: environment === "production" ? "true" : "false",
2981
+ restore_enabled: environment === "staging" ? "true" : "false",
2982
+ restore_environment_name: environment === "staging" ? "production" : "",
2983
+ restore_type: "dump",
2984
+ traefik_mode: "static_ssl",
2985
+ backup_type: "dump"
2986
+ }
2987
+ );
2988
+ if (environment === "staging") {
2989
+ const octokit = new import_core2.Octokit({
2990
+ auth: githubToken
2991
+ });
2992
+ const repositoryId = await getRepositoryId(
2993
+ octokit,
2994
+ githubOrganisation,
2995
+ githubRepository
2996
+ );
2997
+ try {
2998
+ await createEnvironmentVariable(
2999
+ octokit,
3000
+ repositoryId,
3001
+ environment,
3002
+ "RESTORE_ENVIRONMENT_NAME",
3003
+ "production"
3004
+ );
3005
+ } catch (err) {
3006
+ error(`Failed to create variable RESTORE_ENVIRONMENT_NAME for environment ${environment}:`, err);
3007
+ }
3008
+ }
3009
+ if (environment === "production") {
3010
+ const octokit = new import_core2.Octokit({
3011
+ auth: githubToken
3012
+ });
3013
+ console.log("Fetching repository ID for:", githubOrganisation, githubRepository);
3014
+ const repositoryId = await getRepositoryId(
3015
+ octokit,
3016
+ githubOrganisation,
3017
+ githubRepository
3018
+ );
3019
+ console.log("Repository ID:", repositoryId);
3020
+ const { publicKey, privateKey } = generateSSHKeyPair();
3021
+ const secretsToCreate = {
3022
+ BACKUP_HOST_PRIVATE_KEY: privateKey,
3023
+ BACKUP_HOST_PUBLIC_KEY: publicKey,
3024
+ BACKUP_SERVER_USER: "backup"
3025
+ };
3026
+ const variablesToCreate = {
3027
+ BACKUP_HOST: backup_host,
3028
+ KUBE_WORKER_NODES: kube_worker_nodes.join(",")
3029
+ };
3030
+ for (const [secretName, secretValue] of Object.entries(secretsToCreate)) {
3031
+ try {
3032
+ await createEnvironmentSecret(
3033
+ octokit,
3034
+ repositoryId,
3035
+ environment,
3036
+ secretName,
3037
+ secretValue,
3038
+ githubOrganisation,
3039
+ githubRepository
3040
+ );
3041
+ log(` \u2713 Created secret ${secretName} for environment ${environment}`);
3042
+ } catch (err) {
3043
+ error(`Failed to create secret ${secretName} for environment ${environment}:`, err);
3044
+ }
3045
+ }
3046
+ for (const [variableName, variableValue] of Object.entries(variablesToCreate)) {
3047
+ try {
3048
+ await createEnvironmentVariable(
3049
+ octokit,
3050
+ repositoryId,
3051
+ environment,
3052
+ variableName,
3053
+ variableValue
3054
+ );
3055
+ log(` \u2713 Created variable ${variableName} for environment ${environment}`);
3056
+ } catch (err) {
3057
+ error(`Failed to create variable ${variableName} for environment ${environment}:`, err);
3058
+ }
3059
+ }
3060
+ }
3061
+ })();
3062
+ }
3063
+ });
25
3064
 
26
3065
  // src/migrations/v2.0/remove-review-from-register-action.ts
27
3066
  var import_ts_morph = require("ts-morph");
@@ -1883,9 +4922,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1883
4922
  }
1884
4923
  return replacedCount;
1885
4924
  }
1886
- function resolveConfigChain(configObj, path23) {
4925
+ function resolveConfigChain(configObj, path28) {
1887
4926
  let current = configObj;
1888
- for (const key of path23) {
4927
+ for (const key of path28) {
1889
4928
  if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1890
4929
  const prop = current.getProperty(key);
1891
4930
  if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
@@ -2120,6 +5159,10 @@ Done. Converted ${convertedCount} config file(s), replaced ${totalReplaced} rout
2120
5159
  var import_ts_morph11 = require("ts-morph");
2121
5160
  var import_path11 = __toESM(require("path"));
2122
5161
 
5162
+ // ../commons/src/scopes.deprecated.do-not-use.ts
5163
+ var z4 = __toESM(require("zod/v4"));
5164
+ var import_lodash = require("lodash");
5165
+
2123
5166
  // ../commons/src/scopes.ts
2124
5167
  var z3 = __toESM(require("zod/v4"));
2125
5168
  var qs = __toESM(require("qs"));
@@ -2296,12 +5339,14 @@ var SystemScopeType = z3.enum([
2296
5339
  "organisation.read-locations",
2297
5340
  "user.read",
2298
5341
  "user.create",
2299
- "user.edit"
5342
+ "user.edit",
5343
+ "user.search"
2300
5344
  ]);
2301
5345
  var UserScopeType = SystemScopeType.extract([
2302
5346
  "user.read",
2303
5347
  "user.create",
2304
- "user.edit"
5348
+ "user.edit",
5349
+ "user.search"
2305
5350
  ]);
2306
5351
  var ScopesWithRoleOption = UserScopeType.extract(["user.edit", "user.create"]);
2307
5352
  var UserScopeV2 = z3.discriminatedUnion("type", [
@@ -2310,7 +5355,7 @@ var UserScopeV2 = z3.discriminatedUnion("type", [
2310
5355
  options: AllUserScopeOptions.optional()
2311
5356
  }),
2312
5357
  z3.object({
2313
- type: UserScopeType.extract(["user.read"]),
5358
+ type: UserScopeType.extract(["user.read", "user.search"]),
2314
5359
  options: AccessLevelOptions.optional()
2315
5360
  })
2316
5361
  ]);
@@ -2362,8 +5407,8 @@ var flattenScope = (scope) => ({
2362
5407
  type: scope.type,
2363
5408
  ..."options" in scope ? scope.options : {}
2364
5409
  });
2365
- var unflattenScope = (input) => {
2366
- const { type, ...options } = input;
5410
+ var unflattenScope = (input3) => {
5411
+ const { type, ...options } = input3;
2367
5412
  return { type, options };
2368
5413
  };
2369
5414
  var EncodedScope2 = z3.string().brand("EncodedScope");
@@ -2376,22 +5421,29 @@ var encodeScope = (scope) => {
2376
5421
  encode: false
2377
5422
  });
2378
5423
  };
2379
- var decodeScope = (query) => {
2380
- const scope = qs.parse(query, {
5424
+ var decodedScopeCache = /* @__PURE__ */ new Map();
5425
+ var decodeScope = (encodedScope) => {
5426
+ if (decodedScopeCache.has(encodedScope)) {
5427
+ return decodedScopeCache.get(encodedScope);
5428
+ }
5429
+ const scope = qs.parse(encodedScope, {
2381
5430
  ignoreQueryPrefix: true,
2382
5431
  comma: true,
2383
5432
  allowDots: true
2384
5433
  });
2385
5434
  const unflattenedScope = unflattenScope(scope);
2386
- return Scope2.safeParse(unflattenedScope)?.data;
5435
+ const result = Scope2.safeParse(unflattenedScope)?.data;
5436
+ decodedScopeCache.set(encodedScope, result);
5437
+ return result;
2387
5438
  };
2388
5439
  var DEFAULT_SCOPE_OPTIONS = {
2389
5440
  placeOfEvent: JurisdictionFilter.enum.all,
2390
- accessLevel: JurisdictionFilter.enum.all
5441
+ accessLevel: JurisdictionFilter.enum.all,
5442
+ registeredIn: JurisdictionFilter.enum.all,
5443
+ declaredIn: JurisdictionFilter.enum.all
2391
5444
  };
2392
5445
 
2393
5446
  // ../commons/src/scopes.deprecated.do-not-use.ts
2394
- var z4 = __toESM(require("zod/v4"));
2395
5447
  var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2396
5448
  var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2397
5449
  var SearchScope = z4.object({
@@ -2625,6 +5677,74 @@ var legacyScopeToV2Scope = (v1Scope) => {
2625
5677
  }
2626
5678
  throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2627
5679
  };
5680
+ var MERGEABLE_USER_SCOPE_TYPES = ["user.create", "user.edit"];
5681
+ function isMergeableUserScopeType(type) {
5682
+ return MERGEABLE_USER_SCOPE_TYPES.includes(type);
5683
+ }
5684
+ function decodeLegacyScope(legacy) {
5685
+ const encoded = legacyScopeToV2Scope(legacy);
5686
+ const scope = decodeScope(encoded);
5687
+ if (!scope) {
5688
+ throw new Error(
5689
+ `Could not decode migrated scope from legacy '${legacy}' (encoded: '${encoded}').`
5690
+ );
5691
+ }
5692
+ return { legacy, scope };
5693
+ }
5694
+ function groupByType(entries) {
5695
+ return entries.reduce(
5696
+ (groups, entry) => ({
5697
+ ...groups,
5698
+ [entry.scope.type]: [...groups[entry.scope.type] ?? [], entry]
5699
+ }),
5700
+ {}
5701
+ );
5702
+ }
5703
+ function deduplicateEntries(entries) {
5704
+ return entries.filter(
5705
+ (entry, index) => entries.findIndex((e) => (0, import_lodash.isEqual)(e.scope, entry.scope)) === index
5706
+ );
5707
+ }
5708
+ function mergeEntries(type, entries) {
5709
+ const optionsList = entries.map(
5710
+ (e) => "options" in e.scope && e.scope.options ? e.scope.options : {}
5711
+ );
5712
+ const allKeys = optionsList.flatMap(
5713
+ (opts) => Object.keys(opts).filter((k) => opts[k] !== void 0)
5714
+ );
5715
+ const conflictKey = allKeys.find((key, i) => allKeys.indexOf(key) !== i);
5716
+ if (conflictKey) {
5717
+ const conflicting = entries.filter(
5718
+ (e) => conflictKey in ("options" in e.scope && e.scope.options || {})
5719
+ ).map((e) => JSON.stringify(e.legacy));
5720
+ throw new Error(
5721
+ `Cannot auto-merge two '${type}' scopes that both define '${conflictKey}'. Conflicting legacy scopes: [${conflicting.join(", ")}]. Resolve manually in roles.ts and re-run.`
5722
+ );
5723
+ }
5724
+ const mergedOptions = Object.assign({}, ...optionsList);
5725
+ const merged = Object.keys(mergedOptions).length > 0 ? { type, options: mergedOptions } : { type };
5726
+ const parsed = Scope2.safeParse(merged);
5727
+ if (!parsed.success) {
5728
+ throw new Error(
5729
+ `Merged '${type}' scope failed schema validation: ${parsed.error.message}. Legacy scopes: [${entries.map((e) => JSON.stringify(e.legacy)).join(", ")}].`
5730
+ );
5731
+ }
5732
+ return parsed.data;
5733
+ }
5734
+ function migrateLegacyScopesArrayToV2Scopes(legacyScopes) {
5735
+ const groups = groupByType(legacyScopes.map(decodeLegacyScope));
5736
+ return Object.entries(groups).flatMap(([type, entries]) => {
5737
+ const deduped = deduplicateEntries(entries);
5738
+ if (deduped.length <= 1) return deduped.map((e) => e.scope);
5739
+ if (!isMergeableUserScopeType(type)) {
5740
+ console.warn(
5741
+ `Multiple non-mergeable '${type}' scopes detected after dedup \u2014 kept all as-is. Legacy scopes: [${deduped.map((e) => JSON.stringify(e.legacy)).join(", ")}]. Review whether the duplication is intentional.`
5742
+ );
5743
+ return deduped.map((e) => e.scope);
5744
+ }
5745
+ return [mergeEntries(type, deduped)];
5746
+ });
5747
+ }
2628
5748
 
2629
5749
  // src/migrations/v2.0/migrate-scopes.ts
2630
5750
  var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
@@ -2662,57 +5782,65 @@ function resolveLegacyScopeFromElement(element) {
2662
5782
  }
2663
5783
  function migrateScopesArrays(rolesFilePath, project) {
2664
5784
  const sourceFile = project.getSourceFile(rolesFilePath);
2665
- if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
5785
+ if (!sourceFile) {
5786
+ return { migratedCount: 0, removedCount: 0, mergedCount: 0 };
5787
+ }
2666
5788
  let migratedCount = 0;
2667
5789
  let removedCount = 0;
5790
+ let mergedCount = 0;
2668
5791
  const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
5792
+ const relPath = import_path11.default.relative(process.cwd(), rolesFilePath);
2669
5793
  for (const scopesProp of scopesProperties) {
2670
5794
  const initializer = scopesProp.getInitializer();
2671
5795
  if (!initializer || !import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2672
- const elements = initializer.getElements();
2673
- for (let index = elements.length - 1; index >= 0; index--) {
2674
- const element = elements[index];
2675
- if (!import_ts_morph11.Node.isExpression(element)) continue;
5796
+ const rawTexts = [];
5797
+ const legacyStrings = [];
5798
+ let anyChange = false;
5799
+ for (const element of initializer.getElements()) {
2676
5800
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2677
5801
  if (scopeKey && !(scopeKey in SCOPES)) {
2678
5802
  console.warn(
2679
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
5803
+ ` [${relPath}] Removing unknown scope reference: SCOPES.${scopeKey}`
2680
5804
  );
2681
- initializer.removeElement(index);
2682
5805
  removedCount++;
5806
+ anyChange = true;
2683
5807
  continue;
2684
5808
  }
2685
5809
  const legacyScope = resolveLegacyScopeFromElement(element);
2686
5810
  if (!legacyScope) {
2687
5811
  console.warn(
2688
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
5812
+ ` [${relPath}] Preserving non-literal scope expression verbatim: ${element.getText()}`
2689
5813
  );
5814
+ rawTexts.push(element.getText());
2690
5815
  continue;
2691
5816
  }
2692
- try {
2693
- const migratedScope = legacyScopeToV2Scope(legacyScope);
2694
- const scope = decodeScope(migratedScope);
2695
- if (!scope) {
2696
- console.warn(
2697
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2698
- );
2699
- continue;
2700
- }
2701
- element.replaceWithText(JSON.stringify(scope));
2702
- migratedCount++;
2703
- } catch (error) {
2704
- console.warn(
2705
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2706
- );
2707
- }
5817
+ legacyStrings.push(legacyScope);
5818
+ anyChange = true;
5819
+ }
5820
+ if (!anyChange) continue;
5821
+ let mergedScopes;
5822
+ try {
5823
+ mergedScopes = migrateLegacyScopesArrayToV2Scopes(legacyStrings);
5824
+ } catch (error4) {
5825
+ throw new Error(
5826
+ `[${relPath}] Failed to migrate scopes for role: ${error4 instanceof Error ? error4.message : String(error4)}`,
5827
+ { cause: error4 }
5828
+ );
2708
5829
  }
5830
+ migratedCount += legacyStrings.length;
5831
+ mergedCount += legacyStrings.length - mergedScopes.length;
5832
+ const outputElements = [
5833
+ ...rawTexts,
5834
+ ...mergedScopes.map((s) => JSON.stringify(s))
5835
+ ];
5836
+ scopesProp.setInitializer(`[${outputElements.join(", ")}]`);
2709
5837
  }
2710
5838
  if (removedCount > 0) {
2711
5839
  console.log(
2712
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
5840
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${relPath}'.`
2713
5841
  );
2714
5842
  }
2715
- return { migratedCount, removedCount };
5843
+ return { migratedCount, removedCount, mergedCount };
2716
5844
  }
2717
5845
  function ensureScopesHelpersImport(rolesFilePath, project) {
2718
5846
  const sourceFile = project.getSourceFile(rolesFilePath);
@@ -2847,7 +5975,7 @@ async function main11() {
2847
5975
  return;
2848
5976
  }
2849
5977
  const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2850
- const { migratedCount, removedCount } = migrateScopesArrays(
5978
+ const { migratedCount, removedCount, mergedCount } = migrateScopesArrays(
2851
5979
  rolesFilePath,
2852
5980
  project
2853
5981
  );
@@ -2866,7 +5994,7 @@ async function main11() {
2866
5994
  }
2867
5995
  await sourceFile.save();
2868
5996
  console.log(
2869
- `Done. Migrated ${migratedCount} legacy scope(s), removed ${removedCount} unknown SCOPES reference(s), wrapped ${wrappedScopesCount} scope array(s) with defineScopes()${wrappedRoles ? ", wrapped roles with defineRoles()" : ""}${removedRoleType ? ", and removed Role type definition" : ""}${importChanged ? ". Updated toolkit/scopes imports." : "."}`
5997
+ `Done. Migrated ${migratedCount} legacy scope(s), merged ${mergedCount} AND-paired scope(s) into single v2 objects (privilege-escalation fix, see issue #12489), removed ${removedCount} unknown SCOPES reference(s), wrapped ${wrappedScopesCount} scope array(s) with defineScopes()${wrappedRoles ? ", wrapped roles with defineRoles()" : ""}${removedRoleType ? ", and removed Role type definition" : ""}${importChanged ? ". Updated toolkit/scopes imports." : "."}`
2870
5998
  );
2871
5999
  }
2872
6000
 
@@ -3614,9 +6742,9 @@ async function main17() {
3614
6742
  let parsed;
3615
6743
  try {
3616
6744
  parsed = JSON.parse(raw);
3617
- } catch (error) {
6745
+ } catch (error4) {
3618
6746
  console.warn(
3619
- ` [${PACKAGE_JSON_RELATIVE}] Failed to parse JSON \u2014 skipping update. ${error.message}`
6747
+ ` [${PACKAGE_JSON_RELATIVE}] Failed to parse JSON \u2014 skipping update. ${error4.message}`
3620
6748
  );
3621
6749
  return;
3622
6750
  }
@@ -3672,6 +6800,10 @@ var ACTION_PROPERTY_NAME2 = "action";
3672
6800
  var CONDITIONALS_PROPERTY_NAME = "conditionals";
3673
6801
  var TYPE_PROPERTY_NAME7 = "type";
3674
6802
  var SLUG_PROPERTY_NAME = "slug";
6803
+ var READ_ACTION_TYPE = "READ";
6804
+ var ACTION_TYPE_IMPORT_NAME = "ActionType";
6805
+ var TOOLKIT_EVENTS_MODULE2 = "@opencrvs/toolkit/events";
6806
+ var READ_ACTION_FALLBACK_INITIALIZER = `{ type: ${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE} }`;
3675
6807
  var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
3676
6808
  "READ",
3677
6809
  "DELETE",
@@ -3719,91 +6851,137 @@ function isUnsupportedActionType(action) {
3719
6851
  }
3720
6852
  return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
3721
6853
  }
3722
- function migrateWorkqueueActions(workqueue, relPath) {
3723
- const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3724
- if (!actionsProperty || !import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3725
- return 0;
3726
- }
3727
- const actionsInitializer = actionsProperty.getInitializer();
3728
- if (!actionsInitializer || !import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3729
- return 0;
6854
+ function ensureValidAction(workqueue, relPath) {
6855
+ const workqueueLabel = getWorkqueueLabel(workqueue);
6856
+ const actionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
6857
+ if (actionProperty && import_ts_morph17.Node.isPropertyAssignment(actionProperty)) {
6858
+ const initializer = actionProperty.getInitializer();
6859
+ if (initializer && import_ts_morph17.Node.isObjectLiteralExpression(initializer)) {
6860
+ if (!isUnsupportedActionType(initializer)) {
6861
+ return { changed: false, usedReadFallback: false };
6862
+ }
6863
+ actionProperty.set({
6864
+ name: ACTION_PROPERTY_NAME2,
6865
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
6866
+ });
6867
+ console.log(
6868
+ ` [${relPath}] Replaced unsupported 'action' type with '${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE}' on workqueue '${workqueueLabel}'`
6869
+ );
6870
+ return { changed: true, usedReadFallback: true };
6871
+ }
3730
6872
  }
6873
+ workqueue.addPropertyAssignment({
6874
+ name: ACTION_PROPERTY_NAME2,
6875
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
6876
+ });
6877
+ console.log(
6878
+ ` [${relPath}] Added default 'action: ${READ_ACTION_FALLBACK_INITIALIZER}' to workqueue '${workqueueLabel}'`
6879
+ );
6880
+ return { changed: true, usedReadFallback: true };
6881
+ }
6882
+ function migrateWorkqueueActions(workqueue, relPath) {
3731
6883
  const workqueueLabel = getWorkqueueLabel(workqueue);
3732
- const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3733
- if (existingActionProperty) {
3734
- if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3735
- const existingActionInitializer = existingActionProperty.getInitializer();
3736
- if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3737
- const conditionalsProperty2 = existingActionInitializer.getProperty(
3738
- CONDITIONALS_PROPERTY_NAME
6884
+ const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
6885
+ let actionsArrayMigrated = false;
6886
+ if (actionsProperty && import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
6887
+ const actionsInitializer = actionsProperty.getInitializer();
6888
+ if (actionsInitializer && import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
6889
+ const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
6890
+ if (existingActionProperty) {
6891
+ if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
6892
+ const existingActionInitializer = existingActionProperty.getInitializer();
6893
+ if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
6894
+ const conditionalsProperty = existingActionInitializer.getProperty(
6895
+ CONDITIONALS_PROPERTY_NAME
6896
+ );
6897
+ if (conditionalsProperty) {
6898
+ conditionalsProperty.remove();
6899
+ console.log(
6900
+ ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
6901
+ );
6902
+ }
6903
+ }
6904
+ }
6905
+ actionsProperty.remove();
6906
+ console.log(
6907
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
6908
+ );
6909
+ actionsArrayMigrated = true;
6910
+ } else {
6911
+ const actionCandidates = actionsInitializer.getElements().filter(
6912
+ (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3739
6913
  );
3740
- if (conditionalsProperty2) {
3741
- conditionalsProperty2.remove();
6914
+ if (actionCandidates.length === 0) {
6915
+ actionsProperty.remove();
3742
6916
  console.log(
3743
- ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
6917
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3744
6918
  );
3745
- }
3746
- if (isUnsupportedActionType(existingActionInitializer)) {
3747
- existingActionProperty.remove();
3748
- console.log(
3749
- ` [${relPath}] Removed unsupported 'action' type on workqueue '${workqueueLabel}'`
6919
+ actionsArrayMigrated = true;
6920
+ } else {
6921
+ if (actionCandidates.length > 1) {
6922
+ const droppedCount = actionCandidates.length - 1;
6923
+ console.warn(
6924
+ ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
6925
+ );
6926
+ }
6927
+ const conditionalsProperty = actionCandidates[0].getProperty(
6928
+ CONDITIONALS_PROPERTY_NAME
3750
6929
  );
6930
+ if (conditionalsProperty) {
6931
+ conditionalsProperty.remove();
6932
+ console.log(
6933
+ ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
6934
+ );
6935
+ }
6936
+ if (isUnsupportedActionType(actionCandidates[0])) {
6937
+ actionsProperty.remove();
6938
+ console.log(
6939
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
6940
+ );
6941
+ actionsArrayMigrated = true;
6942
+ } else {
6943
+ const firstActionText = actionCandidates[0].getText();
6944
+ workqueue.addPropertyAssignment({
6945
+ name: ACTION_PROPERTY_NAME2,
6946
+ initializer: firstActionText
6947
+ });
6948
+ actionsProperty.remove();
6949
+ console.log(
6950
+ ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
6951
+ );
6952
+ actionsArrayMigrated = true;
6953
+ }
3751
6954
  }
3752
6955
  }
3753
6956
  }
3754
- actionsProperty.remove();
3755
- console.log(
3756
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3757
- );
3758
- return 1;
3759
6957
  }
3760
- const actionCandidates = actionsInitializer.getElements().filter(
3761
- (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3762
- );
3763
- if (actionCandidates.length === 0) {
3764
- actionsProperty.remove();
3765
- console.log(
3766
- ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3767
- );
3768
- return 1;
3769
- }
3770
- if (actionCandidates.length > 1) {
3771
- const droppedCount = actionCandidates.length - 1;
3772
- console.warn(
3773
- ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3774
- );
3775
- }
3776
- const conditionalsProperty = actionCandidates[0].getProperty(
3777
- CONDITIONALS_PROPERTY_NAME
6958
+ const fallback = ensureValidAction(workqueue, relPath);
6959
+ return {
6960
+ changed: actionsArrayMigrated || fallback.changed,
6961
+ usedReadFallback: fallback.usedReadFallback
6962
+ };
6963
+ }
6964
+ function ensureActionTypeImport(sourceFile) {
6965
+ const existingImport = sourceFile.getImportDeclaration(
6966
+ (decl) => decl.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE2
3778
6967
  );
3779
- if (conditionalsProperty) {
3780
- conditionalsProperty.remove();
3781
- console.log(
3782
- ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3783
- );
3784
- }
3785
- if (isUnsupportedActionType(actionCandidates[0])) {
3786
- actionsProperty.remove();
3787
- console.log(
3788
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3789
- );
3790
- return 1;
6968
+ if (existingImport) {
6969
+ const alreadyImported = existingImport.getNamedImports().some((ni) => ni.getName() === ACTION_TYPE_IMPORT_NAME);
6970
+ if (!alreadyImported) {
6971
+ existingImport.addNamedImport(ACTION_TYPE_IMPORT_NAME);
6972
+ }
6973
+ return;
3791
6974
  }
3792
- const firstActionText = actionCandidates[0].getText();
3793
- workqueue.addPropertyAssignment({
3794
- name: ACTION_PROPERTY_NAME2,
3795
- initializer: firstActionText
6975
+ sourceFile.addImportDeclaration({
6976
+ moduleSpecifier: TOOLKIT_EVENTS_MODULE2,
6977
+ namedImports: [ACTION_TYPE_IMPORT_NAME]
3796
6978
  });
3797
- actionsProperty.remove();
3798
- console.log(
3799
- ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3800
- );
3801
- return 1;
3802
6979
  }
3803
6980
  function processFile13(filePath, project) {
3804
6981
  const sourceFile = project.getSourceFile(filePath);
3805
6982
  if (!sourceFile) return 0;
3806
6983
  let migratedWorkqueues = 0;
6984
+ let needsActionTypeImport = false;
3807
6985
  const relPath = import_path18.default.relative(process.cwd(), filePath);
3808
6986
  const callExpressions = sourceFile.getDescendantsOfKind(
3809
6987
  import_ts_morph17.SyntaxKind.CallExpression
@@ -3819,9 +6997,14 @@ function processFile13(filePath, project) {
3819
6997
  if (!import_ts_morph17.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3820
6998
  for (const element of workqueuesArg.getElements()) {
3821
6999
  if (!import_ts_morph17.Node.isObjectLiteralExpression(element)) continue;
3822
- migratedWorkqueues += migrateWorkqueueActions(element, relPath);
7000
+ const result = migrateWorkqueueActions(element, relPath);
7001
+ if (result.changed) migratedWorkqueues++;
7002
+ if (result.usedReadFallback) needsActionTypeImport = true;
3823
7003
  }
3824
7004
  }
7005
+ if (needsActionTypeImport) {
7006
+ ensureActionTypeImport(sourceFile);
7007
+ }
3825
7008
  return migratedWorkqueues;
3826
7009
  }
3827
7010
  async function main18() {
@@ -4156,7 +7339,7 @@ Saved ${handlerRelPath}.`);
4156
7339
  // src/migrations/v2.0/checkout-upstream-files.ts
4157
7340
  var import_child_process = require("child_process");
4158
7341
  var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
4159
- var UPSTREAM_BRANCH = "develop";
7342
+ var UPSTREAM_BRANCH = "release/2.0.0";
4160
7343
  var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
4161
7344
  var FILES_TO_CHECKOUT = [
4162
7345
  "src/analytics/analytics.ts",
@@ -4588,7 +7771,7 @@ var FUNCTION_NAME = "precalculateAdditionalAnalytics";
4588
7771
  var IMPORT_NAMES_TO_REMOVE = /* @__PURE__ */ new Set(["Event", "precalculateBirthEvent"]);
4589
7772
  var RETURN_EXPRESSION_TEXT = "declaration";
4590
7773
  function removeTargetedNamedImports(sourceFile) {
4591
- const log = [];
7774
+ const log2 = [];
4592
7775
  for (const importDecl of [...sourceFile.getImportDeclarations()]) {
4593
7776
  const namedImports = importDecl.getNamedImports();
4594
7777
  if (namedImports.length === 0) continue;
@@ -4598,13 +7781,13 @@ function removeTargetedNamedImports(sourceFile) {
4598
7781
  if (matched.length === 0) continue;
4599
7782
  const removedNames = matched.map((ni) => ni.getName());
4600
7783
  for (const ni of matched) ni.remove();
4601
- log.push(
7784
+ log2.push(
4602
7785
  `removed import(s) ${removedNames.join(", ")} from '${importDecl.getModuleSpecifierValue()}'`
4603
7786
  );
4604
7787
  const stillUsed = importDecl.getNamedImports().length > 0 || importDecl.getDefaultImport() || importDecl.getNamespaceImport();
4605
7788
  if (!stillUsed) importDecl.remove();
4606
7789
  }
4607
- return log;
7790
+ return log2;
4608
7791
  }
4609
7792
  function findPrecalculateFunction(sourceFile) {
4610
7793
  for (const fn of sourceFile.getFunctions()) {
@@ -4627,16 +7810,16 @@ function getFunctionBodyBlock(fn) {
4627
7810
  return initializer.getBody();
4628
7811
  }
4629
7812
  function simplifyPrecalculateFunction(sourceFile) {
4630
- const log = [];
7813
+ const log2 = [];
4631
7814
  const fn = findPrecalculateFunction(sourceFile);
4632
- if (!fn) return log;
7815
+ if (!fn) return log2;
4633
7816
  const body = getFunctionBodyBlock(fn);
4634
- if (!body || !import_ts_morph21.Node.isBlock(body)) return log;
7817
+ if (!body || !import_ts_morph21.Node.isBlock(body)) return log2;
4635
7818
  for (const statement of [...body.getStatements()]) {
4636
7819
  const references = statement.getDescendantsOfKind(import_ts_morph21.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
4637
7820
  if (references) {
4638
7821
  statement.remove();
4639
- log.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
7822
+ log2.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
4640
7823
  }
4641
7824
  }
4642
7825
  const remaining = body.getStatements();
@@ -4644,11 +7827,11 @@ function simplifyPrecalculateFunction(sourceFile) {
4644
7827
  const alreadyCorrect = last && import_ts_morph21.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
4645
7828
  if (!alreadyCorrect) {
4646
7829
  body.addStatements(`return ${RETURN_EXPRESSION_TEXT}`);
4647
- log.push(
7830
+ log2.push(
4648
7831
  `ensured '${FUNCTION_NAME}' ends with 'return ${RETURN_EXPRESSION_TEXT}'`
4649
7832
  );
4650
7833
  }
4651
- return log;
7834
+ return log2;
4652
7835
  }
4653
7836
  async function main24() {
4654
7837
  const cwd = process.cwd();
@@ -4679,8 +7862,8 @@ async function main24() {
4679
7862
  console.log(`[${ANALYTICS_FILE_REL}] already clean \u2014 nothing to do.`);
4680
7863
  return;
4681
7864
  }
4682
- for (const log of allLogs) {
4683
- console.log(` [${ANALYTICS_FILE_REL}] ${log}`);
7865
+ for (const log2 of allLogs) {
7866
+ console.log(` [${ANALYTICS_FILE_REL}] ${log2}`);
4684
7867
  }
4685
7868
  await sourceFile.save();
4686
7869
  console.log(`
@@ -4695,9 +7878,9 @@ var import_path24 = require("path");
4695
7878
  var TEMP_REMOTE2 = "opencrvs-upgrade-v19-v20-codemod-merge-infra";
4696
7879
  var INFRASTRUCTURE_DIR = "infrastructure";
4697
7880
  var BASE_BRANCH = "release-v1.9";
4698
- function gitShowBytes(ref, path23) {
7881
+ function gitShowBytes(ref, path28) {
4699
7882
  try {
4700
- const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path23}`], {
7883
+ const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path28}`], {
4701
7884
  cwd: process.cwd(),
4702
7885
  stdio: ["ignore", "pipe", "pipe"]
4703
7886
  });
@@ -4706,9 +7889,13 @@ function gitShowBytes(ref, path23) {
4706
7889
  return null;
4707
7890
  }
4708
7891
  }
4709
- async function main25() {
7892
+ async function main25({
7893
+ subdirs = []
7894
+ } = {}) {
7895
+ const pathspecs = subdirs.length > 0 ? subdirs.map((s) => `${INFRASTRUCTURE_DIR}/${s}/`) : [`${INFRASTRUCTURE_DIR}/`];
7896
+ const scopeLabel = pathspecs.map((p) => `'${p}'`).join(", ");
4710
7897
  console.log(
4711
- `Merging '${INFRASTRUCTURE_DIR}/' from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
7898
+ `Merging ${scopeLabel} from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4712
7899
  `
4713
7900
  );
4714
7901
  assertIsGitRepo();
@@ -4723,20 +7910,12 @@ async function main25() {
4723
7910
  const ref = `${TEMP_REMOTE2}/${UPSTREAM_BRANCH}`;
4724
7911
  const baseRef = `${TEMP_REMOTE2}/${BASE_BRANCH}`;
4725
7912
  const upstreamFiles = runGit(
4726
- [
4727
- "ls-tree",
4728
- "-r",
4729
- "--name-only",
4730
- "-z",
4731
- ref,
4732
- "--",
4733
- `${INFRASTRUCTURE_DIR}/`
4734
- ],
7913
+ ["ls-tree", "-r", "--name-only", "-z", ref, "--", ...pathspecs],
4735
7914
  { silent: true }
4736
7915
  ).split("\0").filter(Boolean);
4737
7916
  if (upstreamFiles.length === 0) {
4738
7917
  console.log(
4739
- ` No files found under '${INFRASTRUCTURE_DIR}/' on ${ref}. Nothing to merge.`
7918
+ ` No files found under ${scopeLabel} on ${ref}. Nothing to merge.`
4740
7919
  );
4741
7920
  return;
4742
7921
  }
@@ -4811,7 +7990,9 @@ async function main25() {
4811
7990
  var import_fs6 = require("fs");
4812
7991
  var import_path25 = require("path");
4813
7992
  var INFRASTRUCTURE_DIR2 = "infrastructure";
4814
- async function main26() {
7993
+ async function main26({
7994
+ keep = []
7995
+ } = {}) {
4815
7996
  const fullPath = (0, import_path25.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4816
7997
  if (!(0, import_fs6.existsSync)(fullPath)) {
4817
7998
  console.log(
@@ -4819,24 +8000,152 @@ async function main26() {
4819
8000
  );
4820
8001
  return;
4821
8002
  }
4822
- console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4823
- `);
4824
8003
  assertIsGitRepo();
4825
- runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4826
- silent: true
8004
+ if (keep.length === 0) {
8005
+ console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
8006
+ `);
8007
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
8008
+ silent: true
8009
+ });
8010
+ console.log(
8011
+ ` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`
8012
+ );
8013
+ if ((0, import_fs6.existsSync)(fullPath)) {
8014
+ (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
8015
+ console.log(
8016
+ ` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`
8017
+ );
8018
+ }
8019
+ console.log(
8020
+ `
8021
+ Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
8022
+ );
8023
+ return;
8024
+ }
8025
+ const keepSet = new Set(keep);
8026
+ console.log(
8027
+ `Deleting contents of '${INFRASTRUCTURE_DIR2}/' except: ${[...keepSet].map((name) => `'${name}'`).join(", ")}
8028
+ `
8029
+ );
8030
+ const topLevelEntries = (0, import_fs6.readdirSync)(fullPath, { withFileTypes: true });
8031
+ let deleted = 0;
8032
+ for (const entry of topLevelEntries) {
8033
+ if (keepSet.has(entry.name)) {
8034
+ console.log(` Keeping '${INFRASTRUCTURE_DIR2}/${entry.name}'.`);
8035
+ continue;
8036
+ }
8037
+ const relPath = `${INFRASTRUCTURE_DIR2}/${entry.name}${entry.isDirectory() ? "/" : ""}`;
8038
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", relPath], { silent: true });
8039
+ const fullEntryPath = (0, import_path25.join)(fullPath, entry.name);
8040
+ if ((0, import_fs6.existsSync)(fullEntryPath)) {
8041
+ (0, import_fs6.rmSync)(fullEntryPath, { recursive: true, force: true });
8042
+ }
8043
+ console.log(` Deleted '${relPath}'.`);
8044
+ deleted++;
8045
+ }
8046
+ const presentNames = new Set(topLevelEntries.map((e) => e.name));
8047
+ const missingKeeps = [...keepSet].filter((name) => !presentNames.has(name));
8048
+ if (missingKeeps.length > 0) {
8049
+ console.warn(
8050
+ ` [warn] Requested to keep ${missingKeeps.map((n) => `'${n}'`).join(", ")} but they don't exist under '${INFRASTRUCTURE_DIR2}/'.`
8051
+ );
8052
+ }
8053
+ console.log(
8054
+ `
8055
+ Done. Deleted ${deleted} top-level entr${deleted === 1 ? "y" : "ies"}. Review the staged deletions with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
8056
+ );
8057
+ }
8058
+
8059
+ // src/migrations/v2.0/fix-accept-requested-registration-function-type.ts
8060
+ var import_ts_morph22 = require("ts-morph");
8061
+ var import_path26 = __toESM(require("path"));
8062
+ var TARGET_FUNCTION_NAME = "acceptRequestedRegistration";
8063
+ var ACTION_PARAMETER_NAME = "action";
8064
+ var OLD_TYPE = "ActionInput";
8065
+ var NEW_TYPE = "Extract<ActionInput, { type?: 'REGISTER' }>";
8066
+ function isAcceptRequestedRegistrationParameter(parameter) {
8067
+ const functionDeclaration = parameter.getFirstAncestorByKind(
8068
+ import_ts_morph22.SyntaxKind.FunctionDeclaration
8069
+ );
8070
+ if (functionDeclaration?.getName() === TARGET_FUNCTION_NAME) {
8071
+ return true;
8072
+ }
8073
+ const arrowFunction = parameter.getFirstAncestorByKind(
8074
+ import_ts_morph22.SyntaxKind.ArrowFunction
8075
+ );
8076
+ const variableDeclaration = arrowFunction?.getFirstAncestorByKind(
8077
+ import_ts_morph22.SyntaxKind.VariableDeclaration
8078
+ );
8079
+ return variableDeclaration?.getName() === TARGET_FUNCTION_NAME;
8080
+ }
8081
+ function processFile14(filePath, project) {
8082
+ const sourceFile = project.getSourceFile(filePath);
8083
+ if (!sourceFile) return 0;
8084
+ let updatedCount = 0;
8085
+ for (const parameter of sourceFile.getDescendantsOfKind(
8086
+ import_ts_morph22.SyntaxKind.Parameter
8087
+ )) {
8088
+ if (parameter.getName() !== ACTION_PARAMETER_NAME) {
8089
+ continue;
8090
+ }
8091
+ if (!isAcceptRequestedRegistrationParameter(parameter)) {
8092
+ continue;
8093
+ }
8094
+ const typeNode = parameter.getTypeNode();
8095
+ if (!typeNode || typeNode.getText() !== OLD_TYPE) {
8096
+ continue;
8097
+ }
8098
+ parameter.setType(NEW_TYPE);
8099
+ updatedCount++;
8100
+ console.log(
8101
+ ` [${import_path26.default.relative(process.cwd(), filePath)}] Updated '${ACTION_PARAMETER_NAME}' in ${TARGET_FUNCTION_NAME} to ${NEW_TYPE}`
8102
+ );
8103
+ }
8104
+ return updatedCount;
8105
+ }
8106
+ async function main27() {
8107
+ const srcDir = import_path26.default.join(process.cwd(), "src");
8108
+ console.log(`Scanning for ${TARGET_FUNCTION_NAME} in: ${srcDir}
8109
+ `);
8110
+ const project = new import_ts_morph22.Project({
8111
+ tsConfigFilePath: import_path26.default.resolve(srcDir, "../tsconfig.json"),
8112
+ skipAddingFilesFromTsConfig: false
4827
8113
  });
4828
- console.log(` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4829
- if ((0, import_fs6.existsSync)(fullPath)) {
4830
- (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4831
- console.log(` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`);
8114
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
8115
+ const filePath = sf.getFilePath();
8116
+ return filePath.includes("/src/") && !filePath.includes("/node_modules/");
8117
+ });
8118
+ let totalUpdated = 0;
8119
+ const modifiedFiles = [];
8120
+ for (const sourceFile of sourceFiles) {
8121
+ const filePath = sourceFile.getFilePath();
8122
+ const updated = processFile14(filePath, project);
8123
+ if (updated > 0) {
8124
+ totalUpdated += updated;
8125
+ modifiedFiles.push(filePath);
8126
+ }
8127
+ }
8128
+ if (modifiedFiles.length === 0) {
8129
+ console.log(
8130
+ `No '${ACTION_PARAMETER_NAME}: ${OLD_TYPE}' parameter in ${TARGET_FUNCTION_NAME} found. Nothing to do.`
8131
+ );
8132
+ return;
8133
+ }
8134
+ console.log(`
8135
+ Saving ${modifiedFiles.length} modified file(s)...`);
8136
+ for (const filePath of modifiedFiles) {
8137
+ const sourceFile = project.getSourceFileOrThrow(filePath);
8138
+ await sourceFile.save();
8139
+ console.log(` Saved: ${import_path26.default.relative(process.cwd(), filePath)}`);
4832
8140
  }
4833
8141
  console.log(
4834
8142
  `
4835
- Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
8143
+ Done. Updated ${totalUpdated} parameter type annotation(s) in ${TARGET_FUNCTION_NAME}.`
4836
8144
  );
4837
8145
  }
4838
8146
 
4839
8147
  // src/migrations/v2.0/index.ts
8148
+ var NON_SWARM_INFRA_SUBDIRS = ["postgres", "metabase"];
4840
8149
  async function runUpgrade(dockerSwarm) {
4841
8150
  await main18();
4842
8151
  await main();
@@ -4861,13 +8170,57 @@ async function runUpgrade(dockerSwarm) {
4861
8170
  await main22();
4862
8171
  await main23();
4863
8172
  await main24();
8173
+ await main27();
4864
8174
  await main17();
4865
8175
  if (dockerSwarm) {
4866
8176
  await main25();
4867
8177
  } else {
4868
- await main26();
8178
+ await main26({ keep: NON_SWARM_INFRA_SUBDIRS });
8179
+ await main25({ subdirs: NON_SWARM_INFRA_SUBDIRS });
8180
+ }
8181
+ }
8182
+
8183
+ // src/environment/index.ts
8184
+ var import_fs10 = require("fs");
8185
+ var import_path29 = require("path");
8186
+ var REQUIRED_REPOSITORY_DIRECTORIES = [
8187
+ ".github/workflows",
8188
+ "environments",
8189
+ "infrastructure"
8190
+ ];
8191
+ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
8192
+ const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
8193
+ (directory) => {
8194
+ try {
8195
+ return !(0, import_fs10.statSync)((0, import_path29.resolve)(repositoryRoot, directory)).isDirectory();
8196
+ } catch {
8197
+ return true;
8198
+ }
8199
+ }
8200
+ );
8201
+ if (missingDirectories.length > 0) {
8202
+ throw new Error(
8203
+ `The current directory is not a valid OpenCRVS country configuration repository. Missing required director${missingDirectories.length === 1 ? "y" : "ies"}: ${missingDirectories.join(", ")}`
8204
+ );
4869
8205
  }
4870
8206
  }
8207
+ async function runEnvironmentInit() {
8208
+ validateRepositoryStructure();
8209
+ await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
8210
+ }
8211
+ async function runEnvironmentUpdateWorkflows() {
8212
+ validateRepositoryStructure();
8213
+ const { updateWorkflowEnvironments: updateWorkflowEnvironments2 } = await Promise.resolve().then(() => (init_update_workflows(), update_workflows_exports));
8214
+ await updateWorkflowEnvironments2();
8215
+ }
8216
+ async function runEnvironmentUsers() {
8217
+ validateRepositoryStructure();
8218
+ await Promise.resolve().then(() => (init_users(), users_exports));
8219
+ }
8220
+ async function runEnvironmentSwarmToK8s() {
8221
+ validateRepositoryStructure();
8222
+ await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
8223
+ }
4871
8224
 
4872
8225
  // src/cli.ts
4873
8226
  var args = process.argv.slice(2);
@@ -4875,7 +8228,7 @@ var USAGE = `
4875
8228
  Usage: opencrvs <command>
4876
8229
 
4877
8230
  Commands:
4878
- environment init Initialise a new environment
8231
+ environment Manage deployment environments
4879
8232
  upgrade Upgrade an existing environment
4880
8233
  check-translations Check translation files for completeness
4881
8234
 
@@ -4894,7 +8247,7 @@ Options:
4894
8247
  'infrastructure/' directory is deleted (default).
4895
8248
  -h, --help Show this message.
4896
8249
  `.trim();
4897
- function main27() {
8250
+ function main28() {
4898
8251
  const command = args[0];
4899
8252
  if (!command || command === "--help" || command === "-h") {
4900
8253
  console.log(USAGE);
@@ -4914,7 +8267,7 @@ function main27() {
4914
8267
  process.exit(1);
4915
8268
  }
4916
8269
  }
4917
- function handleEnvironment() {
8270
+ async function handleEnvironment() {
4918
8271
  const subcommand = args[1];
4919
8272
  if (!subcommand || subcommand === "--help" || subcommand === "-h") {
4920
8273
  console.log(
@@ -4922,22 +8275,45 @@ function handleEnvironment() {
4922
8275
  Usage: opencrvs environment <subcommand>
4923
8276
 
4924
8277
  Subcommands:
4925
- init Initialise a new environment
8278
+ init Initialise a new environment
8279
+ update-workflows Update workflow environment options
8280
+ users Manage environment users
8281
+ swarm-to-k8s Migrate Docker Swarm configuration to Kubernetes
4926
8282
  `.trim()
4927
8283
  );
4928
8284
  process.exit(0);
4929
8285
  }
4930
8286
  switch (subcommand) {
4931
8287
  case "init":
4932
- console.log("Initialising environment...");
4933
- console.warn("This command is not implemented yet!");
4934
- process.exit(1);
4935
- break;
8288
+ return runEnvironmentCommand("initialisation", runEnvironmentInit);
8289
+ case "update-workflows":
8290
+ return runEnvironmentCommand(
8291
+ "workflow update",
8292
+ runEnvironmentUpdateWorkflows
8293
+ );
8294
+ case "users":
8295
+ return runEnvironmentCommand("user management", runEnvironmentUsers);
8296
+ case "swarm-to-k8s":
8297
+ return runEnvironmentCommand(
8298
+ "Swarm to Kubernetes migration",
8299
+ runEnvironmentSwarmToK8s
8300
+ );
4936
8301
  default:
4937
8302
  console.error(`Unknown subcommand: environment ${subcommand}`);
4938
8303
  process.exit(1);
4939
8304
  }
4940
8305
  }
8306
+ async function runEnvironmentCommand(operation, command) {
8307
+ try {
8308
+ await command();
8309
+ } catch (error4) {
8310
+ console.error(
8311
+ `Environment ${operation} failed:`,
8312
+ error4 instanceof Error ? error4.message : error4
8313
+ );
8314
+ process.exit(1);
8315
+ }
8316
+ }
4941
8317
  async function handleUpgrade() {
4942
8318
  const upgradeArgs = args.slice(1);
4943
8319
  if (upgradeArgs.includes("--help") || upgradeArgs.includes("-h")) {
@@ -4959,8 +8335,8 @@ async function handleUpgrade() {
4959
8335
  try {
4960
8336
  await runUpgrade(dockerSwarm);
4961
8337
  console.log("Upgrade completed successfully!");
4962
- } catch (error) {
4963
- console.error("Upgrade failed:", error);
8338
+ } catch (error4) {
8339
+ console.error("Upgrade failed:", error4);
4964
8340
  process.exit(1);
4965
8341
  }
4966
8342
  }
@@ -4969,4 +8345,4 @@ function handleCheckTranslations() {
4969
8345
  console.warn("This command is not implemented yet!");
4970
8346
  process.exit(1);
4971
8347
  }
4972
- main27();
8348
+ main28();