@opencrvs/toolkit 2.1.0-rc.12673aa → 2.1.0-rc.14fb6a5

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 (188) hide show
  1. package/build.sh +14 -4
  2. package/create-countryconfig/index.js +59 -30
  3. package/dist/application-config/index.js +26 -13
  4. package/dist/authentication/index.d.ts +8 -9
  5. package/dist/authentication/index.js +23 -8
  6. package/dist/cli.js +2268 -1385
  7. package/dist/commons/api/router.d.ts +252 -290
  8. package/dist/commons/application-config/index.d.ts +0 -2
  9. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  10. package/dist/commons/conditionals/validate.d.ts +18 -3
  11. package/dist/commons/events/ActionConfig.d.ts +5 -14
  12. package/dist/commons/events/ActionDocument.d.ts +30 -4
  13. package/dist/commons/events/AdvancedSearchConfig.d.ts +24 -12
  14. package/dist/commons/events/AuditLog.d.ts +1 -0
  15. package/dist/commons/events/Draft.d.ts +1 -21
  16. package/dist/commons/events/EventDocument.d.ts +4 -4
  17. package/dist/commons/events/FieldConfig.d.ts +20 -10
  18. package/dist/commons/events/FieldTypeMapping.d.ts +10 -10
  19. package/dist/commons/events/FieldValue.d.ts +1 -0
  20. package/dist/commons/events/FormConfig.d.ts +6 -0
  21. package/dist/commons/events/PageConfig.d.ts +4 -0
  22. package/dist/commons/events/scopes.d.ts +21 -1
  23. package/dist/commons/events/test.utils.d.ts +53 -21
  24. package/dist/commons/events/utils.d.ts +26 -2
  25. package/dist/conditionals/index.js +21 -7
  26. package/dist/environment/index.d.ts.map +1 -1
  27. package/dist/environment/index.js +2 -1
  28. package/dist/environment/setup-environment.d.ts +1 -1
  29. package/dist/environment/setup-environment.d.ts.map +1 -1
  30. package/dist/environment/setup-environment.js +586 -569
  31. package/dist/environment/swarm-to-k8s.js +3 -4
  32. package/dist/events/index.js +282 -138
  33. package/dist/migrations/v2.1/add-recovery-link-notifications.js +4 -4
  34. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -1
  35. package/dist/migrations/v2.1/add-translations.js +4 -68
  36. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -1
  37. package/dist/migrations/v2.1/enable-telemetry.js +30 -13
  38. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  39. package/dist/migrations/v2.1/index.js +927 -33
  40. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +14 -0
  41. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +1 -0
  42. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.js +348 -0
  43. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts +2 -0
  44. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts.map +1 -0
  45. package/dist/migrations/v2.1/remove-metabase-package-installs.js +161 -0
  46. package/dist/migrations/{v2.0/migrate-scopes.d.ts → v2.1/remove-sentry.d.ts} +1 -1
  47. package/dist/migrations/v2.1/remove-sentry.d.ts.map +1 -0
  48. package/dist/migrations/v2.1/remove-sentry.js +354 -0
  49. package/dist/migrations/{v2.0/rename-api-paths.d.ts → v2.1/rename-trigger-paths.d.ts} +1 -1
  50. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +1 -0
  51. package/dist/migrations/{v2.0/rename-api-paths.js → v2.1/rename-trigger-paths.js} +69 -40
  52. package/dist/migrations/v2.1/template-files.d.ts +8 -0
  53. package/dist/migrations/v2.1/template-files.d.ts.map +1 -0
  54. package/dist/migrations/v2.1/template-files.js +49 -0
  55. package/dist/migrations/v2.1/upgrade-tilt.d.ts +8 -0
  56. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +1 -0
  57. package/dist/migrations/v2.1/upgrade-tilt.js +139 -0
  58. package/dist/notification/index.js +105 -61
  59. package/dist/scopes/index.d.ts +288 -5
  60. package/dist/scopes/index.js +22 -7
  61. package/dist/telemetry/index.js +4 -0
  62. package/dist/templates/charts-values/dependencies/values.yaml +6 -0
  63. package/dist/templates/charts-values/opencrvs-services/values.yaml +6 -0
  64. package/dist/templates/charts-values/opentelemetry/values.yaml +7 -0
  65. package/dist/templates/countryconfig-template/.tiltignore +1 -0
  66. package/dist/templates/countryconfig-template/Dockerfile.assets +7 -0
  67. package/dist/templates/countryconfig-template/Tiltfile +112 -0
  68. package/dist/templates/countryconfig-template/assets/README.md +1 -0
  69. package/dist/templates/countryconfig-template/assets/clear-all-data-dev.sh +61 -0
  70. package/dist/templates/countryconfig-template/assets/deployment/deploy.sh +455 -0
  71. package/dist/templates/countryconfig-template/assets/deployment/reindex.sh +168 -0
  72. package/dist/templates/countryconfig-template/assets/deployment/validate-required-variables-in-compose-files.ts +67 -0
  73. package/dist/templates/countryconfig-template/assets/elasticsearch/reindex.sh +168 -0
  74. package/dist/templates/countryconfig-template/assets/metabase/README.md +34 -0
  75. package/dist/templates/countryconfig-template/assets/metabase/environment-configuration.sql +36 -0
  76. package/dist/templates/countryconfig-template/assets/metabase/initialize-database.sh +46 -0
  77. package/dist/templates/countryconfig-template/assets/metabase/metabase.init.db.sql +27737 -0
  78. package/dist/templates/countryconfig-template/assets/metabase/open-shell.sh +21 -0
  79. package/dist/templates/countryconfig-template/assets/metabase/package.json +13 -0
  80. package/dist/templates/countryconfig-template/assets/metabase/run-dev.sh +108 -0
  81. package/dist/templates/countryconfig-template/assets/metabase/run.sh +120 -0
  82. package/dist/templates/countryconfig-template/assets/metabase/update-database.sh +40 -0
  83. package/dist/templates/countryconfig-template/assets/postgres/setup-analytics.sh +135 -0
  84. package/dist/templates/countryconfig-template/assets/postgres/setup-reference-data.sh +108 -0
  85. package/dist/templates/countryconfig-template/tilt/clear-all-data.ps1 +50 -0
  86. package/dist/templates/countryconfig-template/tilt/clear-all-data.sh +35 -0
  87. package/dist/templates/countryconfig-template/tilt/common.tilt +145 -0
  88. package/dist/templates/countryconfig-template/tilt/examples/dependencies/values.yaml +15 -0
  89. package/dist/templates/countryconfig-template/tilt/examples/opencrvs-services/values.yaml +56 -0
  90. package/dist/templates/countryconfig-template/tilt/examples/traefik/values-minikube.yaml +21 -0
  91. package/dist/templates/countryconfig-template/tilt/examples/traefik/values.yaml +38 -0
  92. package/dist/templates/countryconfig-template/tilt/helm/dependencies/values.yaml +17 -0
  93. package/dist/templates/countryconfig-template/tilt/helm/opencrvs-services/values.yaml +16 -0
  94. package/dist/templates/countryconfig-template/tilt/lib.tilt +95 -0
  95. package/dist/templates/countryconfig-template/tilt/opencrvs.tilt +136 -0
  96. package/dist/translations/template.d.ts +11 -0
  97. package/dist/translations/template.d.ts.map +1 -0
  98. package/dist/translations/template.js +100 -0
  99. package/dist/verify/endpoints.d.ts.map +1 -1
  100. package/dist/verify/endpoints.js +179 -14
  101. package/opencrvs-toolkit-2.1.0-rc.14fb6a5.tgz +0 -0
  102. package/package.json +2 -1
  103. package/tsconfig.build.tsbuildinfo +1 -1
  104. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts +0 -3
  105. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +0 -1
  106. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +0 -429
  107. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts +0 -3
  108. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts.map +0 -1
  109. package/dist/migrations/v2.0/add-resend-invite-notification.js +0 -373
  110. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +0 -22
  111. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +0 -1
  112. package/dist/migrations/v2.0/checkout-upstream-files.js +0 -146
  113. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts +0 -2
  114. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +0 -1
  115. package/dist/migrations/v2.0/convert-config-files-to-ts.js +0 -838
  116. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts +0 -3
  117. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts.map +0 -1
  118. package/dist/migrations/v2.0/convert-paragraph-to-heading.js +0 -158
  119. package/dist/migrations/v2.0/create-events-index.d.ts +0 -3
  120. package/dist/migrations/v2.0/create-events-index.d.ts.map +0 -1
  121. package/dist/migrations/v2.0/create-events-index.js +0 -325
  122. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +0 -11
  123. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +0 -1
  124. package/dist/migrations/v2.0/delete-infrastructure-directory.js +0 -123
  125. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +0 -3
  126. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +0 -1
  127. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +0 -110
  128. package/dist/migrations/v2.0/index.d.ts +0 -13
  129. package/dist/migrations/v2.0/index.d.ts.map +0 -1
  130. package/dist/migrations/v2.0/index.js +0 -103
  131. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts +0 -3
  132. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +0 -1
  133. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +0 -432
  134. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +0 -13
  135. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +0 -1
  136. package/dist/migrations/v2.0/merge-infrastructure-directory.js +0 -222
  137. package/dist/migrations/v2.0/migrate-application-config-url.d.ts +0 -3
  138. package/dist/migrations/v2.0/migrate-application-config-url.d.ts.map +0 -1
  139. package/dist/migrations/v2.0/migrate-application-config-url.js +0 -343
  140. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +0 -1
  141. package/dist/migrations/v2.0/migrate-scopes.js +0 -305
  142. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts +0 -3
  143. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts.map +0 -1
  144. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.js +0 -267
  145. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts +0 -3
  146. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +0 -1
  147. package/dist/migrations/v2.0/migrate-workqueue-configs.js +0 -317
  148. package/dist/migrations/v2.0/remove-delete-actions.d.ts +0 -3
  149. package/dist/migrations/v2.0/remove-delete-actions.d.ts.map +0 -1
  150. package/dist/migrations/v2.0/remove-delete-actions.js +0 -156
  151. package/dist/migrations/v2.0/remove-demo-scope.d.ts +0 -3
  152. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +0 -1
  153. package/dist/migrations/v2.0/remove-demo-scope.js +0 -74
  154. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts +0 -3
  155. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts.map +0 -1
  156. package/dist/migrations/v2.0/remove-deprecated-imports.js +0 -96
  157. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts +0 -3
  158. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts.map +0 -1
  159. package/dist/migrations/v2.0/remove-fhir-url-helpers.js +0 -163
  160. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts +0 -3
  161. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts.map +0 -1
  162. package/dist/migrations/v2.0/remove-hearth-migrations.js +0 -87
  163. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts +0 -3
  164. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts.map +0 -1
  165. package/dist/migrations/v2.0/remove-old-statistics-service.js +0 -356
  166. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts +0 -3
  167. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts.map +0 -1
  168. package/dist/migrations/v2.0/remove-pending-certification-flag.js +0 -109
  169. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts +0 -3
  170. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts.map +0 -1
  171. package/dist/migrations/v2.0/remove-review-from-register-action.js +0 -163
  172. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts +0 -3
  173. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts.map +0 -1
  174. package/dist/migrations/v2.0/remove-unused-environment-variables.js +0 -186
  175. package/dist/migrations/v2.0/rename-api-paths.d.ts.map +0 -1
  176. package/dist/migrations/v2.0/rename-location-parent-id.d.ts +0 -3
  177. package/dist/migrations/v2.0/rename-location-parent-id.d.ts.map +0 -1
  178. package/dist/migrations/v2.0/rename-location-parent-id.js +0 -180
  179. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts +0 -3
  180. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +0 -1
  181. package/dist/migrations/v2.0/simplify-analytics-precalculations.js +0 -195
  182. package/dist/migrations/v2.0/update-package-json.d.ts +0 -3
  183. package/dist/migrations/v2.0/update-package-json.d.ts.map +0 -1
  184. package/dist/migrations/v2.0/update-package-json.js +0 -105
  185. package/dist/translations/check.d.ts +0 -21
  186. package/dist/translations/check.d.ts.map +0 -1
  187. package/dist/translations/check.js +0 -132
  188. package/opencrvs-toolkit-2.1.0-rc.12673aa.tgz +0 -0
@@ -1,838 +0,0 @@
1
- "use strict";
2
- /*
3
- * This Source Code Form is subject to the terms of the Mozilla Public
4
- * License, v. 2.0. If a copy of the MPL was not distributed with this
5
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
- *
7
- * OpenCRVS is also distributed under the terms of the Civil Registration
8
- * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
- *
10
- * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
- */
12
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
- if (k2 === undefined) k2 = k;
14
- var desc = Object.getOwnPropertyDescriptor(m, k);
15
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
- desc = { enumerable: true, get: function() { return m[k]; } };
17
- }
18
- Object.defineProperty(o, k2, desc);
19
- }) : (function(o, m, k, k2) {
20
- if (k2 === undefined) k2 = k;
21
- o[k2] = m[k];
22
- }));
23
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
- Object.defineProperty(o, "default", { enumerable: true, value: v });
25
- }) : function(o, v) {
26
- o["default"] = v;
27
- });
28
- var __importStar = (this && this.__importStar) || (function () {
29
- var ownKeys = function(o) {
30
- ownKeys = Object.getOwnPropertyNames || function (o) {
31
- var ar = [];
32
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
33
- return ar;
34
- };
35
- return ownKeys(o);
36
- };
37
- return function (mod) {
38
- if (mod && mod.__esModule) return mod;
39
- var result = {};
40
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41
- __setModuleDefault(result, mod);
42
- return result;
43
- };
44
- })();
45
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
46
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
47
- return new (P || (P = Promise))(function (resolve, reject) {
48
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
49
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
50
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
51
- step((generator = generator.apply(thisArg, _arguments || [])).next());
52
- });
53
- };
54
- var __importDefault = (this && this.__importDefault) || function (mod) {
55
- return (mod && mod.__esModule) ? mod : { "default": mod };
56
- };
57
- Object.defineProperty(exports, "__esModule", { value: true });
58
- exports.main = main;
59
- /**
60
- * Codemod: Convert JS client/login config files to TypeScript and update Hapi route handlers.
61
- *
62
- * Usage:
63
- * ts-node -r tsconfig-paths/register src/migrations/v2.0/convert-config-files-to-ts.ts
64
- *
65
- * Phase 1 — JS → TS conversion (for each of the four config files in src/):
66
- * - client-config.js → client-config.ts (exports clientConfig)
67
- * - client-config.prod.js → client-config.prod.ts (exports clientConfigProd)
68
- * - login-config.js → login-config.ts (exports loginConfig)
69
- * - login-config.prod.js → login-config.prod.ts (exports loginConfigProd)
70
- *
71
- * For each file:
72
- * - Extracts the `window.config = { ... }` object (handles both direct and IIFE patterns)
73
- * - Removes keys not present in the ClientConfig / LoginConfig schema
74
- * - Converts LANGUAGES from a comma-separated string to an array of strings
75
- * - Adds placeholder for REGISTER_BACKGROUND / LOGIN_BACKGROUND if absent
76
- * - Wraps the config in defineClientConfig() / defineLoginConfig()
77
- * - Deletes the original .js file
78
- *
79
- * For login config files specifically:
80
- * - Imports applicationConfig from src/api/application/application-config
81
- * - Sources USER_NOTIFICATION_DELIVERY_METHOD, INFORMANT_NOTIFICATION_DELIVERY_METHOD,
82
- * and PHONE_NUMBER_PATTERN from applicationConfig rather than hardcoding them
83
- *
84
- * Phase 2 — Route handler replacement:
85
- * - Finds every Hapi route object whose `path` is '/client-config.js' or '/login-config.js'
86
- * - Replaces the handler (or options.handler) with:
87
- * const config = process.env.NODE_ENV === 'production' ? <prod> : <base>
88
- * return h.response(`window.config = ${JSON.stringify(config)}`).type('application/javascript')
89
- * - Adds the required config imports to the route file
90
- *
91
- * Phase 3 — Wrap applicationConfig with defineApplicationConfig:
92
- * - Finds src/api/application/application-config.ts
93
- * - If the exported applicationConfig is a plain object literal, wraps it with
94
- * defineApplicationConfig() from '@opencrvs/toolkit/application-config'
95
- * - Adds the defineApplicationConfig import if not already present
96
- */
97
- const fs = __importStar(require("fs"));
98
- const ts_morph_1 = require("ts-morph");
99
- const path_1 = __importDefault(require("path"));
100
- // ─── Schema-valid keys per config type ───────────────────────────────────────
101
- const CLIENT_VALID_KEYS = new Set([
102
- 'COUNTRY',
103
- 'LANGUAGES',
104
- 'SENTRY',
105
- 'REGISTER_BACKGROUND',
106
- 'DASHBOARDS',
107
- 'FEATURES'
108
- ]);
109
- const LOGIN_VALID_KEYS = new Set([
110
- 'COUNTRY',
111
- 'LANGUAGES',
112
- 'USER_NOTIFICATION_DELIVERY_METHOD',
113
- 'INFORMANT_NOTIFICATION_DELIVERY_METHOD',
114
- 'PHONE_NUMBER_PATTERN',
115
- 'LOGIN_BACKGROUND',
116
- 'SENTRY'
117
- ]);
118
- // Keys defined in ApplicationConfig from packages/commons/src/application-config.ts
119
- const APPLICATION_CONFIG_VALID_KEYS = new Set([
120
- 'APPLICATION_NAME',
121
- 'COUNTRY_LOGO',
122
- 'SYSTEM_IANA_TIMEZONE',
123
- 'CURRENCY',
124
- 'ADMIN_STRUCTURE',
125
- 'PHONE_NUMBER_PATTERN',
126
- 'USER_NOTIFICATION_DELIVERY_METHOD',
127
- 'INFORMANT_NOTIFICATION_DELIVERY_METHOD',
128
- 'SEARCH_DEFAULT_CRITERIA'
129
- ]);
130
- const CONFIG_GROUPS = [
131
- {
132
- baseName: 'client-config',
133
- prodName: 'client-config.prod',
134
- defineFn: 'defineClientConfig',
135
- importFrom: '@opencrvs/toolkit/application-config',
136
- validKeys: CLIENT_VALID_KEYS,
137
- requiredPlaceholders: {
138
- // BackgroundConfig requires backgroundColor or backgroundImage
139
- REGISTER_BACKGROUND: "{ backgroundColor: '#F4F4F7' }"
140
- },
141
- exportNames: {
142
- 'client-config': 'clientConfig',
143
- 'client-config.prod': 'clientConfigProd'
144
- },
145
- routePath: '/client-config.js'
146
- },
147
- {
148
- baseName: 'login-config',
149
- prodName: 'login-config.prod',
150
- defineFn: 'defineLoginConfig',
151
- importFrom: '@opencrvs/toolkit/application-config',
152
- validKeys: LOGIN_VALID_KEYS,
153
- requiredPlaceholders: {},
154
- // These keys are always sourced from applicationConfig rather than
155
- // copied from the old JS file or filled with a placeholder value.
156
- // LOGIN_BACKGROUND lives in applicationConfig and is not part of the
157
- // ApplicationConfig schema, so Phase 3 will inline its value and remove
158
- // it from applicationConfig automatically.
159
- applicationConfigKeys: [
160
- 'LOGIN_BACKGROUND',
161
- 'USER_NOTIFICATION_DELIVERY_METHOD',
162
- 'INFORMANT_NOTIFICATION_DELIVERY_METHOD',
163
- 'PHONE_NUMBER_PATTERN'
164
- ],
165
- applicationConfigImportPath: './api/application/application-config',
166
- exportNames: {
167
- 'login-config': 'loginConfig',
168
- 'login-config.prod': 'loginConfigProd'
169
- },
170
- routePath: '/login-config.js'
171
- }
172
- ];
173
- // ─── HTTP verb set (for route detection) ─────────────────────────────────────
174
- const HTTP_VERBS = new Set([
175
- 'GET',
176
- 'POST',
177
- 'PUT',
178
- 'PATCH',
179
- 'DELETE',
180
- 'OPTIONS',
181
- 'HEAD',
182
- '*'
183
- ]);
184
- // ─── Phase 1 helpers ──────────────────────────────────────────────────────────
185
- /**
186
- * Parses a JS config file and returns the ObjectLiteralExpression that is the
187
- * right-hand side of the `window.config = { ... }` assignment.
188
- * Handles both direct assignment and IIFE-wrapped assignment.
189
- */
190
- function extractWindowConfig(jsFilePath) {
191
- const jsProject = new ts_morph_1.Project({
192
- compilerOptions: { allowJs: true, checkJs: false }
193
- // addFilesFromTsConfig: false
194
- });
195
- let sourceFile;
196
- try {
197
- sourceFile = jsProject.addSourceFileAtPath(jsFilePath);
198
- }
199
- catch (_a) {
200
- console.warn(` Could not parse ${jsFilePath}`);
201
- return null;
202
- }
203
- for (const binary of sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.BinaryExpression)) {
204
- if (binary.getOperatorToken().getKind() !== ts_morph_1.SyntaxKind.EqualsToken)
205
- continue;
206
- const left = binary.getLeft();
207
- if (!ts_morph_1.Node.isPropertyAccessExpression(left))
208
- continue;
209
- if (left.getExpression().getText() !== 'window')
210
- continue;
211
- if (left.getName() !== 'config')
212
- continue;
213
- const right = binary.getRight();
214
- if (ts_morph_1.Node.isObjectLiteralExpression(right))
215
- return right;
216
- }
217
- return null;
218
- }
219
- /**
220
- * Converts a LANGUAGES string initializer like `'en,fr'` into an array literal
221
- * like `['en', 'fr']`. If the initializer is already an array, returns its
222
- * text unchanged.
223
- */
224
- function convertLanguages(init) {
225
- if (ts_morph_1.Node.isStringLiteral(init)) {
226
- const langs = init
227
- .getLiteralValue()
228
- .split(',')
229
- .map((l) => `'${l.trim()}'`)
230
- .join(', ');
231
- return `[${langs}]`;
232
- }
233
- // Already an array or something else — keep as-is
234
- return init.getText();
235
- }
236
- /**
237
- * Extracts the plain URL string from a string literal or a no-substitution
238
- * template literal (i.e. a backtick string with no ${…} expressions).
239
- * Returns null for anything more complex.
240
- */
241
- function extractStaticUrlString(init) {
242
- if (ts_morph_1.Node.isStringLiteral(init)) {
243
- return init.getLiteralValue();
244
- }
245
- if (init.getKind() === ts_morph_1.SyntaxKind.NoSubstitutionTemplateLiteral) {
246
- // getText() returns the text including surrounding backticks — strip them
247
- const raw = init.getText();
248
- return raw.slice(1, -1);
249
- }
250
- return null;
251
- }
252
- /**
253
- * For prod files, rewrites a DASHBOARDS[].url initializer so that the origin
254
- * (protocol + host + optional port) is replaced with `${scheme}//metabase.${hostname}`
255
- * and the path/query/hash is preserved verbatim.
256
- *
257
- * Returns the original text unchanged for dev files or when the URL cannot be
258
- * parsed.
259
- */
260
- function transformDashboardUrl(init, isProd) {
261
- if (!isProd)
262
- return init.getText();
263
- const urlString = extractStaticUrlString(init);
264
- if (!urlString)
265
- return init.getText();
266
- try {
267
- const parsed = new URL(urlString);
268
- const rest = parsed.pathname + parsed.search + parsed.hash;
269
- // Escape the template literal so the OUTPUT file contains real ${} expressions
270
- return `\`\${scheme}//metabase.\${hostname}${rest}\``;
271
- }
272
- catch (_a) {
273
- return init.getText();
274
- }
275
- }
276
- /**
277
- * For prod files, recursively rewrites every `url` property inside the
278
- * DASHBOARDS array using transformDashboardUrl.
279
- * For dev files, returns the initializer text unchanged.
280
- */
281
- function transformDashboardsValue(init, isProd) {
282
- if (!isProd || !ts_morph_1.Node.isArrayLiteralExpression(init)) {
283
- return init.getText();
284
- }
285
- const elementParts = [];
286
- for (const el of init.getElements()) {
287
- if (!ts_morph_1.Node.isObjectLiteralExpression(el)) {
288
- elementParts.push(el.getText());
289
- continue;
290
- }
291
- const propParts = [];
292
- for (const prop of el.getProperties()) {
293
- if (!ts_morph_1.Node.isPropertyAssignment(prop)) {
294
- propParts.push(prop.getText());
295
- continue;
296
- }
297
- const propName = prop.getName();
298
- const propInit = prop.getInitializer();
299
- if (!propInit) {
300
- propParts.push(prop.getText());
301
- continue;
302
- }
303
- if (propName === 'url') {
304
- propParts.push(`url: ${transformDashboardUrl(propInit, isProd)}`);
305
- }
306
- else {
307
- propParts.push(`${propName}: ${propInit.getText()}`);
308
- }
309
- }
310
- elementParts.push(` {\n${propParts.map((p) => ` ${p}`).join(',\n')}\n }`);
311
- }
312
- return `[\n${elementParts.join(',\n')}\n]`;
313
- }
314
- /**
315
- * Generates the full TypeScript source for a converted config file.
316
- *
317
- * Prod files (isProd = true):
318
- * - Import `env` from './environment'
319
- * - Define `scheme = 'https'`, `hostname = env.DOMAIN`, `sentry = env.SENTRY_DSN`
320
- * - Use `sentry` for the SENTRY property
321
- * - Rewrite DASHBOARDS[].url origins to use scheme/hostname template expressions
322
- *
323
- * Dev files (isProd = false):
324
- * - No env import
325
- * - Define `scheme = 'http'`, `hostname = 'localhost'`
326
- * - Keep SENTRY and DASHBOARDS URLs as-is from the original JS file
327
- */
328
- function generateTsContent(configObj, exportName, group, isProd) {
329
- var _a;
330
- // ── Config properties ────────────────────────────────────────────────────────
331
- const propertyLines = [];
332
- const seenKeys = new Set();
333
- const appConfigKeySet = new Set((_a = group.applicationConfigKeys) !== null && _a !== void 0 ? _a : []);
334
- for (const prop of configObj.getProperties()) {
335
- if (!ts_morph_1.Node.isPropertyAssignment(prop))
336
- continue;
337
- const name = prop.getName();
338
- if (!group.validKeys.has(name))
339
- continue;
340
- // Keys sourced from applicationConfig are always emitted separately below
341
- if (appConfigKeySet.has(name))
342
- continue;
343
- seenKeys.add(name);
344
- const init = prop.getInitializer();
345
- if (!init)
346
- continue;
347
- if (name === 'LANGUAGES') {
348
- propertyLines.push(` LANGUAGES: ${convertLanguages(init)}`);
349
- }
350
- else if (name === 'SENTRY' && isProd) {
351
- propertyLines.push(` SENTRY: sentry`);
352
- }
353
- else if (name === 'DASHBOARDS') {
354
- propertyLines.push(` DASHBOARDS: ${transformDashboardsValue(init, isProd)}`);
355
- }
356
- else {
357
- propertyLines.push(` ${name}: ${init.getText()}`);
358
- }
359
- }
360
- // Add placeholder lines for required keys that were absent in the JS file
361
- for (const [key, placeholder] of Object.entries(group.requiredPlaceholders)) {
362
- if (!seenKeys.has(key)) {
363
- propertyLines.push(` // TODO: configure ${key} — replace this placeholder`, ` ${key}: ${placeholder}`);
364
- }
365
- }
366
- // Always emit applicationConfig-sourced keys last, regardless of whether
367
- // they appeared in the original JS file
368
- for (const key of appConfigKeySet) {
369
- propertyLines.push(` ${key}: applicationConfig.${key}`);
370
- }
371
- const body = propertyLines.join(',\n');
372
- const headerLines = [];
373
- headerLines.push(`import * as fs from 'fs'`);
374
- headerLines.push(`import { join } from 'path'`);
375
- if (isProd) {
376
- headerLines.push(`import { env } from './environment'`);
377
- }
378
- headerLines.push(`import { ${group.defineFn} } from '${group.importFrom}'`);
379
- if (group.applicationConfigImportPath) {
380
- headerLines.push(`import { applicationConfig } from '${group.applicationConfigImportPath}'`);
381
- }
382
- headerLines.push('');
383
- if (isProd) {
384
- headerLines.push(`const scheme = 'https'`);
385
- headerLines.push(`const hostname = env.DOMAIN`);
386
- headerLines.push(`const sentry = env.SENTRY_DSN`);
387
- }
388
- else {
389
- headerLines.push(`const scheme = 'http'`);
390
- headerLines.push(`const hostname = 'localhost'`);
391
- }
392
- return [
393
- ...headerLines,
394
- '',
395
- `export const ${exportName} = ${group.defineFn}({`,
396
- body,
397
- '})',
398
- ''
399
- ].join('\n');
400
- }
401
- /**
402
- * Converts a single JS config file to TypeScript.
403
- * Returns true if a file was written.
404
- */
405
- function convertFile(name, group, srcDir) {
406
- const jsFilePath = path_1.default.join(srcDir, `${name}.js`);
407
- const tsFilePath = path_1.default.join(srcDir, `${name}.ts`);
408
- if (!fs.existsSync(jsFilePath)) {
409
- console.log(` Skipping ${name}.js — file not found`);
410
- return false;
411
- }
412
- if (fs.existsSync(tsFilePath)) {
413
- console.log(` Skipping ${name}.js — ${name}.ts already exists`);
414
- return false;
415
- }
416
- const configObj = extractWindowConfig(jsFilePath);
417
- if (!configObj) {
418
- console.warn(` [${name}.js] Could not locate window.config assignment — skipping`);
419
- return false;
420
- }
421
- const isProd = name.endsWith('.prod');
422
- const exportName = group.exportNames[name];
423
- const content = generateTsContent(configObj, exportName, group, isProd);
424
- fs.writeFileSync(tsFilePath, content, 'utf8');
425
- fs.unlinkSync(jsFilePath);
426
- console.log(` Converted ${name}.js → ${name}.ts (export: ${exportName})`);
427
- return true;
428
- }
429
- // ─── Phase 2 helpers ──────────────────────────────────────────────────────────
430
- /**
431
- * Returns true when an ObjectLiteralExpression is a Hapi route config, i.e. it
432
- * has both a `method` property (a recognised HTTP verb or array of verbs) and a
433
- * `path` property that is a string literal.
434
- */
435
- function isRouteConfig(obj) {
436
- const methodProp = obj.getProperty('method');
437
- if (!methodProp || !ts_morph_1.Node.isPropertyAssignment(methodProp))
438
- return false;
439
- const methodInit = methodProp.getInitializer();
440
- if (!methodInit)
441
- return false;
442
- if (ts_morph_1.Node.isStringLiteral(methodInit)) {
443
- if (!HTTP_VERBS.has(methodInit.getLiteralValue().toUpperCase()))
444
- return false;
445
- }
446
- else if (ts_morph_1.Node.isArrayLiteralExpression(methodInit)) {
447
- const allVerbs = methodInit
448
- .getElements()
449
- .every((el) => ts_morph_1.Node.isStringLiteral(el) &&
450
- HTTP_VERBS.has(el.getLiteralValue().toUpperCase()));
451
- if (!allVerbs)
452
- return false;
453
- }
454
- else {
455
- return false;
456
- }
457
- const pathProp = obj.getProperty('path');
458
- if (!pathProp || !ts_morph_1.Node.isPropertyAssignment(pathProp))
459
- return false;
460
- const pathInit = pathProp.getInitializer();
461
- return !!pathInit && ts_morph_1.Node.isStringLiteral(pathInit);
462
- }
463
- /**
464
- * Returns the string value of a route config's `path` property, or null if not
465
- * available.
466
- */
467
- function getRoutePath(obj) {
468
- const pathProp = obj.getProperty('path');
469
- if (!pathProp || !ts_morph_1.Node.isPropertyAssignment(pathProp))
470
- return null;
471
- const pathInit = pathProp.getInitializer();
472
- if (!pathInit || !ts_morph_1.Node.isStringLiteral(pathInit))
473
- return null;
474
- return pathInit.getLiteralValue();
475
- }
476
- /**
477
- * Finds the PropertyAssignment for the handler function inside a route config.
478
- * Looks at both `handler` (top-level) and `options.handler` (nested).
479
- */
480
- function findHandlerProperty(routeObj) {
481
- // Top-level handler
482
- const directHandler = routeObj.getProperty('handler');
483
- if (directHandler && ts_morph_1.Node.isPropertyAssignment(directHandler)) {
484
- return directHandler;
485
- }
486
- // options.handler
487
- const optionsProp = routeObj.getProperty('options');
488
- if (optionsProp && ts_morph_1.Node.isPropertyAssignment(optionsProp)) {
489
- const optionsInit = optionsProp.getInitializer();
490
- if (optionsInit && ts_morph_1.Node.isObjectLiteralExpression(optionsInit)) {
491
- const nestedHandler = optionsInit.getProperty('handler');
492
- if (nestedHandler && ts_morph_1.Node.isPropertyAssignment(nestedHandler)) {
493
- return nestedHandler;
494
- }
495
- }
496
- }
497
- return null;
498
- }
499
- /**
500
- * Ensures the source file has named imports for both the base and prod config
501
- * exports, adding the import declarations if they are not already present.
502
- */
503
- function ensureConfigImports(sourceFile, group, srcDir) {
504
- const routeFileDir = path_1.default.dirname(sourceFile.getFilePath());
505
- for (const name of [group.baseName, group.prodName]) {
506
- const exportName = group.exportNames[name];
507
- const absoluteConfigPath = path_1.default.join(srcDir, name);
508
- const rel = path_1.default
509
- .relative(routeFileDir, absoluteConfigPath)
510
- .replace(/\\/g, '/');
511
- const moduleSpecifier = rel.startsWith('.') ? rel : `./${rel}`;
512
- const alreadyImported = sourceFile
513
- .getImportDeclarations()
514
- .some((d) => d.getModuleSpecifierValue() === moduleSpecifier ||
515
- d.getNamedImports().some((ni) => ni.getName() === exportName));
516
- if (!alreadyImported) {
517
- sourceFile.addImportDeclaration({
518
- moduleSpecifier,
519
- namedImports: [exportName]
520
- });
521
- }
522
- }
523
- }
524
- /**
525
- * Processes all TypeScript source files for route handler replacements.
526
- * Returns the total number of handlers replaced.
527
- */
528
- function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
529
- const baseExport = group.exportNames[group.baseName];
530
- const prodExport = group.exportNames[group.prodName];
531
- // The new handler body — note the escaped template literal so that the
532
- // output file contains a real template literal, not an interpolation here.
533
- const newHandlerText = `async (request, h) => {
534
- const config =
535
- process.env.NODE_ENV === 'production' ? ${prodExport} : ${baseExport}
536
- return h
537
- .response(\`window.config = \${JSON.stringify(config)}\`)
538
- .type('application/javascript')
539
- }`;
540
- let replacedCount = 0;
541
- for (const sourceFile of sourceFiles) {
542
- const filePath = sourceFile.getFilePath();
543
- const candidates = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.ObjectLiteralExpression);
544
- for (const obj of candidates) {
545
- if (!isRouteConfig(obj))
546
- continue;
547
- if (getRoutePath(obj) !== group.routePath)
548
- continue;
549
- const handlerProp = findHandlerProperty(obj);
550
- if (!handlerProp) {
551
- console.warn(` [${relCwd(filePath)}] Found route '${group.routePath}' but could not locate handler property — skipping`);
552
- continue;
553
- }
554
- handlerProp.setInitializer(newHandlerText);
555
- ensureConfigImports(sourceFile, group, srcDir);
556
- replacedCount++;
557
- console.log(` [${relCwd(filePath)}] Replaced handler for route '${group.routePath}'`);
558
- }
559
- }
560
- return replacedCount;
561
- }
562
- // ─── Phase 3 helper ──────────────────────────────────────────────────────────
563
- /**
564
- * Resolves a chain of property accesses on an ObjectLiteralExpression.
565
- * E.g. given path ['BIRTH', 'LATE_REGISTRATION_TARGET'] and an object
566
- * `{ BIRTH: { LATE_REGISTRATION_TARGET: 45 } }`, returns the text '45'.
567
- * Returns null if any segment of the path cannot be resolved.
568
- */
569
- function resolveConfigChain(configObj, path) {
570
- let current = configObj;
571
- for (const key of path) {
572
- if (!ts_morph_1.Node.isObjectLiteralExpression(current))
573
- return null;
574
- const prop = current.getProperty(key);
575
- if (!prop || !ts_morph_1.Node.isPropertyAssignment(prop))
576
- return null;
577
- const initNode = prop.getInitializer();
578
- if (!initNode)
579
- return null;
580
- current = initNode;
581
- }
582
- return current.getText();
583
- }
584
- /**
585
- * When inlining a value from `application-config.ts` into a file in a
586
- * different directory, `__dirname`-based paths (e.g. for reading image
587
- * assets) must be adjusted so they continue to resolve to the original
588
- * location — the referenced files themselves are NOT moved.
589
- *
590
- * Rewrites `join(__dirname, ...)` / `path.join(__dirname, ...)` /
591
- * `resolve(__dirname, ...)` / `path.resolve(__dirname, ...)` by inserting
592
- * the relative path from the target directory back to the source directory
593
- * as an extra leading argument.
594
- *
595
- * Example: inlining from `src/api/application/` into `src/login-config.ts`
596
- * join(__dirname, 'login-bg.jpg')
597
- * → join(__dirname, 'api/application', 'login-bg.jpg')
598
- */
599
- function rewriteDirnameRefs(text, relDir) {
600
- if (!relDir || relDir === '.')
601
- return text;
602
- const relForward = relDir.replace(/\\/g, '/');
603
- return text.replace(/\b((?:path\.)?(?:join|resolve))\s*\(\s*__dirname\s*,/g, `$1(__dirname, '${relForward}',`);
604
- }
605
- /**
606
- * Ensures the source file has a namespace `fs` import (`import * as fs from 'fs'`).
607
- * No-op if a namespace or default `fs` import is already present.
608
- */
609
- function ensureFsImport(sf) {
610
- const hasFs = sf
611
- .getImportDeclarations()
612
- .some((d) => d.getModuleSpecifierValue() === 'fs' &&
613
- (d.getNamespaceImport() || d.getDefaultImport()));
614
- if (hasFs)
615
- return;
616
- sf.addImportDeclaration({
617
- moduleSpecifier: 'fs',
618
- namespaceImport: 'fs'
619
- });
620
- }
621
- /**
622
- * Ensures the source file has a named `join` import from 'path'.
623
- * Merges into an existing 'path' import if present, otherwise adds a new
624
- * `import { join } from 'path'` declaration.
625
- */
626
- function ensureJoinImport(sf) {
627
- const pathImports = sf
628
- .getImportDeclarations()
629
- .filter((d) => d.getModuleSpecifierValue() === 'path');
630
- if (pathImports.some((d) => d.getNamedImports().some((ni) => ni.getName() === 'join'))) {
631
- return;
632
- }
633
- if (pathImports.length > 0) {
634
- pathImports[0].addNamedImport('join');
635
- return;
636
- }
637
- sf.addImportDeclaration({
638
- moduleSpecifier: 'path',
639
- namedImports: ['join']
640
- });
641
- }
642
- // ─── Entry point ─────────────────────────────────────────────────────────────
643
- function main() {
644
- return __awaiter(this, void 0, void 0, function* () {
645
- var _a;
646
- const srcDir = path_1.default.join(process.cwd(), 'src');
647
- const relCwd = (fp) => path_1.default.relative(process.cwd(), fp);
648
- // ── Phase 1: Convert JS config files to TypeScript ────────────────────────
649
- console.log('Phase 1: Converting JS config files to TypeScript...\n');
650
- let convertedCount = 0;
651
- for (const group of CONFIG_GROUPS) {
652
- for (const name of [group.baseName, group.prodName]) {
653
- if (convertFile(name, group, srcDir)) {
654
- convertedCount++;
655
- }
656
- }
657
- }
658
- if (convertedCount === 0) {
659
- console.log(' No JS config files needed conversion.\n');
660
- }
661
- else {
662
- console.log(`\n Converted ${convertedCount} file(s).\n`);
663
- }
664
- // ── Phase 3: Wrap applicationConfig with defineApplicationConfig ──────────
665
- console.log('Phase 3: Wrapping applicationConfig with defineApplicationConfig...\n');
666
- const appConfigRelPath = 'api/application/application-config.ts';
667
- const appConfigAbsPath = path_1.default.join(srcDir, appConfigRelPath);
668
- if (!fs.existsSync(appConfigAbsPath)) {
669
- console.log(` Skipping Phase 3 — ${appConfigRelPath} not found in src/\n`);
670
- }
671
- else {
672
- const appConfigProject = new ts_morph_1.Project({
673
- tsConfigFilePath: path_1.default.resolve(srcDir, '../tsconfig.json'),
674
- skipAddingFilesFromTsConfig: false
675
- });
676
- const appConfigFile = (_a = appConfigProject.getSourceFile(appConfigAbsPath)) !== null && _a !== void 0 ? _a : appConfigProject.addSourceFileAtPath(appConfigAbsPath);
677
- let wrapped = false;
678
- for (const varDecl of appConfigFile.getVariableDeclarations()) {
679
- if (varDecl.getName() !== 'applicationConfig')
680
- continue;
681
- const init = varDecl.getInitializer();
682
- if (!init || !ts_morph_1.Node.isObjectLiteralExpression(init))
683
- continue;
684
- // Remove properties not defined in the ApplicationConfig schema
685
- const propsToRemove = init.getProperties().filter((prop) => {
686
- if (!ts_morph_1.Node.isPropertyAssignment(prop))
687
- return false;
688
- const name = prop
689
- .getNameNode()
690
- .getText()
691
- .replace(/^['"]|['"]$/g, '');
692
- return !APPLICATION_CONFIG_VALID_KEYS.has(name);
693
- });
694
- if (propsToRemove.length > 0) {
695
- // Before removing, inline every cross-file reference to each unknown key.
696
- // Example: applicationConfig.BIRTH.LATE_REGISTRATION_TARGET → 45
697
- const filesToSaveAfterInlining = new Set();
698
- const appConfigDir = path_1.default.dirname(appConfigAbsPath);
699
- for (const removedProp of propsToRemove) {
700
- const key = removedProp.getName();
701
- for (const sf of appConfigProject.getSourceFiles()) {
702
- // Skip the config file itself, files outside src/, and node_modules
703
- if (sf.getFilePath() === appConfigAbsPath)
704
- continue;
705
- if (!sf.getFilePath().includes('/src/'))
706
- continue;
707
- if (sf.getFilePath().includes('/node_modules/'))
708
- continue;
709
- // Relative path from the target file's directory back to the
710
- // applicationConfig's directory. Used to adjust `__dirname`-based
711
- // paths in the inlined value (e.g. image asset references) since
712
- // those assets are not moved.
713
- const targetDir = path_1.default.dirname(sf.getFilePath());
714
- const relDirFromTarget = path_1.default.relative(targetDir, appConfigDir);
715
- // Break-and-restart after each replacement because replaceWithText()
716
- // invalidates existing node references in the ts-morph tree
717
- let madeReplacement = true;
718
- while (madeReplacement) {
719
- madeReplacement = false;
720
- for (const identNode of sf.getDescendantsOfKind(ts_morph_1.SyntaxKind.Identifier)) {
721
- if (identNode.getText() !== 'applicationConfig')
722
- continue;
723
- // Walk up the property-access chain from this identifier
724
- let node = identNode;
725
- const accessPath = [];
726
- while (true) {
727
- const parent = node.getParent();
728
- if (!ts_morph_1.Node.isPropertyAccessExpression(parent))
729
- break;
730
- if (parent.getExpression() !== node)
731
- break;
732
- accessPath.push(parent.getName());
733
- node = parent;
734
- }
735
- if (accessPath.length === 0 || accessPath[0] !== key)
736
- continue;
737
- const resolvedValue = resolveConfigChain(init, accessPath);
738
- if (resolvedValue === null) {
739
- console.log(` Cannot resolve applicationConfig.${accessPath.join('.')} — skipping inline replacement`);
740
- continue;
741
- }
742
- const adjustedValue = rewriteDirnameRefs(resolvedValue, relDirFromTarget);
743
- node.replaceWithText(adjustedValue);
744
- // If the inlined value references `fs` or `join`, ensure the
745
- // target file has the corresponding imports — these are
746
- // commonly used to read image assets from disk.
747
- if (/\bfs\s*\./.test(adjustedValue)) {
748
- ensureFsImport(sf);
749
- }
750
- if (/\bjoin\s*\(/.test(adjustedValue)) {
751
- ensureJoinImport(sf);
752
- }
753
- console.log(` Inlined applicationConfig.${accessPath.join('.')} → ${adjustedValue} in ${path_1.default.relative(process.cwd(), sf.getFilePath())}`);
754
- filesToSaveAfterInlining.add(sf);
755
- madeReplacement = true;
756
- break; // restart — tree has changed
757
- }
758
- }
759
- }
760
- }
761
- // Persist files that received inline replacements
762
- for (const sf of Array.from(filesToSaveAfterInlining)) {
763
- yield sf.save();
764
- console.log(` Saved (inlined): ${path_1.default.relative(process.cwd(), sf.getFilePath())}`);
765
- }
766
- // Remove in reverse order to avoid index shifting
767
- for (const prop of [...propsToRemove].reverse()) {
768
- const propName = prop.getName();
769
- console.log(` Removing unknown key '${propName}' from applicationConfig (not in ApplicationConfig schema)`);
770
- prop.remove();
771
- }
772
- }
773
- // Wrap the plain object literal with defineApplicationConfig(...)
774
- varDecl.setInitializer(`defineApplicationConfig(${init.getText()})`);
775
- // Upsert the defineApplicationConfig named import
776
- const TOOLKIT_MODULE = '@opencrvs/toolkit/application-config';
777
- const existing = appConfigFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === TOOLKIT_MODULE);
778
- if (existing) {
779
- const names = new Set(existing.getNamedImports().map((ni) => ni.getName()));
780
- if (!names.has('defineApplicationConfig')) {
781
- existing.addNamedImport('defineApplicationConfig');
782
- }
783
- }
784
- else {
785
- appConfigFile.addImportDeclaration({
786
- moduleSpecifier: TOOLKIT_MODULE,
787
- namedImports: ['defineApplicationConfig']
788
- });
789
- }
790
- wrapped = true;
791
- console.log(` Wrapped applicationConfig with defineApplicationConfig in ${appConfigRelPath}`);
792
- break;
793
- }
794
- if (!wrapped) {
795
- console.log(` Skipping Phase 3 — applicationConfig plain object not found (already wrapped?)\n`);
796
- }
797
- else {
798
- yield appConfigFile.save();
799
- console.log(` Saved: ${appConfigRelPath}\n`);
800
- }
801
- }
802
- // ── Phase 2: Update Hapi route handlers ───────────────────────────────────
803
- console.log('Phase 2: Updating Hapi route handlers...\n');
804
- const project = new ts_morph_1.Project({
805
- tsConfigFilePath: path_1.default.resolve(srcDir, '../tsconfig.json'),
806
- skipAddingFilesFromTsConfig: false
807
- });
808
- const sourceFiles = project.getSourceFiles().filter((sf) => {
809
- const fp = sf.getFilePath();
810
- return fp.includes('/src/') && !fp.includes('/node_modules/');
811
- });
812
- console.log(` Analysing ${sourceFiles.length} source file(s).\n`);
813
- let totalReplaced = 0;
814
- for (const group of CONFIG_GROUPS) {
815
- totalReplaced += updateRouteHandlers(sourceFiles, group, srcDir, relCwd);
816
- }
817
- if (totalReplaced === 0) {
818
- console.log(' No route handlers matched — nothing to update in Phase 2.\n');
819
- }
820
- // ── Save modified TS files ────────────────────────────────────────────────
821
- const modified = sourceFiles.filter((sf) => sf.wasForgotten() === false);
822
- const toSave = modified.filter((sf) => sf.getDescendantsOfKind(ts_morph_1.SyntaxKind.ObjectLiteralExpression).length > 0);
823
- // Only save files that actually had route handler changes
824
- let savedCount = 0;
825
- for (const sf of project.getSourceFiles()) {
826
- if (sf.isSaved())
827
- continue;
828
- yield sf.save();
829
- console.log(` Saved: ${relCwd(sf.getFilePath())}`);
830
- savedCount++;
831
- }
832
- if (savedCount === 0 && totalReplaced === 0) {
833
- console.log('Nothing was changed.');
834
- return;
835
- }
836
- console.log(`\nDone. Converted ${convertedCount} config file(s), replaced ${totalReplaced} route handler(s).`);
837
- });
838
- }