@opra/cli 1.0.0-alpha.12 → 1.0.0-alpha.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cjs/ts-generator/generators/clean-directory.js +35 -0
- package/cjs/ts-generator/generators/generate-data-type.js +258 -0
- package/cjs/ts-generator/generators/generate-document.js +60 -0
- package/cjs/ts-generator/generators/generate-http-api.js +45 -0
- package/cjs/ts-generator/generators/generate-http-controller.js +224 -0
- package/cjs/ts-generator/ts-generator.js +16 -17
- package/esm/ts-generator/generators/clean-directory.js +30 -0
- package/esm/ts-generator/generators/generate-data-type.js +247 -0
- package/esm/ts-generator/generators/generate-document.js +55 -0
- package/esm/ts-generator/generators/generate-http-api.js +40 -0
- package/esm/ts-generator/generators/generate-http-controller.js +219 -0
- package/esm/ts-generator/ts-generator.js +16 -17
- package/package.json +4 -3
- package/types/ts-generator/generators/clean-directory.d.ts +2 -0
- package/types/ts-generator/generators/generate-data-type.d.ts +41 -0
- package/types/ts-generator/generators/generate-document.d.ts +8 -0
- package/types/ts-generator/generators/generate-http-api.d.ts +3 -0
- package/types/ts-generator/generators/generate-http-controller.d.ts +3 -0
- package/types/ts-generator/ts-generator.d.ts +15 -15
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.cleanDirectory = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const node_fs_1 = tslib_1.__importDefault(require("node:fs"));
|
|
6
|
+
const node_path_1 = tslib_1.__importDefault(require("node:path"));
|
|
7
|
+
const chalk_1 = tslib_1.__importDefault(require("chalk"));
|
|
8
|
+
function cleanDirectory(dirname) {
|
|
9
|
+
const rootDir = dirname;
|
|
10
|
+
const _cleanDirectory = (targetDir) => {
|
|
11
|
+
if (!node_fs_1.default.existsSync(targetDir))
|
|
12
|
+
return;
|
|
13
|
+
const files = node_fs_1.default.readdirSync(targetDir);
|
|
14
|
+
for (const f of files) {
|
|
15
|
+
const absolutePath = node_path_1.default.join(targetDir, f);
|
|
16
|
+
if (node_fs_1.default.statSync(absolutePath).isDirectory()) {
|
|
17
|
+
_cleanDirectory(absolutePath);
|
|
18
|
+
if (!node_fs_1.default.readdirSync(absolutePath).length) {
|
|
19
|
+
this.emit('verbose', chalk_1.default.cyan(`Removing directory ${node_path_1.default.relative(absolutePath, rootDir)}`));
|
|
20
|
+
node_fs_1.default.rmdirSync(absolutePath);
|
|
21
|
+
}
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
if (node_path_1.default.extname(f) === '.ts') {
|
|
25
|
+
const contents = node_fs_1.default.readFileSync(absolutePath, 'utf-8');
|
|
26
|
+
if (contents.includes('#!oprimp_auto_generated!#')) {
|
|
27
|
+
this.emit('verbose', chalk_1.default.cyan(`Removing file ${node_path_1.default.relative(absolutePath, rootDir)}`));
|
|
28
|
+
node_fs_1.default.unlinkSync(absolutePath);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
_cleanDirectory(dirname);
|
|
34
|
+
}
|
|
35
|
+
exports.cleanDirectory = cleanDirectory;
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports._generateMappedTypeCode = exports._generateMixinTypeCode = exports._generateSimpleTypeCode = exports._generateComplexTypeCode = exports._generateEnumTypeCode = exports._generateTypeCode = exports.generateDataType = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const common_1 = require("@opra/common");
|
|
6
|
+
const path_1 = tslib_1.__importDefault(require("path"));
|
|
7
|
+
const code_block_js_1 = require("../../code-block.js");
|
|
8
|
+
const string_utils_js_1 = require("../utils/string-utils.js");
|
|
9
|
+
const internalTypeNames = ['any', 'boolean', 'bigint', 'number', 'null', 'string', 'object'];
|
|
10
|
+
async function generateDataType(dataType, intent, currentFile) {
|
|
11
|
+
const doc = dataType.node.getDocument();
|
|
12
|
+
if (doc.id !== this._document?.id) {
|
|
13
|
+
const { generator } = await this.generateDocument(doc);
|
|
14
|
+
return await generator.generateDataType(dataType, intent, currentFile);
|
|
15
|
+
}
|
|
16
|
+
const typeName = dataType.name;
|
|
17
|
+
if (typeName) {
|
|
18
|
+
if (internalTypeNames.includes(typeName))
|
|
19
|
+
return { kind: 'internal', typeName: dataType.name };
|
|
20
|
+
let file = this._filesMap.get(dataType);
|
|
21
|
+
if (file) {
|
|
22
|
+
if (currentFile)
|
|
23
|
+
currentFile.addImport(file.filename, [typeName]);
|
|
24
|
+
return { kind: 'named', file, typeName: dataType.name };
|
|
25
|
+
}
|
|
26
|
+
if (dataType instanceof common_1.SimpleType)
|
|
27
|
+
file = this.addFile(path_1.default.join(this._documentRoot, '/simple-types.ts'), true);
|
|
28
|
+
else if (dataType instanceof common_1.EnumType)
|
|
29
|
+
file = this.addFile(path_1.default.join(this._typesRoot, 'enums', typeName + '.ts'));
|
|
30
|
+
else
|
|
31
|
+
file = this.addFile(path_1.default.join(this._typesRoot, 'types', typeName + '.ts'));
|
|
32
|
+
this._filesMap.set(dataType, file);
|
|
33
|
+
if (file.exportTypes.includes(typeName)) {
|
|
34
|
+
if (currentFile)
|
|
35
|
+
currentFile.addImport(file.filename, [typeName]);
|
|
36
|
+
return { kind: 'named', file, typeName: dataType.name };
|
|
37
|
+
}
|
|
38
|
+
file.exportTypes.push(typeName);
|
|
39
|
+
const typesIndexTs = this.addFile(path_1.default.join(this._typesRoot, 'index.ts'), true);
|
|
40
|
+
const indexTs = this.addFile('/index.ts', true);
|
|
41
|
+
indexTs.addExport(typesIndexTs.filename);
|
|
42
|
+
const codeBlock = (file.code['type_' + typeName] = new code_block_js_1.CodeBlock());
|
|
43
|
+
codeBlock.head = `/**\n * ${(0, string_utils_js_1.wrapJSDocString)(dataType.description || '')}\n *`;
|
|
44
|
+
codeBlock.head += `
|
|
45
|
+
* @url ${path_1.default.posix.join(doc.url || this.serviceUrl, '$schema', '#types/' + typeName)}
|
|
46
|
+
*/
|
|
47
|
+
export `;
|
|
48
|
+
codeBlock.typeDef = (await this._generateTypeCode(file, dataType, 'root')) + '\n\n';
|
|
49
|
+
typesIndexTs.addExport(file.filename);
|
|
50
|
+
if (currentFile)
|
|
51
|
+
currentFile.addImport(file.filename, [typeName]);
|
|
52
|
+
return { kind: 'named', file, typeName };
|
|
53
|
+
}
|
|
54
|
+
if (!currentFile)
|
|
55
|
+
throw new TypeError(`You must provide currentFile to generate data type`);
|
|
56
|
+
const code = await this._generateTypeCode(currentFile, dataType, intent);
|
|
57
|
+
return { kind: 'embedded', code };
|
|
58
|
+
}
|
|
59
|
+
exports.generateDataType = generateDataType;
|
|
60
|
+
/**
|
|
61
|
+
*
|
|
62
|
+
*/
|
|
63
|
+
async function _generateTypeCode(currentFile, dataType, intent) {
|
|
64
|
+
if (intent === 'root' && !dataType.name) {
|
|
65
|
+
throw new TypeError(`Name required to generate data type code to root intent`);
|
|
66
|
+
}
|
|
67
|
+
if (dataType instanceof common_1.EnumType) {
|
|
68
|
+
return await this._generateEnumTypeCode(currentFile, dataType, intent);
|
|
69
|
+
}
|
|
70
|
+
if (dataType instanceof common_1.ComplexType) {
|
|
71
|
+
return await this._generateComplexTypeCode(currentFile, dataType, intent);
|
|
72
|
+
}
|
|
73
|
+
if (dataType instanceof common_1.SimpleType) {
|
|
74
|
+
return await this._generateSimpleTypeCode(currentFile, dataType, intent);
|
|
75
|
+
}
|
|
76
|
+
if (dataType instanceof common_1.MappedType) {
|
|
77
|
+
return await this._generateMappedTypeCode(currentFile, dataType, intent);
|
|
78
|
+
}
|
|
79
|
+
if (dataType instanceof common_1.MixinType) {
|
|
80
|
+
return await this._generateMixinTypeCode(currentFile, dataType, intent);
|
|
81
|
+
}
|
|
82
|
+
/* istanbul ignore next */
|
|
83
|
+
throw new TypeError(`${dataType.kind} data types can not be directly exported`);
|
|
84
|
+
}
|
|
85
|
+
exports._generateTypeCode = _generateTypeCode;
|
|
86
|
+
/**
|
|
87
|
+
*
|
|
88
|
+
*/
|
|
89
|
+
async function _generateEnumTypeCode(currentFile, dataType, intent) {
|
|
90
|
+
if (intent === 'root') {
|
|
91
|
+
let out = `enum ${dataType.name} {\n\t`;
|
|
92
|
+
for (const [value, info] of Object.entries(dataType.attributes)) {
|
|
93
|
+
// Print JSDoc
|
|
94
|
+
let jsDoc = '';
|
|
95
|
+
if (dataType.attributes[value].description)
|
|
96
|
+
jsDoc += ` * ${dataType.attributes[value].description}\n`;
|
|
97
|
+
if (jsDoc)
|
|
98
|
+
out += `/**\n${jsDoc} */\n`;
|
|
99
|
+
out +=
|
|
100
|
+
`${info.alias || value} = ` +
|
|
101
|
+
(typeof value === 'number' ? value : "'" + String(value).replace("'", "\\'") + "'");
|
|
102
|
+
out += ',\n\n';
|
|
103
|
+
}
|
|
104
|
+
return out + '\b}';
|
|
105
|
+
}
|
|
106
|
+
return ('(' +
|
|
107
|
+
Object.keys(dataType.attributes)
|
|
108
|
+
.map(t => `'${t}'`)
|
|
109
|
+
.join(' | ') +
|
|
110
|
+
')');
|
|
111
|
+
}
|
|
112
|
+
exports._generateEnumTypeCode = _generateEnumTypeCode;
|
|
113
|
+
/**
|
|
114
|
+
*
|
|
115
|
+
*/
|
|
116
|
+
async function _generateComplexTypeCode(currentFile, dataType, intent) {
|
|
117
|
+
let out = intent === 'root' ? `interface ${dataType.name} ` : '';
|
|
118
|
+
const ownFields = [...dataType.fields.values()].filter(f => f.origin === dataType);
|
|
119
|
+
if (dataType.base) {
|
|
120
|
+
const base = await this.generateDataType(dataType.base, 'extends', currentFile);
|
|
121
|
+
let baseDef = base.kind === 'embedded' ? base.code : base.typeName;
|
|
122
|
+
const omitBaseFields = ownFields.filter(f => dataType.base.fields.has(f.name));
|
|
123
|
+
if (omitBaseFields.length)
|
|
124
|
+
baseDef = `Omit<${baseDef}, ${omitBaseFields.map(x => "'" + x.name + "'").join(' | ')}>`;
|
|
125
|
+
if (intent === 'root')
|
|
126
|
+
out += `extends ${baseDef} `;
|
|
127
|
+
else {
|
|
128
|
+
out += baseDef;
|
|
129
|
+
if (!ownFields.length)
|
|
130
|
+
return out;
|
|
131
|
+
out += ' & ';
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
out += '{\n\t';
|
|
135
|
+
let i = 0;
|
|
136
|
+
for (const field of ownFields) {
|
|
137
|
+
if (i++)
|
|
138
|
+
out += '\n';
|
|
139
|
+
// Print JSDoc
|
|
140
|
+
out += `/**\n * ${field.description || ''}\n`;
|
|
141
|
+
if (field.default)
|
|
142
|
+
out += ` * @default ` + field.default + '\n';
|
|
143
|
+
// if (field.format)
|
|
144
|
+
// jsDoc += ` * @format ` + field.format + '\n';
|
|
145
|
+
if (field.exclusive)
|
|
146
|
+
out += ` * @exclusive\n`;
|
|
147
|
+
if (field.readonly)
|
|
148
|
+
out += ` * @readonly\n`;
|
|
149
|
+
if (field.writeonly)
|
|
150
|
+
out += ` * @writeonly\n`;
|
|
151
|
+
if (field.deprecated) {
|
|
152
|
+
out += ` * @deprecated ` + (typeof field.deprecated === 'string' ? field.deprecated : '') + '\n';
|
|
153
|
+
}
|
|
154
|
+
out += ' */\n';
|
|
155
|
+
// Print field name
|
|
156
|
+
if (field.readonly)
|
|
157
|
+
out += 'readonly ';
|
|
158
|
+
out += `${field.name}${field.required ? '' : '?'}: `;
|
|
159
|
+
if (field.fixed) {
|
|
160
|
+
const t = typeof field.fixed;
|
|
161
|
+
out += `${t === 'number' || t === 'boolean' || t === 'bigint' ? field.fixed : "'" + field.fixed + "'"}\n`;
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
const x = await this.generateDataType(field.type, 'typeDef', currentFile);
|
|
165
|
+
out += (x.kind === 'embedded' ? x.code : x.typeName) + `${field.isArray ? '[]' : ''};\n`;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (dataType.additionalFields)
|
|
169
|
+
out += '[key: string]: any;\n';
|
|
170
|
+
return out + '\b}';
|
|
171
|
+
}
|
|
172
|
+
exports._generateComplexTypeCode = _generateComplexTypeCode;
|
|
173
|
+
/**
|
|
174
|
+
*
|
|
175
|
+
*/
|
|
176
|
+
async function _generateSimpleTypeCode(currentFile, dataType, intent) {
|
|
177
|
+
let out = intent === 'root' ? `type ${dataType.name} = ` : '';
|
|
178
|
+
out += dataType.nameMappings.js || 'any';
|
|
179
|
+
return intent === 'root' ? out + ';' : out;
|
|
180
|
+
}
|
|
181
|
+
exports._generateSimpleTypeCode = _generateSimpleTypeCode;
|
|
182
|
+
/**
|
|
183
|
+
*
|
|
184
|
+
*/
|
|
185
|
+
async function _generateMixinTypeCode(currentFile, dataType, intent) {
|
|
186
|
+
const outArray = [];
|
|
187
|
+
for (const t of dataType.types) {
|
|
188
|
+
const x = await this.generateDataType(t, 'typeDef', currentFile);
|
|
189
|
+
if (x.kind === 'embedded') {
|
|
190
|
+
outArray.push(x.code.includes('|') ? '(' + x.code + ')' : x.code);
|
|
191
|
+
}
|
|
192
|
+
else
|
|
193
|
+
outArray.push(x.typeName);
|
|
194
|
+
}
|
|
195
|
+
if (intent === 'root')
|
|
196
|
+
return `type ${dataType.name} = ${outArray.join(' & ')}`;
|
|
197
|
+
if (intent === 'extends')
|
|
198
|
+
return outArray.join(', ');
|
|
199
|
+
return outArray.join(' & ');
|
|
200
|
+
}
|
|
201
|
+
exports._generateMixinTypeCode = _generateMixinTypeCode;
|
|
202
|
+
/**
|
|
203
|
+
*
|
|
204
|
+
*/
|
|
205
|
+
async function _generateMappedTypeCode(currentFile, dataType, intent) {
|
|
206
|
+
let out = intent === 'root' ? `type ${dataType.name} = ` : '';
|
|
207
|
+
const base = await this.generateDataType(dataType.base, 'typeDef', currentFile);
|
|
208
|
+
const typeDef = base.kind === 'embedded' ? base.code : base.typeName;
|
|
209
|
+
const pick = dataType.pick?.length ? dataType.pick : undefined;
|
|
210
|
+
const omit = !pick && dataType.omit?.length ? dataType.omit : undefined;
|
|
211
|
+
const partial = dataType.partial === true || (Array.isArray(dataType.partial) && dataType.partial.length > 0)
|
|
212
|
+
? dataType.partial
|
|
213
|
+
: undefined;
|
|
214
|
+
const required = dataType.required === true || (Array.isArray(dataType.required) && dataType.required.length > 0)
|
|
215
|
+
? dataType.required
|
|
216
|
+
: undefined;
|
|
217
|
+
if (!(pick || omit || partial || required))
|
|
218
|
+
return typeDef;
|
|
219
|
+
if (partial === true)
|
|
220
|
+
out += 'Partial<';
|
|
221
|
+
else if (partial) {
|
|
222
|
+
out += 'PartialSome<';
|
|
223
|
+
currentFile.addExport('ts-gems', ['PartialSome']);
|
|
224
|
+
}
|
|
225
|
+
if (required === true)
|
|
226
|
+
out += 'Partial<';
|
|
227
|
+
else if (required) {
|
|
228
|
+
out += 'RequiredSome<';
|
|
229
|
+
currentFile.addExport('ts-gems', ['RequiredSome']);
|
|
230
|
+
}
|
|
231
|
+
if (pick)
|
|
232
|
+
out += 'Pick<';
|
|
233
|
+
else if (omit)
|
|
234
|
+
out += 'Omit<';
|
|
235
|
+
out += typeDef;
|
|
236
|
+
if (omit || pick) {
|
|
237
|
+
out +=
|
|
238
|
+
', ' +
|
|
239
|
+
(omit || pick)
|
|
240
|
+
.filter(x => !!x)
|
|
241
|
+
.map(x => `'${x}'`)
|
|
242
|
+
.join(' | ') +
|
|
243
|
+
'>';
|
|
244
|
+
}
|
|
245
|
+
if (partial) {
|
|
246
|
+
if (Array.isArray(partial)) {
|
|
247
|
+
out +=
|
|
248
|
+
', ' +
|
|
249
|
+
partial
|
|
250
|
+
.filter(x => !!x)
|
|
251
|
+
.map(x => `'${x}'`)
|
|
252
|
+
.join(' | ');
|
|
253
|
+
}
|
|
254
|
+
out += '>';
|
|
255
|
+
}
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
exports._generateMappedTypeCode = _generateMappedTypeCode;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.generateDocument = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const client_1 = require("@opra/client");
|
|
6
|
+
const common_1 = require("@opra/common");
|
|
7
|
+
const chalk_1 = tslib_1.__importDefault(require("chalk"));
|
|
8
|
+
const path_1 = tslib_1.__importDefault(require("path"));
|
|
9
|
+
const putil_varhelpers_1 = require("putil-varhelpers");
|
|
10
|
+
async function generateDocument(document, options) {
|
|
11
|
+
if (!document || typeof document === 'string') {
|
|
12
|
+
if (document) {
|
|
13
|
+
const out = this._documentsMap.get(document);
|
|
14
|
+
if (out)
|
|
15
|
+
return out;
|
|
16
|
+
}
|
|
17
|
+
this.emit('log', chalk_1.default.cyan('Fetching document schema from ') + chalk_1.default.blueBright(this.serviceUrl));
|
|
18
|
+
const client = new client_1.OpraHttpClient(this.serviceUrl);
|
|
19
|
+
document = await client.fetchDocument({ documentId: document });
|
|
20
|
+
}
|
|
21
|
+
this._document = document;
|
|
22
|
+
let out = this._documentsMap.get(document.id);
|
|
23
|
+
if (out)
|
|
24
|
+
return out;
|
|
25
|
+
out = {
|
|
26
|
+
document,
|
|
27
|
+
generator: this,
|
|
28
|
+
};
|
|
29
|
+
this._documentsMap.set(document.id, out);
|
|
30
|
+
this.emit('log', chalk_1.default.white('[' + document.id + '] ') + chalk_1.default.cyan('Processing document ') + chalk_1.default.magenta(document.info.title));
|
|
31
|
+
if (document.references.size) {
|
|
32
|
+
this.emit('log', chalk_1.default.white('[' + document.id + '] ') + chalk_1.default.cyan(`Processing references`));
|
|
33
|
+
for (const ref of document.references.values()) {
|
|
34
|
+
const generator = this.extend();
|
|
35
|
+
generator._document = ref;
|
|
36
|
+
generator._documentRoot = '/references/' + (ref.info.title ? (0, putil_varhelpers_1.pascalCase)(ref.info.title) : ref.id);
|
|
37
|
+
generator._typesRoot = path_1.default.join(generator._documentRoot, 'models');
|
|
38
|
+
await generator.generateDocument(ref, { typesOnly: true });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
this._fileHeaderDocInfo = `/*
|
|
42
|
+
* ${document.info.title}
|
|
43
|
+
* Id: ${document.id}
|
|
44
|
+
* Version: ${document.info.version}
|
|
45
|
+
* ${this.serviceUrl}
|
|
46
|
+
*/`;
|
|
47
|
+
if (document.types.size) {
|
|
48
|
+
this.emit('log', chalk_1.default.white('[' + document.id + ']'), chalk_1.default.cyan(`Processing data types`));
|
|
49
|
+
for (const t of document.types.values()) {
|
|
50
|
+
await this.generateDataType(t, 'root');
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (options?.typesOnly)
|
|
54
|
+
return out;
|
|
55
|
+
if (document.api instanceof common_1.HttpApi) {
|
|
56
|
+
await this.generateHttpApi(document.api);
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
exports.generateDocument = generateDocument;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.generateHttpApi = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const node_path_1 = tslib_1.__importDefault(require("node:path"));
|
|
6
|
+
const putil_varhelpers_1 = require("putil-varhelpers");
|
|
7
|
+
const code_block_js_1 = require("../../code-block.js");
|
|
8
|
+
const http_controller_node_js_1 = require("../http-controller-node.js");
|
|
9
|
+
const string_utils_js_1 = require("../utils/string-utils.js");
|
|
10
|
+
async function generateHttpApi(api) {
|
|
11
|
+
let file = this._filesMap.get(api);
|
|
12
|
+
if (file)
|
|
13
|
+
return file;
|
|
14
|
+
const className = api.name ? (0, putil_varhelpers_1.pascalCase)(api.name) : 'Api';
|
|
15
|
+
file = this.addFile(className + '.ts');
|
|
16
|
+
file.addImport('@opra/client', ['kClient', 'OpraHttpClient']);
|
|
17
|
+
const indexTs = this.addFile('/index.ts', true);
|
|
18
|
+
indexTs.addExport('.' + file.filename);
|
|
19
|
+
const httpApiNodeFile = this.addFile('./http-controller-node.ts');
|
|
20
|
+
httpApiNodeFile.code.content = http_controller_node_js_1.httpControllerNodeScript;
|
|
21
|
+
const classBlock = (file.code[className] = new code_block_js_1.CodeBlock());
|
|
22
|
+
classBlock.doc = `/**
|
|
23
|
+
* ${(0, string_utils_js_1.wrapJSDocString)(api.description || '')}
|
|
24
|
+
* @class ${className}
|
|
25
|
+
* @url ${node_path_1.default.posix.join(this.serviceUrl, '$schema')}
|
|
26
|
+
*/`;
|
|
27
|
+
classBlock.head = `\nexport class ${className} {\n\t`;
|
|
28
|
+
classBlock.properties = 'readonly [kClient]: OpraHttpClient;';
|
|
29
|
+
const classConstBlock = (classBlock.classConstBlock = new code_block_js_1.CodeBlock());
|
|
30
|
+
classConstBlock.head = `\n\nconstructor(client: OpraHttpClient) {`;
|
|
31
|
+
classConstBlock.body = `\n\tthis[kClient] = client;`;
|
|
32
|
+
classConstBlock.tail = `\b\n}\n`;
|
|
33
|
+
for (const controller of api.controllers.values()) {
|
|
34
|
+
const generator = this.extend();
|
|
35
|
+
const f = await generator.generateHttpController(controller);
|
|
36
|
+
const childClassName = (0, putil_varhelpers_1.pascalCase)(controller.name) + 'Controller';
|
|
37
|
+
file.addImport('.' + f.filename, [childClassName]);
|
|
38
|
+
const property = '$' + controller.name.charAt(0).toLowerCase() + (0, putil_varhelpers_1.camelCase)(controller.name.substring(1));
|
|
39
|
+
classBlock.properties += `\nreadonly ${property}: ${childClassName};`;
|
|
40
|
+
classConstBlock.body += `\nthis.${property} = new ${childClassName}(client);`;
|
|
41
|
+
}
|
|
42
|
+
classBlock.tail = `\b}`;
|
|
43
|
+
return file;
|
|
44
|
+
}
|
|
45
|
+
exports.generateHttpApi = generateHttpApi;
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.generateHttpController = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const node_path_1 = tslib_1.__importDefault(require("node:path"));
|
|
6
|
+
const type_is_1 = tslib_1.__importDefault(require("@browsery/type-is"));
|
|
7
|
+
const common_1 = require("@opra/common");
|
|
8
|
+
const putil_varhelpers_1 = require("putil-varhelpers");
|
|
9
|
+
const code_block_js_1 = require("../../code-block.js");
|
|
10
|
+
const locate_named_type_js_1 = require("../utils/locate-named-type.js");
|
|
11
|
+
const string_utils_js_1 = require("../utils/string-utils.js");
|
|
12
|
+
async function generateHttpController(controller) {
|
|
13
|
+
let file = this._filesMap.get(controller);
|
|
14
|
+
if (file)
|
|
15
|
+
return file;
|
|
16
|
+
const className = (0, putil_varhelpers_1.pascalCase)(controller.name) + 'Controller';
|
|
17
|
+
file = this.addFile(node_path_1.default.join(this._apiPath, className + '.ts'));
|
|
18
|
+
file.addImport('@opra/client', ['HttpRequestObservable', 'kClient', 'OpraHttpClient']);
|
|
19
|
+
file.addImport(node_path_1.default.relative(file.dirname, '/http-controller-node.ts'), ['HttpControllerNode']);
|
|
20
|
+
const classBlock = (file.code[className] = new code_block_js_1.CodeBlock());
|
|
21
|
+
classBlock.doc = `/**
|
|
22
|
+
* ${(0, string_utils_js_1.wrapJSDocString)(controller.description || '')}
|
|
23
|
+
* @class ${className}
|
|
24
|
+
* @url ${node_path_1.default.posix.join(this.serviceUrl, '$schema', '#resources/' + className)}
|
|
25
|
+
*/`;
|
|
26
|
+
classBlock.head = `\nexport class ${className} extends HttpControllerNode {\n\t`;
|
|
27
|
+
classBlock.properties = '';
|
|
28
|
+
const classConstBlock = (classBlock.classConstBlock = new code_block_js_1.CodeBlock());
|
|
29
|
+
classConstBlock.head = `\n\nconstructor(client: OpraHttpClient) {`;
|
|
30
|
+
classConstBlock.body = `\n\tsuper(client);`;
|
|
31
|
+
classConstBlock.tail = `\b\n}\n`;
|
|
32
|
+
if (controller.controllers.size) {
|
|
33
|
+
for (const child of controller.controllers.values()) {
|
|
34
|
+
const generator = this.extend();
|
|
35
|
+
generator._apiPath = node_path_1.default.join(this._apiPath, className);
|
|
36
|
+
const f = await generator.generateHttpController(child);
|
|
37
|
+
const childClassName = (0, putil_varhelpers_1.pascalCase)(child.name) + 'Controller';
|
|
38
|
+
file.addImport(f.filename, [childClassName]);
|
|
39
|
+
const property = '$' + child.name.charAt(0).toLowerCase() + (0, putil_varhelpers_1.camelCase)(child.name.substring(1));
|
|
40
|
+
classBlock.properties += `\nreadonly ${property}: ${childClassName};`;
|
|
41
|
+
classConstBlock.body += `\nthis.${property} = new ${childClassName}(client);`;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** Process operations */
|
|
45
|
+
for (const operation of controller.operations.values()) {
|
|
46
|
+
const operationBlock = (classBlock['operation_' + operation.name] = new code_block_js_1.CodeBlock());
|
|
47
|
+
operationBlock.doc = `
|
|
48
|
+
/**
|
|
49
|
+
* ${(0, string_utils_js_1.wrapJSDocString)(operation.description || operation.name + ' operation')}`;
|
|
50
|
+
if (operation.parameters.length) {
|
|
51
|
+
const block = new code_block_js_1.CodeBlock();
|
|
52
|
+
block.doc = '\n *\n * RegExp parameters:';
|
|
53
|
+
let i = 0;
|
|
54
|
+
for (const prm of operation.parameters) {
|
|
55
|
+
if (!(prm.name instanceof RegExp))
|
|
56
|
+
continue;
|
|
57
|
+
i++;
|
|
58
|
+
block.doc +=
|
|
59
|
+
`\n * > ${String(prm.name)} - ${prm.description || ''}` +
|
|
60
|
+
`\n * - location: ${prm.location}` +
|
|
61
|
+
`\n * - type: ${(0, locate_named_type_js_1.locateNamedType)(prm.type)?.name || 'any'}${prm.isArray ? '[' + prm.arraySeparator + ']' : ''}` +
|
|
62
|
+
(prm.required ? `\n * required: ${prm.required}` : '') +
|
|
63
|
+
(prm.deprecated ? `\n * deprecated: ${prm.deprecated}` : '');
|
|
64
|
+
}
|
|
65
|
+
if (i)
|
|
66
|
+
operationBlock.doc += block;
|
|
67
|
+
}
|
|
68
|
+
operationBlock.doc += `\n */\n`;
|
|
69
|
+
operationBlock.head = `${operation.name}(`;
|
|
70
|
+
/** Process operation parameters */
|
|
71
|
+
const mergedParams = [...controller.parameters, ...operation.parameters];
|
|
72
|
+
const pathParams = [];
|
|
73
|
+
const queryParams = [];
|
|
74
|
+
const headerParams = [];
|
|
75
|
+
if (mergedParams.length) {
|
|
76
|
+
const pathParamsMap = {};
|
|
77
|
+
const queryParamsMap = {};
|
|
78
|
+
const headerParamsMap = {};
|
|
79
|
+
for (const prm of mergedParams) {
|
|
80
|
+
if (typeof prm.name !== 'string')
|
|
81
|
+
continue;
|
|
82
|
+
if (prm.location === 'path')
|
|
83
|
+
pathParamsMap[prm.name] = prm;
|
|
84
|
+
if (prm.location === 'query')
|
|
85
|
+
queryParamsMap[prm.name] = prm;
|
|
86
|
+
if (prm.location === 'header')
|
|
87
|
+
headerParamsMap[prm.name] = prm;
|
|
88
|
+
}
|
|
89
|
+
pathParams.push(...Object.values(pathParamsMap));
|
|
90
|
+
queryParams.push(...Object.values(queryParamsMap));
|
|
91
|
+
headerParams.push(...Object.values(headerParamsMap));
|
|
92
|
+
}
|
|
93
|
+
let argIndex = 0;
|
|
94
|
+
for (const prm of pathParams) {
|
|
95
|
+
let typeName;
|
|
96
|
+
if (prm.type) {
|
|
97
|
+
const xt = await this.generateDataType(prm.type, 'typeDef', file);
|
|
98
|
+
typeName = xt.kind === 'embedded' ? xt.code : xt.typeName;
|
|
99
|
+
}
|
|
100
|
+
else
|
|
101
|
+
typeName = `any`;
|
|
102
|
+
if (argIndex++ > 0)
|
|
103
|
+
operationBlock.head += ', ';
|
|
104
|
+
operationBlock.head += `${prm.name}: ${typeName}`;
|
|
105
|
+
}
|
|
106
|
+
let hasBody = false;
|
|
107
|
+
if (operation.requestBody?.content.length) {
|
|
108
|
+
if (argIndex++ > 0)
|
|
109
|
+
operationBlock.head += ', ';
|
|
110
|
+
let typeArr = [];
|
|
111
|
+
for (const content of operation.requestBody.content) {
|
|
112
|
+
if (content.type) {
|
|
113
|
+
const xt = await this.generateDataType(content.type, 'typeDef', file);
|
|
114
|
+
let typeDef = xt.kind === 'embedded' ? xt.code : xt.typeName;
|
|
115
|
+
if (typeDef === 'any') {
|
|
116
|
+
typeArr = [];
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
if (typeDef) {
|
|
120
|
+
if (operation.requestBody.partial) {
|
|
121
|
+
file.addImport('ts-gems', ['PartialDTO']);
|
|
122
|
+
typeDef = `PartialDTO<${typeDef}>`;
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
file.addImport('ts-gems', ['DTO']);
|
|
126
|
+
typeDef = `DTO<${typeDef}>`;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
typeDef = typeDef || 'undefined';
|
|
130
|
+
if (!typeArr.includes(typeDef))
|
|
131
|
+
typeArr.push(typeDef);
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
typeArr = [];
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
operationBlock.head += `$body: ${typeArr.join(' | ') || 'any'}`;
|
|
138
|
+
hasBody = true;
|
|
139
|
+
}
|
|
140
|
+
/** process query params */
|
|
141
|
+
const isQueryRequired = queryParams.find(p => p.required);
|
|
142
|
+
const isHeadersRequired = queryParams.find(p => p.required);
|
|
143
|
+
if (queryParams.length) {
|
|
144
|
+
if (argIndex++ > 0)
|
|
145
|
+
operationBlock.head += ', ';
|
|
146
|
+
operationBlock.head += '\n\t$params' + (isHeadersRequired || isQueryRequired ? '' : '?') + ': {\n\t';
|
|
147
|
+
for (const prm of queryParams) {
|
|
148
|
+
operationBlock.head += `/**\n * ${prm.description || ''}\n */\n`;
|
|
149
|
+
operationBlock.head += `${prm.name}${prm.required ? '' : '?'}: `;
|
|
150
|
+
if (prm.type) {
|
|
151
|
+
const xt = await this.generateDataType(prm.type, 'typeDef', file);
|
|
152
|
+
const typeDef = xt.kind === 'embedded' ? xt.code : xt.typeName;
|
|
153
|
+
operationBlock.head += `${typeDef};\n`;
|
|
154
|
+
}
|
|
155
|
+
else
|
|
156
|
+
operationBlock.head += `any;\n`;
|
|
157
|
+
}
|
|
158
|
+
operationBlock.head += '\b}\b';
|
|
159
|
+
}
|
|
160
|
+
/** process header params */
|
|
161
|
+
if (headerParams.length) {
|
|
162
|
+
if (argIndex++ > 0)
|
|
163
|
+
operationBlock.head += ', \n';
|
|
164
|
+
operationBlock.head += '\t$headers' + (isHeadersRequired ? '' : '?') + ': {\n\t';
|
|
165
|
+
for (const prm of headerParams) {
|
|
166
|
+
operationBlock.head += `/**\n * ${prm.description || ''}\n */\n`;
|
|
167
|
+
operationBlock.head += `${prm.name}${prm.required ? '' : '?'}: `;
|
|
168
|
+
if (prm.type) {
|
|
169
|
+
const xt = await this.generateDataType(prm.type, 'typeDef', file);
|
|
170
|
+
const typeDef = xt.kind === 'embedded' ? xt.code : xt.typeName;
|
|
171
|
+
operationBlock.head += `${typeDef};\n`;
|
|
172
|
+
}
|
|
173
|
+
else
|
|
174
|
+
operationBlock.head += `any;\n`;
|
|
175
|
+
}
|
|
176
|
+
operationBlock.head += '\b}\b';
|
|
177
|
+
}
|
|
178
|
+
/* Determine return type */
|
|
179
|
+
const returnTypes = [];
|
|
180
|
+
let typeDef = '';
|
|
181
|
+
for (const resp of operation.responses) {
|
|
182
|
+
if (!resp.statusCode.find(r => r.intersects(200, 299)))
|
|
183
|
+
continue;
|
|
184
|
+
typeDef = '';
|
|
185
|
+
if (resp.type) {
|
|
186
|
+
const xt = await this.generateDataType(resp.type, 'typeDef', file);
|
|
187
|
+
typeDef = xt.kind === 'embedded' ? xt.code : xt.typeName;
|
|
188
|
+
}
|
|
189
|
+
if (typeDef) {
|
|
190
|
+
if (typeDef !== 'OperationResult') {
|
|
191
|
+
if (resp.partial) {
|
|
192
|
+
file.addImport('ts-gems', ['PartialDTO']);
|
|
193
|
+
typeDef = `PartialDTO<${typeDef}>`;
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
file.addImport('ts-gems', ['DTO']);
|
|
197
|
+
typeDef = `DTO<${typeDef}>`;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (resp.contentType && type_is_1.default.is(String(resp.contentType), [common_1.MimeTypes.opra_response_json])) {
|
|
202
|
+
file.addImport('@opra/common', ['OperationResult']);
|
|
203
|
+
typeDef = typeDef ? `OperationResult<${typeDef}>` : 'OperationResult';
|
|
204
|
+
}
|
|
205
|
+
typeDef = typeDef || 'undefined';
|
|
206
|
+
if (!returnTypes.includes(typeDef))
|
|
207
|
+
returnTypes.push(typeDef);
|
|
208
|
+
}
|
|
209
|
+
operationBlock.head += `\n): HttpRequestObservable<${returnTypes.join(' | ') || 'any'}>{`;
|
|
210
|
+
operationBlock.body = `\n\t`;
|
|
211
|
+
operationBlock.body +=
|
|
212
|
+
`const url = this._prepareUrl('${operation.getFullUrl()}', {` + pathParams.map(p => p.name).join(', ') + '});';
|
|
213
|
+
operationBlock.body +=
|
|
214
|
+
`\nreturn this[kClient].request(url, { method: '${operation.method}'` +
|
|
215
|
+
(hasBody ? ', body: $body' : '') +
|
|
216
|
+
(queryParams.length ? ', params: $params as any' : '') +
|
|
217
|
+
(headerParams.length ? ', headers: $headers as any' : '') +
|
|
218
|
+
'});';
|
|
219
|
+
operationBlock.tail = `\b\n};\n`;
|
|
220
|
+
}
|
|
221
|
+
classBlock.tail = `\b}`;
|
|
222
|
+
return file;
|
|
223
|
+
}
|
|
224
|
+
exports.generateHttpController = generateHttpController;
|