@opencrvs/toolkit 2.0.0-rc.21b1468 → 2.0.0-rc.220b4d4

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