-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgenerator.ts
211 lines (171 loc) · 5.76 KB
/
generator.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import * as fs from 'node:fs';
import * as Path from 'node:path';
import { type LoaderOptions, SchemaLoader } from './loader';
import type { ClassField } from './typeschema';
/**
* Options interface for Generator class.
* Defines common configuration options for all generators.
*/
export interface GeneratorOptions {
/** Path to the output directory where generated files will be saved */
outputDir: string;
/** Array of TypeSchema source files */
files?: string[];
/** Optional path to directory containing static files to be copied */
staticDir?: string;
/** Map of FHIR primitive types to target language types */
typeMap?: Record<string, string>;
/** Set of reserved keywords in the target language */
keywords?: Set<string>;
loaderOptions?: LoaderOptions;
tabSize?: number;
}
export class Generator {
private fileDescriptor: number | null = null;
private currentDir: string | null = null;
private opts: GeneratorOptions;
filePath?: string;
identLevel = 0;
loader: SchemaLoader;
constructor(opts: GeneratorOptions) {
this.opts = opts;
this.currentDir = opts.outputDir || null;
this.loader = new SchemaLoader({ ...opts.loaderOptions, ...opts });
}
clear() {
if (this.opts.outputDir) {
return fs.rmSync(this.opts.outputDir, { recursive: true, force: true });
}
}
readFile(path: string): string {
return fs.readFileSync(Path.join(this.opts.outputDir || '', path), 'utf-8');
}
async init() {
await this.loader.load();
}
generate() {
throw Error('Implement this method in target generator type');
}
dir(path: string, gencontent: () => void) {
this.currentDir = Path.join(this.opts.outputDir || '', path);
if (!fs.existsSync(this.currentDir)) {
fs.mkdirSync(this.currentDir, { recursive: true });
}
gencontent();
}
file(path: string, gencontent: () => void) {
this.filePath = Path.join(this.currentDir || '', path);
if (!fs.existsSync(Path.dirname(this.filePath))) {
fs.mkdirSync(Path.dirname(this.filePath), { recursive: true });
}
// console.log('file', this.filePath);
this.fileDescriptor = fs.openSync(this.filePath, 'w');
gencontent();
fs.closeSync(this.fileDescriptor);
}
jsonFile(path: string, content: any) {
this.file(path, () => {
this.write(JSON.stringify(content, null, 2));
});
}
ensureCurrentFile() {
if (!this.fileDescriptor) {
throw new Error('No current file');
}
}
write(str: string) {
this.ensureCurrentFile();
fs.writeSync(this.fileDescriptor as number, str);
}
writeIdent() {
this.write(' '.repeat(this.identLevel * (this.opts.tabSize ?? 4)));
}
line(...tokens: string[]) {
this.writeIdent();
this.write(`${tokens.join(' ')}\n`);
}
lineSM(...tokens: string[]) {
this.writeIdent();
this.write(`${tokens.join(' ')};\n`);
}
curlyBlock(tokens: Array<string | undefined>, gencontent: () => void) {
this.write(tokens.filter(Boolean).join(' '));
this.write(' {\n');
this.ident();
gencontent();
this.deident();
this.write('}\n');
}
squareBlock(tokens: string[], gencontent: () => void) {
this.line(`${tokens.join(' ')}[`);
this.ident();
gencontent();
this.deident();
this.line(']');
}
curlBrackets(gencontent: () => void) {
this.write('{');
gencontent();
this.write('}');
}
ident() {
this.identLevel++;
}
deident() {
this.identLevel--;
}
token(...tokens: string[]) {}
getFieldName(name: string) {
// const keywords = this.opts.keywords ?? new Set();
// if (keywords.has(name)) {
// return name + '_';
// }
return name;
}
getFieldType(field: ClassField): string {
if (field.enum) {
return field.enum.map((e) => `'${e}'`).join(' | ');
}
if (field.type.kind === 'nested') {
return this.deriveNestedSchemaName(field.type.url);
}
if (field.type.kind === 'primitive-type') {
const typeMap = this.opts.typeMap ?? {};
return typeMap[field.type.name] ?? 'string';
}
if (field.reference?.length) {
const references = field.reference.map((ref) => `'${ref.name}'`).join(' | ');
return `Reference<${references}>`;
}
return this.uppercaseFirstLetter(field.type.name);
}
copyStaticFiles() {
if (!this.opts.staticDir) {
throw new Error('staticDir must be set in subclass.');
}
fs.cpSync(Path.resolve(this.opts.staticDir), this.opts.outputDir, { recursive: true });
}
canonicalToName(canonical: string | undefined) {
if (!canonical) return undefined;
return canonical.split('/').pop();
}
uppercaseFirstLetter(str: string): string {
if (!str || str.length === 0) return str;
return str.charAt(0).toUpperCase() + str.slice(1);
}
uppercaseFirstLetterOfEach(strings: string[]): string[] {
return strings.map((str) => this.uppercaseFirstLetter(str));
}
deriveNestedSchemaName(url: string, includeResourceName = false) {
const path = this.canonicalToName(url);
if (path) {
const [resourceName, rest] = path.split('#');
const name = this.uppercaseFirstLetterOfEach(rest.split('.')).join('');
if (includeResourceName) {
return [resourceName, name].join('');
}
return name;
}
return '';
}
}