-
Notifications
You must be signed in to change notification settings - Fork 58
/
converter.js
220 lines (171 loc) · 7.32 KB
/
converter.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
const path = require('path');
const camelcase = require('camelcase');
const flatten = arr => arr.reduce((a, b) => a.concat(b), []);
const arrayRegex = /^(.+)\[\]$/;
const simpleCollectionRegex = /^(?:I?List|IReadOnlyList|IEnumerable|ICollection|IReadOnlyCollection|HashSet)<([\w\d]+)>\??$/;
const collectionRegex = /^(?:I?List|IReadOnlyList|IEnumerable|ICollection|IReadOnlyCollection|HashSet)<(.+)>\??$/;
const simpleDictionaryRegex = /^(?:I?Dictionary|SortedDictionary|IReadOnlyDictionary)<([\w\d]+)\s*,\s*([\w\d]+)>\??$/;
const dictionaryRegex = /^(?:I?Dictionary|SortedDictionary|IReadOnlyDictionary)<([\w\d]+)\s*,\s*(.+)>\??$/;
const defaultTypeTranslations = {
int: 'number',
double: 'number',
float: 'number',
Int32: 'number',
Int64: 'number',
short: 'number',
long: 'number',
decimal: 'number',
bool: 'boolean',
DateTime: 'string',
DateTimeOffset: 'string',
Guid: 'string',
dynamic: 'any',
object: 'any',
};
const createConverter = config => {
const typeTranslations = Object.assign({}, defaultTypeTranslations, config.customTypeTranslations);
const convert = json => {
const content = json.map(file => {
const filename = path.relative(process.cwd(), file.FileName);
const rows = flatten([
...file.Models.map(model => convertModel(model, filename)),
...file.Enums.map(enum_ => convertEnum(enum_, filename)),
]);
return rows
.map(row => config.namespace ? ` ${row}` : row)
.join('\n');
});
const filteredContent = content.filter(x => x.length > 0);
if (config.namespace) {
return [
`declare module ${config.namespace} {`,
...filteredContent,
'}',
].join('\n');
} else {
return filteredContent.join('\n');
}
};
const convertModel = (model, filename) => {
const rows = [];
if (model.BaseClasses) {
model.IndexSignature = model.BaseClasses.find(type => type.match(dictionaryRegex));
model.BaseClasses = model.BaseClasses.filter(type => !type.match(dictionaryRegex));
}
const members = [...(model.Fields || []), ...(model.Properties || [])];
const baseClasses = model.BaseClasses && model.BaseClasses.length ? ` extends ${model.BaseClasses.join(', ')}` : '';
if (!config.omitFilePathComment) {
rows.push(`// ${filename}`);
}
if (model.Obsolete) {
rows.push(formatObsoleteMessage(model.ObsoleteMessage, ''));
}
rows.push(`export interface ${model.ModelName}${baseClasses} {`);
const propertySemicolon = config.omitSemicolon ? '' : ';';
if (model.IndexSignature) {
rows.push(` ${convertIndexType(model.IndexSignature)}${propertySemicolon}`);
}
members.forEach(member => {
if (member.Obsolete) {
rows.push(formatObsoleteMessage(member.ObsoleteMessage, ' '));
}
rows.push(` ${convertProperty(member)}${propertySemicolon}`);
});
rows.push(`}\n`);
return rows;
};
const convertEnum = (enum_, filename) => {
const rows = [];
if (!config.omitFilePathComment) {
rows.push(`// ${filename}`);
}
const entries = Object.entries(enum_.Values);
if (enum_.Obsolete) {
rows.push(formatObsoleteMessage(enum_.ObsoleteMessage, ''));
}
const getEnumStringValue = (value) => config.camelCaseEnums
? camelcase(value)
: value;
const lastValueSemicolon = config.omitSemicolon ? '' : ';';
if (config.stringLiteralTypesInsteadOfEnums) {
rows.push(`export type ${enum_.Identifier} =`);
entries.forEach(([key], i) => {
const delimiter = (i === entries.length - 1) ? lastValueSemicolon : ' |';
rows.push(` '${getEnumStringValue(key)}'${delimiter}`);
});
rows.push('');
} else {
rows.push(`export enum ${enum_.Identifier} {`);
entries.forEach(([key, entry]) => {
if (entry.Obsolete) {
rows.push(formatObsoleteMessage(entry.ObsoleteMessage, ' '));
}
if (config.numericEnums) {
if (entry.Value == null) {
rows.push(` ${key},`);
} else {
rows.push(` ${key} = ${entry.Value},`);
}
} else {
rows.push(` ${key} = '${getEnumStringValue(key)}',`);
}
});
rows.push(`}\n`);
}
return rows;
};
const formatObsoleteMessage = (obsoleteMessage, indentation) => {
if (obsoleteMessage) {
obsoleteMessage = ' ' + obsoleteMessage;
} else {
obsoleteMessage = '';
}
let deprecationMessage = '';
deprecationMessage += `${indentation}/**\n`;
deprecationMessage += `${indentation} * @deprecated${obsoleteMessage}\n`;
deprecationMessage += `${indentation} */`;
return deprecationMessage;
}
const convertProperty = property => {
const optional = property.Type.endsWith('?');
const identifier = convertIdentifier(optional ? `${property.Identifier.split(' ')[0]}?` : property.Identifier.split(' ')[0]);
const type = parseType(property.Type);
return `${identifier}: ${type}`;
};
const convertIndexType = indexType => {
const dictionary = indexType.match(dictionaryRegex);
const simpleDictionary = indexType.match(simpleDictionaryRegex);
propType = simpleDictionary ? dictionary[2] : parseType(dictionary[2]);
return `[key: ${convertType(dictionary[1])}]: ${convertType(propType)}`;
};
const convertRecord = indexType => {
const dictionary = indexType.match(dictionaryRegex);
const simpleDictionary = indexType.match(simpleDictionaryRegex);
propType = simpleDictionary ? dictionary[2] : parseType(dictionary[2]);
return `Record<${convertType(dictionary[1])}, ${convertType(propType)}>`;
};
const parseType = propType => {
const array = propType.match(arrayRegex);
if (array) {
propType = array[1];
}
const collection = propType.match(collectionRegex);
const dictionary = propType.match(dictionaryRegex);
let type;
if (collection) {
const simpleCollection = propType.match(simpleCollectionRegex);
propType = simpleCollection ? collection[1] : parseType(collection[1]);
type = `${convertType(propType)}[]`;
} else if (dictionary) {
type = `${convertRecord(propType)}`;
} else {
const optional = propType.endsWith('?');
type = convertType(optional ? propType.slice(0, propType.length - 1) : propType);
}
return array ? `${type}[]` : type;
};
const convertIdentifier = identifier => config.camelCase ? camelcase(identifier, config.camelCaseOptions) : identifier;
const convertType = type => type in typeTranslations ? typeTranslations[type] : type;
return convert;
};
module.exports = createConverter;