-
Notifications
You must be signed in to change notification settings - Fork 22
/
cf-definitions-builder.ts
195 lines (164 loc) · 5.9 KB
/
cf-definitions-builder.ts
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
import {
forEachStructureChild,
ImportDeclarationStructure,
OptionalKind,
Project,
ScriptTarget,
SourceFile,
StructureKind,
} from 'ts-morph';
import { moduleName } from './module-name';
import { ContentTypeRenderer, DefaultContentTypeRenderer } from './renderer';
import { CFContentType, CFEditorInterface, WriteCallback } from './types';
import { flatten } from 'lodash';
export default class CFDefinitionsBuilder {
private readonly project: Project;
private readonly contentTypeRenderers: ContentTypeRenderer[];
constructor(contentTypeRenderers: ContentTypeRenderer[] = []) {
if (contentTypeRenderers.length === 0) {
contentTypeRenderers.push(new DefaultContentTypeRenderer());
}
this.contentTypeRenderers = contentTypeRenderers;
this.project = new Project({
useInMemoryFileSystem: true,
compilerOptions: {
target: ScriptTarget.ES5,
declaration: true,
},
});
for (const renderer of this.contentTypeRenderers) {
renderer.setup(this.project);
}
}
public appendType = (
model: CFContentType,
editorInterface?: CFEditorInterface,
): CFDefinitionsBuilder => {
if (model.sys.type !== 'ContentType') {
throw new Error('given data is not describing a ContentType');
}
const file = this.addFile(moduleName(model.sys.id));
for (const renderer of this.contentTypeRenderers) {
renderer.render(model, file, editorInterface);
}
file.organizeImports({
ensureNewLineAtEndOfFile: true,
});
return this;
};
public appendTypes = (
models: CFContentType[],
editorInterface?: CFEditorInterface,
): CFDefinitionsBuilder => {
for (const model of models) {
this.appendType(model, editorInterface);
}
return this;
};
public write = async (dir: string, writeCallback: WriteCallback): Promise<void> => {
this.addIndexFile();
if (dir.endsWith('/')) {
dir = dir.slice(0, -1);
}
const writePromises = this.project.getSourceFiles().map((file) => {
const targetPath = `${dir}${file.getFilePath()}`;
file.formatText();
return writeCallback(targetPath, file.getFullText());
});
await Promise.all(writePromises);
this.removeIndexFile();
};
public toString = (): string => {
const mergeFileName = 'ContentTypes';
const mergeFile = this.addFile(mergeFileName);
const imports: OptionalKind<ImportDeclarationStructure>[] = [];
const types: string[] = [];
for (const sourceFile of this.project.getSourceFiles().filter((sourceFile) => {
return sourceFile.getBaseNameWithoutExtension() !== mergeFileName;
}))
forEachStructureChild(sourceFile.getStructure(), (childStructure) => {
switch (childStructure.kind) {
case StructureKind.ImportDeclaration:
imports.push(childStructure);
break;
case StructureKind.Interface:
types.push(childStructure.name);
mergeFile.addInterface(childStructure);
break;
case StructureKind.TypeAlias:
types.push(childStructure.name);
mergeFile.addTypeAlias(childStructure);
break;
case StructureKind.Function:
mergeFile.addFunction(childStructure);
break;
default:
throw new Error(`Unhandled node type '${StructureKind[childStructure.kind]}'.`);
}
});
const additionalFiles = flatten(
this.contentTypeRenderers.map((renderer) => {
return renderer.additionalFiles();
}),
);
const additionalFileNames = new Set(
additionalFiles.map((file) => file.getBaseNameWithoutExtension()),
);
// only import modules not present in merge file and not present in additional files
for (const importD of imports) {
const name = importD.moduleSpecifier.startsWith('./')
? importD.moduleSpecifier.slice(2)
: importD.moduleSpecifier;
// This check relies on the fact that module and file name match
if (!types.includes(name) && !additionalFileNames.has(name)) {
mergeFile.addImportDeclaration(importD);
}
}
mergeFile.organizeImports({
ensureNewLineAtEndOfFile: true,
});
mergeFile.formatText();
const fullText = mergeFile.getFullText();
this.project.removeSourceFile(mergeFile);
return fullText;
};
private addFile = (name: string): SourceFile => {
return this.project.createSourceFile(`${name}.ts`, undefined, {
overwrite: true,
});
};
private getIndexFile = (): SourceFile | undefined => {
return this.project.getSourceFile((file) => {
return file.getBaseNameWithoutExtension() === 'index';
});
};
private addIndexFile = (): void => {
this.removeIndexFile();
const indexFile = this.addFile('index');
// this assumes all things are named exports
// maybe use https://github.com/dsherret/ts-morph/issues/165#issuecomment-350522329
for (const sourceFile of this.project.getSourceFiles()) {
const exportDeclarations = sourceFile.getExportSymbols();
if (sourceFile.getBaseNameWithoutExtension() !== 'index') {
// we have to add every single exported member to differentiate type only exports
// organize imports in the end optimize again and groups imports from same module
for (const exportDeclaration of exportDeclarations) {
indexFile.addExportDeclaration({
isTypeOnly: !sourceFile.getFunctions().some((f) => {
return f.getName() === exportDeclaration.getExportSymbol().getName();
}),
namedExports: [exportDeclaration.getExportSymbol().getEscapedName()],
moduleSpecifier: `./${sourceFile.getBaseNameWithoutExtension()}`,
});
}
}
}
indexFile.organizeImports();
};
private removeIndexFile = () => {
const indexFile = this.getIndexFile();
if (indexFile) {
this.project.removeSourceFile(indexFile);
}
};
}