-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathjson-schema-processor.js
277 lines (245 loc) · 7.83 KB
/
json-schema-processor.js
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// Copyright (c) 2023 S44, LLC
// Copyright Contributors to the CitrineOS Project
//
// SPDX-License-Identifier: Apache 2.0
/* eslint-disable */
const fs = require('fs');
const jsts = require('json-schema-to-typescript');
const prettier = require('prettier');
const { exec } = require('child_process');
if (process.argv.length === 2) {
console.error('Expected input path argument!');
process.exit(1);
}
const path = process.argv[2];
const globalEnums = new Set();
const globalDefinitions = {};
const globalEnumDefinitions = {};
const licenseComment = `// Copyright 2023 S44, LLC
// Copyright Contributors to the CitrineOS Project
//
// SPDX-License-Identifier: Apache 2.0
`;
fs.readdir(path, (error, files) => {
const writeToFile = true;
const promises = files.map((file) => {
let data = fs.readFileSync(`${path}/${file}`);
return processJsonSchema(data, writeToFile);
});
Promise.all(promises).then((values) => {
values.forEach(({ definitions, enumDefinitions, enums }) => {
Object.assign(globalDefinitions, definitions);
if (enumDefinitions.length > 0) {
enumDefinitions.forEach((entry) => {
globalEnums.add(entry);
});
}
if (enums.length > 0) {
enums.forEach((entry) => {
let { enumName, enumDocumentation, enumDefinition } =
splitEnum(entry);
if (enumName == 'DataEnumType') {
// Adding missing type for DataEnumType... type in OCPP 2.0.1 appendix but not in part 3 JSON schemas
let lastLineIndex = enumDefinition.lastIndexOf(`'`);
enumDefinition =
enumDefinition.substring(0, lastLineIndex) +
`',\n passwordString = 'passwordString` +
enumDefinition.substring(lastLineIndex);
}
globalEnumDefinitions[enumName] = enumDefinition;
});
}
});
const exportStatements = [];
const exportMap = {};
// Export all enum types
exportStatements.push(`export * from './enums';`);
// Prepare all definitions for export
for (let key in globalDefinitions) {
var definitionSource = globalDefinitions[key];
if (!exportMap[definitionSource]) {
exportMap[definitionSource] = [key];
} else {
exportMap[definitionSource].push(key);
}
}
// Export all definitions and schemas
for (let key in exportMap) {
exportStatements.push(
`export { ${exportMap[key].join(', ')} } from './types/${key}';`,
);
exportStatements.push(
`export { default as ${key}Schema } from './schemas/${key}.json';`,
);
}
if (writeToFile) {
fs.writeFileSync(
`./src/ocpp/model/enums/index.ts`,
licenseComment +
Object.values(globalEnumDefinitions).sort().join('\n\n') +
'\n',
);
fs.writeFileSync(
`./src/ocpp/model/index.ts`,
licenseComment + exportStatements.join('\n') + '\n',
);
exec(`cd .. && npm run lint-fix`, (error, stdout, stderr) => {
if (error) {
console.error(`Error executing npm script: ${error.message}`);
return;
}
if (stderr) {
console.error(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
}
});
});
async function processJsonSchema(data, writeToFile = true) {
let jsonSchema = JSON.parse(data);
let id = jsonSchema['$id'].split(':').pop();
jsonSchema['$id'] = id;
delete jsonSchema['$schema'];
// Preprocess nodes to enable enum extraction
processNode(jsonSchema);
// Determine if the schema is a request or response
let schemaType = '';
if (id.toLowerCase().includes('request')) {
schemaType = 'OcppRequest';
} else if (id.toLowerCase().includes('response')) {
schemaType = 'OcppResponse';
}
return new Promise((resolve, reject) => {
jsts
.compile(jsonSchema, id, {
style: { singleQuote: true, trailingComma: 'all' },
format: true,
})
.then((ts) => {
// Add licence comment
ts = licenseComment + ts;
// Extend the generated interface with Request or Response
if (schemaType) {
const interfaceNamePattern = new RegExp(
`export interface ${id}`,
'g',
);
ts = ts.replace(
interfaceNamePattern,
`export interface ${id} extends ${schemaType}`,
);
}
// Extract enums
const enums = extractEnums(ts);
if (enums) {
for (let i = 0; i < enums.length; i++) {
const entry = enums[i];
ts = ts.replace(entry, '');
enums[i] = entry.trimEnd();
}
}
// Collect all definitions
const { definitions, enumDefinitions } = collectDefinitions(
jsonSchema,
id,
);
// Add import statement for enums & schemaType
const searchString = '\nexport';
const index = ts.indexOf(searchString);
ts =
ts.substring(0, index) +
(enumDefinitions.length > 0
? `\nimport { ${enumDefinitions.join(', ')} } from '../enums';\n`
: '\n') +
`import { ${schemaType} } from '../../..';\n` +
ts.substring(index);
if (writeToFile) {
fs.writeFileSync(
`./src/ocpp/model/types/${id}.ts`,
ts.replace(/\n+$/, '\n'),
);
// Format JSON with Prettier
prettier
.format(JSON.stringify(jsonSchema, null, 2), { parser: 'json' })
.then((formattedJson) => {
fs.writeFileSync(
`./src/ocpp/model/schemas/${id}.json`,
formattedJson,
);
});
}
resolve({
definitions,
enumDefinitions,
enums: enums == null ? [] : enums,
});
});
});
}
function mapFromId(id) {
const map = {};
const idKey = `${id}`;
map[idKey] = id;
return map;
}
function collectDefinitions(jsonSchema, id) {
const definitions = mapFromId(id);
const enumDefinitions = [];
for (const key in jsonSchema['definitions']) {
if (!key.includes('EnumType')) {
definitions[key] = id;
} else {
enumDefinitions.push(key);
}
}
return { definitions, enumDefinitions };
}
function processNode(node) {
if (node['enum']) {
node['tsEnumNames'] = [...node['enum']];
node['tsEnumNames'] = node['tsEnumNames'].map((name) => {
return name.replaceAll('.', '_').replaceAll('-', '_');
});
} else {
for (let key in node) {
if (typeof node[key] === 'object') {
processNode(node[key]);
}
}
}
}
function extractEnums(ts) {
const pattern =
/^\/\*\*\s*\n([^\*]|(\*(?!\/)))*\*\/\nexport const enum (\w)* {(\s|\w|-|\.|=|'|,)*}\n*/gm;
const undocumentedPattern =
/^export const enum (\w)* {(\s|\w|-|\.|=|'|,)*}\n*/gm;
const matches = ts.match(pattern);
let undocumentedMatches = ts.match(undocumentedPattern);
if (matches && undocumentedMatches) {
const namePattern = /export const enum (\w)*/g;
matches.forEach((match) => {
const enumName = match
.match(namePattern)[0]
.replace('export const enum ', '');
undocumentedMatches = undocumentedMatches.filter(
(undocumentedMatch) => !undocumentedMatch.includes(enumName),
);
});
}
return [
...(matches ? matches : []),
...(undocumentedMatches ? undocumentedMatches : []),
];
}
function splitEnum(enumDefinition) {
const commentPattern = /^\/\*\*\s*\n([^\*]|(\*(?!\/)))*\*\/\n/gm;
const namePattern = /export const enum (\w)*/g;
const enumName = enumDefinition
.match(namePattern)[0]
.replace('export const enum ', '');
let enumDocumentation = enumDefinition.match(commentPattern);
enumDocumentation = enumDocumentation ? enumDocumentation[0] : '';
return { enumName, enumDocumentation, enumDefinition };
}