-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextensions.ts
More file actions
249 lines (214 loc) · 11.1 KB
/
extensions.ts
File metadata and controls
249 lines (214 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import path, { join, resolve } from 'path';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { cloneDeep } from 'lodash';
import { ContentTypeStruct, CtConstructorParam, ModuleConstructorParam, Extension } from '../types';
import { sanitizePath, cliux, log } from '@contentstack/cli-utilities';
import auditConfig from '../config';
import { $t, auditMsg, commonMsg } from '../messages';
import { values } from 'lodash';
import BaseClass from './base-class';
export default class Extensions extends BaseClass {
protected fix: boolean;
public fileName: any;
public folderPath: string;
public extensionsSchema: Extension[];
public ctSchema: ContentTypeStruct[];
public moduleName: keyof typeof auditConfig.moduleConfig;
public ctUidSet: Set<string>;
public missingCtInExtensions: Extension[];
public missingCts: Set<string>;
public extensionsPath: string;
constructor({
fix,
config,
moduleName,
ctSchema,
}: ModuleConstructorParam & Pick<CtConstructorParam, 'ctSchema'>) {
super({ config });
this.fix = fix ?? false;
this.ctSchema = ctSchema;
this.extensionsSchema = [];
log.debug(`Initializing Extensions module`, this.config.auditContext);
log.debug(`Fix mode: ${this.fix}`, this.config.auditContext);
log.debug(`Content types count: ${ctSchema.length}`, this.config.auditContext);
log.debug(`Module name: ${moduleName}`, this.config.auditContext);
this.moduleName = this.validateModules(moduleName!, this.config.moduleConfig);
this.fileName = config.moduleConfig[this.moduleName].fileName;
log.debug(`File name: ${this.fileName}`, this.config.auditContext);
this.folderPath = resolve(
sanitizePath(config.basePath),
sanitizePath(config.moduleConfig[this.moduleName].dirName),
);
log.debug(`Folder path: ${this.folderPath}`, this.config.auditContext);
this.ctUidSet = new Set(['$all']);
this.missingCtInExtensions = [];
this.missingCts = new Set();
this.extensionsPath = '';
log.debug(`Extensions module initialization completed`, this.config.auditContext);
}
validateModules(
moduleName: keyof typeof auditConfig.moduleConfig,
moduleConfig: Record<string, unknown>,
): keyof typeof auditConfig.moduleConfig {
log.debug(`Validating module: ${moduleName}`, this.config.auditContext);
log.debug(`Available modules: ${Object.keys(moduleConfig).join(', ')}`, this.config.auditContext);
if (Object.keys(moduleConfig).includes(moduleName)) {
log.debug(`Module ${moduleName} is valid`, this.config.auditContext);
return moduleName;
}
log.debug(`Module ${moduleName} not found, defaulting to 'extensions'`, this.config.auditContext);
return 'extensions';
}
async run(totalCount?: number) {
try {
log.debug(`Starting ${this.moduleName} audit process`, this.config.auditContext);
log.debug(`Extensions folder path: ${this.folderPath}`, this.config.auditContext);
log.debug(`Fix mode: ${this.fix}`, this.config.auditContext);
if (!existsSync(this.folderPath)) {
log.debug(`Skipping ${this.moduleName} audit - path does not exist`, this.config.auditContext);
log.warn(`Skipping ${this.moduleName} audit`, this.config.auditContext);
cliux.print($t(auditMsg.NOT_VALID_PATH, { path: this.folderPath }), { color: 'yellow' });
return {};
}
this.extensionsPath = path.join(this.folderPath, this.fileName);
log.debug(`Extensions file path: ${this.extensionsPath}`, this.config.auditContext);
// Load extensions schema with loading spinner
await this.withLoadingSpinner('EXTENSIONS: Loading extensions schema...', async () => {
this.extensionsSchema = existsSync(this.extensionsPath)
? values(JSON.parse(readFileSync(this.extensionsPath, 'utf-8')) as Extension[])
: [];
});
log.debug(`Loaded ${this.extensionsSchema.length} extensions`, this.config.auditContext);
log.debug(`Building content type UID set from ${this.ctSchema.length} content types`, this.config.auditContext);
this.ctSchema.map((ct) => this.ctUidSet.add(ct.uid));
log.debug(`Content type UID set contains: ${Array.from(this.ctUidSet).join(', ')}`, this.config.auditContext);
// Create progress manager if we have a total count
if (totalCount && totalCount > 0) {
const progress = this.createSimpleProgress(this.moduleName, totalCount);
progress.updateStatus('Validating extensions...');
}
log.debug(`Processing ${this.extensionsSchema.length} extensions`, this.config.auditContext);
for (const ext of this.extensionsSchema) {
const { title, uid, scope } = ext;
log.debug(`Processing extension: ${title} (${uid})`, this.config.auditContext);
log.debug(`Extension scope content types: ${scope?.content_types?.join(', ') || 'none'}`, this.config.auditContext);
const ctNotPresent = scope?.content_types.filter((ct) => !this.ctUidSet.has(ct));
log.debug(`Missing content types in extension: ${ctNotPresent?.join(', ') || 'none'}`, this.config.auditContext);
if (ctNotPresent?.length && ext.scope) {
log.debug(`Extension ${title} has ${ctNotPresent.length} missing content types`, this.config.auditContext);
ext.content_types = ctNotPresent;
ctNotPresent.forEach((ct) => {
log.debug(`Adding missing content type: ${ct} to the Audit report.`, this.config.auditContext);
this.missingCts?.add(ct);
});
this.missingCtInExtensions?.push(cloneDeep(ext));
} else {
log.debug(`Extension ${title} has no missing content types`, this.config.auditContext);
}
log.info(
$t(auditMsg.SCAN_EXT_SUCCESS_MSG, {
title,
module: this.config.moduleConfig[this.moduleName].name,
uid,
}),
this.config.auditContext
);
// Track progress for each extension processed
if (this.progressManager) {
this.progressManager.tick(true, `extension: ${title}`, null);
}
}
log.debug(`Extensions audit completed. Found ${this.missingCtInExtensions.length} extensions with missing content types`, this.config.auditContext);
log.debug(`Total missing content types: ${this.missingCts.size}`, this.config.auditContext);
if (this.fix && this.missingCtInExtensions.length) {
log.debug(`Fix mode enabled, fixing ${this.missingCtInExtensions.length} extensions`, this.config.auditContext);
await this.fixExtensionsScope(cloneDeep(this.missingCtInExtensions));
this.missingCtInExtensions.forEach((ext) => {
log.debug(`Marking extension ${ext.title} as fixed`, this.config.auditContext);
ext.fixStatus = 'Fixed';
});
log.debug(`Extensions fix completed`, this.config.auditContext);
this.completeProgress(true);
return this.missingCtInExtensions;
}
log.debug(`Extensions audit completed without fixes`, this.config.auditContext);
this.completeProgress(true);
return this.missingCtInExtensions;
} catch (error: any) {
this.completeProgress(false, error?.message || 'Extensions audit failed');
throw error;
}
}
async fixExtensionsScope(missingCtInExtensions: Extension[]) {
log.debug(`Starting extensions scope fix for ${missingCtInExtensions.length} extensions`, this.config.auditContext);
log.debug(`Loading current extensions schema from: ${this.extensionsPath}`, this.config.auditContext);
let newExtensionSchema: Record<string, Extension> = existsSync(this.extensionsPath)
? JSON.parse(readFileSync(this.extensionsPath, 'utf8'))
: {};
log.debug(`Loaded ${Object.keys(newExtensionSchema).length} existing extensions`, this.config.auditContext);
let userConfirm: boolean;
if (
this.config.flags['copy-dir'] ||
this.config.flags['external-config']?.skipConfirm ||
this.config.flags.yes
) {
userConfirm = true;
} else {
this.completeProgress(true);
userConfirm = await cliux.confirm(commonMsg.FIX_CONFIRMATION);
}
for (const ext of missingCtInExtensions) {
const { uid, title } = ext;
log.debug(`Fixing extension: ${title} (${uid})`, this.config.auditContext);
log.debug(`Extension scope content types: ${ext?.scope?.content_types?.join(', ') || 'none'}`, this.config.auditContext);
const fixedCts = ext?.scope?.content_types.filter((ct) => !this.missingCts.has(ct));
log.debug(`Valid content types after filtering: ${fixedCts?.join(', ') || 'none'}`, this.config.auditContext);
if (fixedCts?.length && newExtensionSchema[uid]?.scope) {
log.debug(`Updating extension ${title} scope with ${fixedCts.length} valid content types`, this.config.auditContext);
newExtensionSchema[uid].scope.content_types = fixedCts;
} else {
log.debug(`Extension ${title} has no valid content types or scope not found`, this.config.auditContext);
cliux.print($t(commonMsg.EXTENSION_FIX_WARN, { title: title, uid }), { color: 'yellow' });
if (userConfirm) {
log.debug(`Deleting extension: ${title} (${uid})`, this.config.auditContext);
delete newExtensionSchema[uid];
} else {
log.debug(`Keeping extension: ${title} (${uid})`, this.config.auditContext);
}
}
}
log.debug(`Extensions scope fix completed, writing updated schema`, this.config.auditContext);
await this.writeFixContent(newExtensionSchema, userConfirm);
}
async writeFixContent(fixedExtensions: Record<string, Extension>, preConfirmed?: boolean) {
log.debug(`Writing fix content for ${Object.keys(fixedExtensions).length} extensions`, this.config.auditContext);
log.debug(`Fix mode: ${this.fix}`, this.config.auditContext);
log.debug(`Copy directory flag: ${this.config.flags['copy-dir']}`, this.config.auditContext);
log.debug(`External config skip confirm: ${this.config.flags['external-config']?.skipConfirm}`, this.config.auditContext);
log.debug(`Yes flag: ${this.config.flags.yes}`, this.config.auditContext);
let shouldWrite: boolean;
if (!this.fix) {
shouldWrite = false;
} else if (preConfirmed !== undefined) {
shouldWrite = preConfirmed;
} else if (
this.config.flags['copy-dir'] ||
this.config.flags['external-config']?.skipConfirm ||
this.config.flags.yes
) {
shouldWrite = true;
} else {
this.completeProgress(true);
shouldWrite = await cliux.confirm(commonMsg.FIX_CONFIRMATION);
}
if (shouldWrite) {
const outputPath = join(this.folderPath, this.config.moduleConfig[this.moduleName].fileName);
log.debug(`Writing fixed extensions to: ${outputPath}`, this.config.auditContext);
log.debug(`Extensions to write: ${Object.keys(fixedExtensions).join(', ')}`, this.config.auditContext);
writeFileSync(outputPath, JSON.stringify(fixedExtensions));
log.debug(`Successfully wrote fixed extensions to file`, this.config.auditContext);
} else {
log.debug(`Skipping file write - fix mode disabled or user declined confirmation`, this.config.auditContext);
}
}
}