@opencrvs/toolkit 1.9.12-rc.c4223c6 → 1.9.12-rc.c4d2a9f
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.
- package/dist/cli.js +400 -4
- package/dist/commons/api/router.d.ts +125 -138
- package/dist/commons/events/EventConfig.d.ts +3 -1
- package/dist/events/index.js +14 -3
- package/dist/migrations/v2.0/checkout-upstream-files.d.ts +3 -0
- package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -0
- package/dist/migrations/v2.0/checkout-upstream-files.js +143 -0
- package/dist/migrations/v2.0/create-events-index.d.ts +3 -0
- package/dist/migrations/v2.0/create-events-index.d.ts.map +1 -0
- package/dist/migrations/v2.0/create-events-index.js +326 -0
- package/dist/migrations/v2.0/index.d.ts.map +1 -1
- package/dist/migrations/v2.0/index.js +398 -2
- package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts +3 -0
- package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +1 -0
- package/dist/migrations/v2.0/simplify-analytics-precalculations.js +196 -0
- package/dist/notification/index.js +3 -0
- package/opencrvs-toolkit-1.9.12-rc.c4d2a9f.tgz +0 -0
- package/package.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
- package/opencrvs-toolkit-1.9.12-rc.c4223c6.tgz +0 -0
|
@@ -29,14 +29,16 @@ export type EventConfig = {
|
|
|
29
29
|
declaration: DeclarationFormConfig;
|
|
30
30
|
advancedSearch: AdvancedSearchConfig[];
|
|
31
31
|
flags: FlagConfig[];
|
|
32
|
+
analytics: boolean;
|
|
32
33
|
};
|
|
33
|
-
export type EventConfigInput = Omit<EventConfig, 'advancedSearch' | 'flags' | 'declaration' | 'actions' | 'dateOfEvent' | 'placeOfEvent'> & {
|
|
34
|
+
export type EventConfigInput = Omit<EventConfig, 'advancedSearch' | 'flags' | 'declaration' | 'actions' | 'dateOfEvent' | 'placeOfEvent' | 'analytics'> & {
|
|
34
35
|
dateOfEvent?: z.input<typeof FieldReference> | z.infer<typeof EventFieldReference>;
|
|
35
36
|
placeOfEvent?: z.input<typeof FieldReference>;
|
|
36
37
|
advancedSearch?: AdvancedSearchConfig[];
|
|
37
38
|
flags?: FlagConfig[];
|
|
38
39
|
declaration: DeclarationFormConfigInput;
|
|
39
40
|
actions: z.input<typeof ActionConfig>[];
|
|
41
|
+
analytics?: boolean;
|
|
40
42
|
};
|
|
41
43
|
export declare const EventConfig: z.ZodType<EventConfig, EventConfigInput>;
|
|
42
44
|
//# sourceMappingURL=EventConfig.d.ts.map
|
package/dist/events/index.js
CHANGED
|
@@ -4574,7 +4574,16 @@ function aggregateActionDeclarations(event2) {
|
|
|
4574
4574
|
if (!requestAction) {
|
|
4575
4575
|
return declaration;
|
|
4576
4576
|
}
|
|
4577
|
-
|
|
4577
|
+
const declarationWithApprovedCorrection = getCompleteActionDeclaration(
|
|
4578
|
+
declaration,
|
|
4579
|
+
event2,
|
|
4580
|
+
requestAction
|
|
4581
|
+
);
|
|
4582
|
+
return getCompleteActionDeclaration(
|
|
4583
|
+
declarationWithApprovedCorrection,
|
|
4584
|
+
event2,
|
|
4585
|
+
action
|
|
4586
|
+
);
|
|
4578
4587
|
}
|
|
4579
4588
|
return getCompleteActionDeclaration(declaration, event2, action);
|
|
4580
4589
|
}, {});
|
|
@@ -5342,6 +5351,9 @@ var _EventConfigBase = z33.object({
|
|
|
5342
5351
|
),
|
|
5343
5352
|
flags: z33.array(FlagConfig).optional().default([]).describe(
|
|
5344
5353
|
"Configuration of flags associated with the actions of this event type."
|
|
5354
|
+
),
|
|
5355
|
+
analytics: z33.boolean().optional().default(true).describe(
|
|
5356
|
+
"Indicates whether the records of this event type are included in analytics"
|
|
5345
5357
|
)
|
|
5346
5358
|
});
|
|
5347
5359
|
var EventConfig = _EventConfigBase.superRefine((event2, ctx) => {
|
|
@@ -10010,8 +10022,7 @@ function userDeserializer(serializedUserField, user2) {
|
|
|
10010
10022
|
`Deserializer for ${serializedUserField.$userField} is not implemented yet`
|
|
10011
10023
|
);
|
|
10012
10024
|
}
|
|
10013
|
-
|
|
10014
|
-
return typeof value === "string" ? value : void 0;
|
|
10025
|
+
return user2[serializedUserField.$userField] ?? void 0;
|
|
10015
10026
|
}
|
|
10016
10027
|
function isDefined(value) {
|
|
10017
10028
|
return value !== void 0;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"checkout-upstream-files.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.0/checkout-upstream-files.ts"],"names":[],"mappings":"AA0GA,iBAAe,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAuDnC;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
4
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
5
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
6
|
+
*
|
|
7
|
+
* OpenCRVS is also distributed under the terms of the Civil Registration
|
|
8
|
+
* & Healthcare Disclaimer located at http://opencrvs.org/license.
|
|
9
|
+
*
|
|
10
|
+
* Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
|
|
11
|
+
*/
|
|
12
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
13
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
14
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
15
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
16
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
17
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
18
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
+
exports.main = main;
|
|
23
|
+
/**
|
|
24
|
+
* Codemod: Replace selected files with their upstream v2.0 versions from
|
|
25
|
+
* opencrvs/opencrvs-countryconfig.
|
|
26
|
+
*
|
|
27
|
+
* Usage:
|
|
28
|
+
* ts-node -r tsconfig-paths/register src/migrations/v2.0/checkout-upstream-files.ts
|
|
29
|
+
*
|
|
30
|
+
* What it does:
|
|
31
|
+
* 1. Registers a temporary git remote that points at the canonical
|
|
32
|
+
* opencrvs-countryconfig repository.
|
|
33
|
+
* 2. Fetches the chosen upstream branch at --depth=1 to keep it fast.
|
|
34
|
+
* 3. Path-scoped checkouts each listed file from that branch. The upstream
|
|
35
|
+
* version is written to the working tree AND staged in the index, so
|
|
36
|
+
* the dev can review the diff afterwards with:
|
|
37
|
+
* git diff --cached -- <file>
|
|
38
|
+
* 4. Removes the temporary remote in all cases (success, failure, or
|
|
39
|
+
* unexpected error) via a `finally` block.
|
|
40
|
+
*
|
|
41
|
+
* Why a git-based approach (as opposed to a raw HTTPS download):
|
|
42
|
+
* - Git handles text, binary, and line endings correctly.
|
|
43
|
+
* - The checked-out files end up staged, giving an obvious review UX.
|
|
44
|
+
* - `git checkout <ref> -- <paths>` is a blob-level copy, so it works
|
|
45
|
+
* whether or not the target repo shares history with
|
|
46
|
+
* opencrvs-countryconfig (e.g. country implementations started from
|
|
47
|
+
* scratch rather than forked).
|
|
48
|
+
*
|
|
49
|
+
* Caveats:
|
|
50
|
+
* - Overwrites any local modifications to the listed files. Run the
|
|
51
|
+
* upgrade on a clean working tree, or accept that the upstream version
|
|
52
|
+
* replaces yours.
|
|
53
|
+
* - Requires git to be installed and network access to github.com.
|
|
54
|
+
* - Requires the country config working directory to be a git repo.
|
|
55
|
+
*/
|
|
56
|
+
const child_process_1 = require("child_process");
|
|
57
|
+
const _1 = require(".");
|
|
58
|
+
const UPSTREAM_URL = 'https://github.com/opencrvs/opencrvs-countryconfig.git';
|
|
59
|
+
// @TODO: This needs to be changed to 'release-v2.0.0' once the branch is created
|
|
60
|
+
const UPSTREAM_BRANCH = 'develop';
|
|
61
|
+
// Remote name used only for the duration of this codemod. Prefixed to avoid
|
|
62
|
+
// clashing with remotes the user may have (origin, upstream, etc.).
|
|
63
|
+
const TEMP_REMOTE = 'opencrvs-upgrade-v19-v20-codemod';
|
|
64
|
+
const FILES_TO_CHECKOUT = [
|
|
65
|
+
'infrastructure/postgres/setup-analytics.sh',
|
|
66
|
+
'src/analytics/analytics.ts'
|
|
67
|
+
];
|
|
68
|
+
// ─── Git helpers ─────────────────────────────────────────────────────────────
|
|
69
|
+
/**
|
|
70
|
+
* Runs a git command in the country config working directory.
|
|
71
|
+
*
|
|
72
|
+
* By default stderr is inherited so the user sees progress output from
|
|
73
|
+
* long-running commands (e.g. `git fetch`). Pass `silent: true` to suppress
|
|
74
|
+
* both stdout and stderr when you only care about the exit code.
|
|
75
|
+
*/
|
|
76
|
+
function runGit(args, { silent = false } = {}) {
|
|
77
|
+
return (0, child_process_1.execFileSync)('git', args, {
|
|
78
|
+
cwd: (0, _1.getCwd)(),
|
|
79
|
+
encoding: 'utf8',
|
|
80
|
+
stdio: silent ? ['ignore', 'pipe', 'pipe'] : ['ignore', 'pipe', 'inherit']
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Runs a git command and returns true on success, false on failure.
|
|
85
|
+
* Stderr/stdout are suppressed — use only when the exit code is the only
|
|
86
|
+
* signal you care about.
|
|
87
|
+
*/
|
|
88
|
+
function tryGit(args) {
|
|
89
|
+
try {
|
|
90
|
+
runGit(args, { silent: true });
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
catch (_a) {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function assertIsGitRepo() {
|
|
98
|
+
if (!tryGit(['rev-parse', '--is-inside-work-tree'])) {
|
|
99
|
+
throw new Error(`checkout-upstream-files: ${(0, _1.getCwd)()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
// ─── Entry point ─────────────────────────────────────────────────────────────
|
|
103
|
+
function main() {
|
|
104
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
105
|
+
console.log(`Checking out ${FILES_TO_CHECKOUT.length} file(s) from ${UPSTREAM_URL}@${UPSTREAM_BRANCH}...\n`);
|
|
106
|
+
assertIsGitRepo();
|
|
107
|
+
// Best-effort cleanup of a stale temp remote from a previous aborted run.
|
|
108
|
+
tryGit(['remote', 'remove', TEMP_REMOTE]);
|
|
109
|
+
try {
|
|
110
|
+
console.log(` Adding temporary remote '${TEMP_REMOTE}' → ${UPSTREAM_URL}`);
|
|
111
|
+
runGit(['remote', 'add', TEMP_REMOTE, UPSTREAM_URL], { silent: true });
|
|
112
|
+
console.log(` Fetching ${TEMP_REMOTE}/${UPSTREAM_BRANCH} (depth 1)...`);
|
|
113
|
+
runGit(['fetch', '--depth=1', TEMP_REMOTE, UPSTREAM_BRANCH]);
|
|
114
|
+
const ref = `${TEMP_REMOTE}/${UPSTREAM_BRANCH}`;
|
|
115
|
+
const missing = [];
|
|
116
|
+
let checkedOut = 0;
|
|
117
|
+
for (const file of FILES_TO_CHECKOUT) {
|
|
118
|
+
// `--` separates paths from refs and avoids ambiguity when a path
|
|
119
|
+
// happens to match a branch/tag name.
|
|
120
|
+
if (tryGit(['checkout', ref, '--', file])) {
|
|
121
|
+
console.log(` Checked out ${file} from ${ref}`);
|
|
122
|
+
checkedOut++;
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
console.warn(` [warn] ${file} not found on ${ref} — skipping. Verify the path exists on that branch.`);
|
|
126
|
+
missing.push(file);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
console.log(`\n Checked out ${checkedOut}/${FILES_TO_CHECKOUT.length} file(s) from ${ref}.`);
|
|
130
|
+
if (missing.length > 0) {
|
|
131
|
+
console.warn(` Missing on upstream branch: ${missing.join(', ')}`);
|
|
132
|
+
}
|
|
133
|
+
if (checkedOut > 0) {
|
|
134
|
+
console.log(` Review the staged changes with: git diff --cached -- ${FILES_TO_CHECKOUT.map((f) => `'${f}'`).join(' ')}\n`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
if (tryGit(['remote', 'remove', TEMP_REMOTE])) {
|
|
139
|
+
console.log(` Removed temporary remote '${TEMP_REMOTE}'.`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-events-index.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.0/create-events-index.ts"],"names":[],"mappings":"AAqTA,iBAAe,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAmEnC;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
4
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
5
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
6
|
+
*
|
|
7
|
+
* OpenCRVS is also distributed under the terms of the Civil Registration
|
|
8
|
+
* & Healthcare Disclaimer located at http://opencrvs.org/license.
|
|
9
|
+
*
|
|
10
|
+
* Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
|
|
11
|
+
*/
|
|
12
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
13
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
14
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
15
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
16
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
17
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
18
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
22
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
23
|
+
};
|
|
24
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
|
+
exports.main = main;
|
|
26
|
+
/**
|
|
27
|
+
* Codemod: Create `src/events/index.ts` that collects every `defineConfig`
|
|
28
|
+
* event export, and rewire the event-config handler to import from it.
|
|
29
|
+
*
|
|
30
|
+
* Usage:
|
|
31
|
+
* ts-node -r tsconfig-paths/register src/migrations/v2.0/create-events-index.ts
|
|
32
|
+
*
|
|
33
|
+
* Context:
|
|
34
|
+
* No codemod currently *moves* event-config source files into `src/events/`.
|
|
35
|
+
* Event configs therefore still live wherever the country defined them
|
|
36
|
+
* (typically `src/form/...`). This codemod works regardless of their
|
|
37
|
+
* location by discovering every `export const X = defineConfig(...)`
|
|
38
|
+
* declaration in `src/`.
|
|
39
|
+
*
|
|
40
|
+
* What it does:
|
|
41
|
+
* 1. Scans `src/` for every top-level `export const X = defineConfig(...)`
|
|
42
|
+
* declaration and records `{ name, filePath }` pairs.
|
|
43
|
+
* 2. Creates `src/events/index.ts` (if it does not already exist) that
|
|
44
|
+
* imports each event config from its actual file location using a
|
|
45
|
+
* relative path from `src/events/`, and exports:
|
|
46
|
+
* export const eventConfigs = [<name1>, <name2>, ...]
|
|
47
|
+
* 3. Locates the event-config Hapi handler file (a file whose top level
|
|
48
|
+
* declares a function named `getCustomEventsHandler` or
|
|
49
|
+
* `getEventsHandler`) and:
|
|
50
|
+
* - Removes direct named imports of the event configs it no longer
|
|
51
|
+
* needs, cleaning up the import declaration if it becomes empty.
|
|
52
|
+
* - Removes any previously-inlined `export const eventConfigs = [...]`
|
|
53
|
+
* at the top level (in case an earlier codemod version hoisted one).
|
|
54
|
+
* - Adds `import { eventConfigs } from '@countryconfig/events'`
|
|
55
|
+
* (merging into an existing import of the same module if present).
|
|
56
|
+
* - Rewrites `h.response([<identifiers>]).code(...)` inside the
|
|
57
|
+
* handler to `h.response(eventConfigs).code(...)`.
|
|
58
|
+
* 4. Saves the modified files.
|
|
59
|
+
*
|
|
60
|
+
* The codemod is safe to re-run: if `src/events/index.ts` already exists it
|
|
61
|
+
* is left untouched, and handler modifications are idempotent.
|
|
62
|
+
*/
|
|
63
|
+
const ts_morph_1 = require("ts-morph");
|
|
64
|
+
const fs_1 = __importDefault(require("fs"));
|
|
65
|
+
const path_1 = __importDefault(require("path"));
|
|
66
|
+
const _1 = require(".");
|
|
67
|
+
const DEFINE_CONFIG_NAME = 'defineConfig';
|
|
68
|
+
const HANDLER_FUNCTION_NAMES = new Set([
|
|
69
|
+
'getCustomEventsHandler',
|
|
70
|
+
'getEventsHandler'
|
|
71
|
+
]);
|
|
72
|
+
const EVENT_CONFIGS_IDENTIFIER = 'eventConfigs';
|
|
73
|
+
const EVENTS_INDEX_IMPORT_PATH = '@countryconfig/events';
|
|
74
|
+
const RESPONSE_METHOD_NAME = 'response';
|
|
75
|
+
const LICENSE_HEADER = `/*
|
|
76
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
77
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
78
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
79
|
+
*
|
|
80
|
+
* OpenCRVS is also distributed under the terms of the Civil Registration
|
|
81
|
+
* & Healthcare Disclaimer located at http://opencrvs.org/license.
|
|
82
|
+
*
|
|
83
|
+
* Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
|
|
84
|
+
*/
|
|
85
|
+
`;
|
|
86
|
+
// ─── Discovery ───────────────────────────────────────────────────────────────
|
|
87
|
+
/**
|
|
88
|
+
* Returns every top-level `export const X = defineConfig(...)` declaration in
|
|
89
|
+
* files under `srcDir`. A declaration may wrap the call in a type assertion
|
|
90
|
+
* (`... as EventConfig`) — this is unwrapped before matching.
|
|
91
|
+
*
|
|
92
|
+
* An existing `src/events/index.ts` is excluded so re-runs don't pick up its
|
|
93
|
+
* re-exports as source definitions.
|
|
94
|
+
*/
|
|
95
|
+
function findEventConfigExports(project, srcDir) {
|
|
96
|
+
const found = [];
|
|
97
|
+
const eventsIndexAbs = path_1.default.join(srcDir, 'events', 'index.ts');
|
|
98
|
+
for (const sourceFile of project.getSourceFiles()) {
|
|
99
|
+
const filePath = sourceFile.getFilePath();
|
|
100
|
+
if (!filePath.startsWith(srcDir) || filePath.includes('/node_modules/')) {
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (filePath === eventsIndexAbs)
|
|
104
|
+
continue;
|
|
105
|
+
for (const statement of sourceFile.getVariableStatements()) {
|
|
106
|
+
if (!statement.hasExportKeyword())
|
|
107
|
+
continue;
|
|
108
|
+
for (const decl of statement.getDeclarations()) {
|
|
109
|
+
const initializer = decl.getInitializer();
|
|
110
|
+
if (!initializer)
|
|
111
|
+
continue;
|
|
112
|
+
const unwrapped = ts_morph_1.Node.isAsExpression(initializer)
|
|
113
|
+
? initializer.getExpression()
|
|
114
|
+
: initializer;
|
|
115
|
+
if (!ts_morph_1.Node.isCallExpression(unwrapped))
|
|
116
|
+
continue;
|
|
117
|
+
const callee = unwrapped.getExpression();
|
|
118
|
+
if (!ts_morph_1.Node.isIdentifier(callee))
|
|
119
|
+
continue;
|
|
120
|
+
if (callee.getText() !== DEFINE_CONFIG_NAME)
|
|
121
|
+
continue;
|
|
122
|
+
found.push({ name: decl.getName(), filePath });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return found;
|
|
127
|
+
}
|
|
128
|
+
// ─── Path helpers ────────────────────────────────────────────────────────────
|
|
129
|
+
/**
|
|
130
|
+
* Builds the POSIX module-specifier string used by `src/events/index.ts` to
|
|
131
|
+
* import from `eventConfigFilePath`.
|
|
132
|
+
*
|
|
133
|
+
* - Strips the trailing `.ts` extension.
|
|
134
|
+
* - Collapses `/index` so `src/form/v2/birth/index.ts` → `../form/v2/birth`.
|
|
135
|
+
* - Ensures the result starts with `./` or `../` (relative paths are required
|
|
136
|
+
* for sibling files that would otherwise be parsed as bare module names).
|
|
137
|
+
*/
|
|
138
|
+
function buildIndexImportSpecifier(eventConfigFilePath, srcDir) {
|
|
139
|
+
const eventsIndexDir = path_1.default.join(srcDir, 'events');
|
|
140
|
+
let rel = path_1.default
|
|
141
|
+
.relative(eventsIndexDir, eventConfigFilePath)
|
|
142
|
+
.split(path_1.default.sep)
|
|
143
|
+
.join('/');
|
|
144
|
+
if (rel.endsWith('.ts'))
|
|
145
|
+
rel = rel.slice(0, -'.ts'.length);
|
|
146
|
+
if (rel.endsWith('/index'))
|
|
147
|
+
rel = rel.slice(0, -'/index'.length);
|
|
148
|
+
if (!rel.startsWith('.'))
|
|
149
|
+
rel = './' + rel;
|
|
150
|
+
return rel;
|
|
151
|
+
}
|
|
152
|
+
// ─── events/index.ts generation ──────────────────────────────────────────────
|
|
153
|
+
function buildEventsIndexSource(exports, srcDir) {
|
|
154
|
+
const imports = exports
|
|
155
|
+
.map((e) => `import { ${e.name} } from '${buildIndexImportSpecifier(e.filePath, srcDir)}'`)
|
|
156
|
+
.join('\n');
|
|
157
|
+
const array = `export const ${EVENT_CONFIGS_IDENTIFIER} = [${exports
|
|
158
|
+
.map((e) => e.name)
|
|
159
|
+
.join(', ')}]`;
|
|
160
|
+
return `${LICENSE_HEADER}${imports}\n\n${array}\n`;
|
|
161
|
+
}
|
|
162
|
+
// ─── Handler discovery & rewrite ─────────────────────────────────────────────
|
|
163
|
+
/**
|
|
164
|
+
* Returns the first source file under `srcDir` whose top-level declarations
|
|
165
|
+
* include a function (either `function foo()` or `const foo = () => {}`) whose
|
|
166
|
+
* name is in `HANDLER_FUNCTION_NAMES`.
|
|
167
|
+
*/
|
|
168
|
+
function findHandlerSourceFile(project, srcDir) {
|
|
169
|
+
for (const sf of project.getSourceFiles()) {
|
|
170
|
+
const fp = sf.getFilePath();
|
|
171
|
+
if (!fp.startsWith(srcDir) || fp.includes('/node_modules/'))
|
|
172
|
+
continue;
|
|
173
|
+
for (const fn of sf.getFunctions()) {
|
|
174
|
+
const name = fn.getName();
|
|
175
|
+
if (name && HANDLER_FUNCTION_NAMES.has(name))
|
|
176
|
+
return sf;
|
|
177
|
+
}
|
|
178
|
+
for (const statement of sf.getVariableStatements()) {
|
|
179
|
+
for (const decl of statement.getDeclarations()) {
|
|
180
|
+
if (HANDLER_FUNCTION_NAMES.has(decl.getName()))
|
|
181
|
+
return sf;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Mutates the handler source file:
|
|
189
|
+
* 1. Removes named imports matching `exportNames` from existing imports
|
|
190
|
+
* and drops any import declaration that's left empty.
|
|
191
|
+
* 2. Removes a stale top-level `export const eventConfigs = ...` if present.
|
|
192
|
+
* 3. Ensures `import { eventConfigs } from '@countryconfig/events'` exists
|
|
193
|
+
* (merging into an existing import of the same module when possible).
|
|
194
|
+
* 4. Replaces every `h.response([<identifiers>])` argument with
|
|
195
|
+
* `eventConfigs`.
|
|
196
|
+
*
|
|
197
|
+
* Returns a log of the changes that were actually applied.
|
|
198
|
+
*/
|
|
199
|
+
function modifyHandler(sourceFile, exportNames) {
|
|
200
|
+
const changes = [];
|
|
201
|
+
// 1. Drop direct imports of event configs. Iterate over a snapshot because
|
|
202
|
+
// `importDecl.remove()` may mutate the declaration list.
|
|
203
|
+
for (const importDecl of [...sourceFile.getImportDeclarations()]) {
|
|
204
|
+
const namedImports = importDecl.getNamedImports();
|
|
205
|
+
if (namedImports.length === 0)
|
|
206
|
+
continue;
|
|
207
|
+
const matched = namedImports.filter((ni) => exportNames.has(ni.getName()));
|
|
208
|
+
if (matched.length === 0)
|
|
209
|
+
continue;
|
|
210
|
+
const removedNames = matched.map((ni) => ni.getName());
|
|
211
|
+
for (const ni of matched)
|
|
212
|
+
ni.remove();
|
|
213
|
+
changes.push(`removed direct imports: ${removedNames.join(', ')}`);
|
|
214
|
+
const stillUsed = importDecl.getNamedImports().length > 0 ||
|
|
215
|
+
importDecl.getDefaultImport() ||
|
|
216
|
+
importDecl.getNamespaceImport();
|
|
217
|
+
if (!stillUsed)
|
|
218
|
+
importDecl.remove();
|
|
219
|
+
}
|
|
220
|
+
// 2. Remove an inline top-level `export const eventConfigs = ...` if present.
|
|
221
|
+
// This cleans up after any earlier in-place hoisting done by a previous
|
|
222
|
+
// version of this migration.
|
|
223
|
+
for (const statement of [...sourceFile.getVariableStatements()]) {
|
|
224
|
+
if (!statement.hasExportKeyword())
|
|
225
|
+
continue;
|
|
226
|
+
const hasEventConfigs = statement
|
|
227
|
+
.getDeclarations()
|
|
228
|
+
.some((d) => d.getName() === EVENT_CONFIGS_IDENTIFIER);
|
|
229
|
+
if (hasEventConfigs) {
|
|
230
|
+
statement.remove();
|
|
231
|
+
changes.push(`removed inline 'export const ${EVENT_CONFIGS_IDENTIFIER}'`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
// 3. Ensure `import { eventConfigs } from '@countryconfig/events'`.
|
|
235
|
+
const existing = sourceFile.getImportDeclaration((imp) => imp.getModuleSpecifierValue() === EVENTS_INDEX_IMPORT_PATH);
|
|
236
|
+
if (existing) {
|
|
237
|
+
const already = existing
|
|
238
|
+
.getNamedImports()
|
|
239
|
+
.some((ni) => ni.getName() === EVENT_CONFIGS_IDENTIFIER);
|
|
240
|
+
if (!already) {
|
|
241
|
+
existing.addNamedImport(EVENT_CONFIGS_IDENTIFIER);
|
|
242
|
+
changes.push(`added '${EVENT_CONFIGS_IDENTIFIER}' to existing import from '${EVENTS_INDEX_IMPORT_PATH}'`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
sourceFile.addImportDeclaration({
|
|
247
|
+
moduleSpecifier: EVENTS_INDEX_IMPORT_PATH,
|
|
248
|
+
namedImports: [EVENT_CONFIGS_IDENTIFIER]
|
|
249
|
+
});
|
|
250
|
+
changes.push(`added import { ${EVENT_CONFIGS_IDENTIFIER} } from '${EVENTS_INDEX_IMPORT_PATH}'`);
|
|
251
|
+
}
|
|
252
|
+
// 4. Replace inline `h.response([<identifiers>])` with `h.response(eventConfigs)`.
|
|
253
|
+
for (const call of sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.CallExpression)) {
|
|
254
|
+
const callee = call.getExpression();
|
|
255
|
+
if (!ts_morph_1.Node.isPropertyAccessExpression(callee))
|
|
256
|
+
continue;
|
|
257
|
+
if (callee.getName() !== RESPONSE_METHOD_NAME)
|
|
258
|
+
continue;
|
|
259
|
+
const args = call.getArguments();
|
|
260
|
+
if (args.length !== 1)
|
|
261
|
+
continue;
|
|
262
|
+
const [arg] = args;
|
|
263
|
+
if (!ts_morph_1.Node.isArrayLiteralExpression(arg))
|
|
264
|
+
continue;
|
|
265
|
+
if (arg.getElements().length === 0)
|
|
266
|
+
continue;
|
|
267
|
+
if (!arg.getElements().every((el) => ts_morph_1.Node.isIdentifier(el)))
|
|
268
|
+
continue;
|
|
269
|
+
arg.replaceWithText(EVENT_CONFIGS_IDENTIFIER);
|
|
270
|
+
changes.push(`rewrote h.response([...]) → h.response(${EVENT_CONFIGS_IDENTIFIER})`);
|
|
271
|
+
}
|
|
272
|
+
return changes;
|
|
273
|
+
}
|
|
274
|
+
// ─── Entry point ─────────────────────────────────────────────────────────────
|
|
275
|
+
function main() {
|
|
276
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
277
|
+
const cwd = (0, _1.getCwd)();
|
|
278
|
+
const srcDir = path_1.default.join(cwd, 'src');
|
|
279
|
+
console.log(`Scanning for defineConfig event exports in: ${srcDir}\n`);
|
|
280
|
+
const project = new ts_morph_1.Project({
|
|
281
|
+
tsConfigFilePath: path_1.default.resolve(srcDir, '../tsconfig.json'),
|
|
282
|
+
skipAddingFilesFromTsConfig: false
|
|
283
|
+
});
|
|
284
|
+
const eventConfigExports = findEventConfigExports(project, srcDir);
|
|
285
|
+
if (eventConfigExports.length === 0) {
|
|
286
|
+
console.log('No top-level `export const X = defineConfig(...)` declarations found. Nothing to do.');
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
console.log(`Found ${eventConfigExports.length} event config export(s):`);
|
|
290
|
+
for (const e of eventConfigExports) {
|
|
291
|
+
console.log(` ${e.name} ← ${path_1.default.relative(cwd, e.filePath)}`);
|
|
292
|
+
}
|
|
293
|
+
// ── Create (or skip) src/events/index.ts ───────────────────────────────────
|
|
294
|
+
const eventsIndexAbs = path_1.default.join(srcDir, 'events', 'index.ts');
|
|
295
|
+
const eventsIndexRel = path_1.default.relative(cwd, eventsIndexAbs);
|
|
296
|
+
if (fs_1.default.existsSync(eventsIndexAbs)) {
|
|
297
|
+
console.log(`\n[${eventsIndexRel}] already exists — leaving untouched.`);
|
|
298
|
+
}
|
|
299
|
+
else {
|
|
300
|
+
fs_1.default.mkdirSync(path_1.default.dirname(eventsIndexAbs), { recursive: true });
|
|
301
|
+
const source = buildEventsIndexSource(eventConfigExports, srcDir);
|
|
302
|
+
const eventsIndexFile = project.createSourceFile(eventsIndexAbs, source, {
|
|
303
|
+
overwrite: false
|
|
304
|
+
});
|
|
305
|
+
yield eventsIndexFile.save();
|
|
306
|
+
console.log(`\n[${eventsIndexRel}] created with ${EVENT_CONFIGS_IDENTIFIER} of ${eventConfigExports.length} event(s).`);
|
|
307
|
+
}
|
|
308
|
+
// ── Rewire handler file ────────────────────────────────────────────────────
|
|
309
|
+
const handler = findHandlerSourceFile(project, srcDir);
|
|
310
|
+
if (!handler) {
|
|
311
|
+
console.log(`\nNo event-config handler file found (looked for exported function(s): ${Array.from(HANDLER_FUNCTION_NAMES).join(', ')}). Skipping handler rewrite.`);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
const handlerRelPath = path_1.default.relative(cwd, handler.getFilePath());
|
|
315
|
+
const exportNameSet = new Set(eventConfigExports.map((e) => e.name));
|
|
316
|
+
const changes = modifyHandler(handler, exportNameSet);
|
|
317
|
+
if (changes.length === 0) {
|
|
318
|
+
console.log(`\n[${handlerRelPath}] already wired to ${EVENTS_INDEX_IMPORT_PATH} — no changes.`);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
for (const c of changes)
|
|
322
|
+
console.log(` [${handlerRelPath}] ${c}`);
|
|
323
|
+
yield handler.save();
|
|
324
|
+
console.log(`\nSaved ${handlerRelPath}.`);
|
|
325
|
+
});
|
|
326
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.0/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.0/index.ts"],"names":[],"mappings":"AA+BA,wBAAgB,MAAM,WAMrB;AAED;;;GAGG;AACH,wBAAsB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,iBA8BxD"}
|