@opra/cli 1.0.0-alpha.9 → 1.0.0-beta.2

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.
Files changed (41) hide show
  1. package/cjs/file-writer.js +2 -2
  2. package/cjs/oprimp-cli.js +11 -9
  3. package/cjs/ts-generator/{processors → generators}/clean-directory.js +4 -5
  4. package/cjs/ts-generator/generators/generate-data-type.js +258 -0
  5. package/cjs/ts-generator/generators/generate-document.js +64 -0
  6. package/cjs/ts-generator/{processors/process-http-api.js → generators/generate-http-api.js} +3 -4
  7. package/cjs/ts-generator/generators/generate-http-controller.js +296 -0
  8. package/cjs/ts-generator/ts-file.js +18 -12
  9. package/cjs/ts-generator/ts-generator.js +20 -20
  10. package/cjs/ts-generator/utils/locate-named-type.js +1 -2
  11. package/cjs/ts-generator/utils/string-utils.js +4 -5
  12. package/esm/file-writer.js +1 -1
  13. package/esm/oprimp-cli.js +9 -7
  14. package/esm/package.json +3 -0
  15. package/esm/ts-generator/{processors → generators}/clean-directory.js +3 -3
  16. package/esm/ts-generator/generators/generate-data-type.js +248 -0
  17. package/esm/ts-generator/{processors/process-document.js → generators/generate-document.js} +17 -12
  18. package/esm/ts-generator/{processors/process-http-api.js → generators/generate-http-api.js} +2 -2
  19. package/esm/ts-generator/generators/generate-http-controller.js +292 -0
  20. package/esm/ts-generator/ts-file.js +15 -9
  21. package/esm/ts-generator/ts-generator.js +20 -20
  22. package/package.json +28 -33
  23. package/types/file-writer.d.ts +1 -1
  24. package/types/index.d.cts +1 -0
  25. package/types/interfaces/service-generation-context.interface.d.ts +2 -2
  26. package/types/ts-generator/generators/generate-data-type.d.ts +41 -0
  27. package/types/ts-generator/{processors/process-document.d.ts → generators/generate-document.d.ts} +1 -1
  28. package/types/ts-generator/generators/generate-http-api.d.ts +3 -0
  29. package/types/ts-generator/generators/generate-http-controller.d.ts +3 -0
  30. package/types/ts-generator/ts-file.d.ts +6 -2
  31. package/types/ts-generator/ts-generator.d.ts +22 -20
  32. package/bin/bin/oprimp.mjs +0 -3
  33. package/cjs/ts-generator/processors/process-data-types.js +0 -262
  34. package/cjs/ts-generator/processors/process-document.js +0 -60
  35. package/cjs/ts-generator/processors/process-http-controller.js +0 -189
  36. package/esm/ts-generator/processors/process-data-types.js +0 -251
  37. package/esm/ts-generator/processors/process-http-controller.js +0 -184
  38. package/types/ts-generator/processors/process-data-types.d.ts +0 -30
  39. package/types/ts-generator/processors/process-http-api.d.ts +0 -3
  40. package/types/ts-generator/processors/process-http-controller.d.ts +0 -3
  41. /package/types/ts-generator/{processors → generators}/clean-directory.d.ts +0 -0
@@ -1,60 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.processDocument = 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 processDocument(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.processDocument(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.processDataType(t);
51
- }
52
- }
53
- if (options?.typesOnly)
54
- return out;
55
- if (document.api instanceof common_1.HttpApi) {
56
- await this.processHttpApi(document.api);
57
- }
58
- return out;
59
- }
60
- exports.processDocument = processDocument;
@@ -1,189 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.processHttpController = 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 locate_named_type_js_1 = require("../utils/locate-named-type.js");
9
- const string_utils_js_1 = require("../utils/string-utils.js");
10
- async function processHttpController(controller) {
11
- let file = this._filesMap.get(controller);
12
- if (file)
13
- return file;
14
- const className = (0, putil_varhelpers_1.pascalCase)(controller.name) + 'Controller';
15
- file = this.addFile(node_path_1.default.join(this._apiPath, className + '.ts'));
16
- file.addImport('@opra/client', ['HttpRequestObservable', 'kClient', 'OpraHttpClient']);
17
- file.addImport(node_path_1.default.relative(file.dirname, '/http-controller-node.ts'), ['HttpControllerNode']);
18
- const classBlock = (file.code[className] = new code_block_js_1.CodeBlock());
19
- classBlock.doc = `/**
20
- * ${(0, string_utils_js_1.wrapJSDocString)(controller.description || '')}
21
- * @class ${className}
22
- * @url ${node_path_1.default.posix.join(this.serviceUrl, '$schema', '#resources/' + className)}
23
- */`;
24
- classBlock.head = `\nexport class ${className} extends HttpControllerNode {\n\t`;
25
- classBlock.properties = '';
26
- const classConstBlock = (classBlock.classConstBlock = new code_block_js_1.CodeBlock());
27
- classConstBlock.head = `\n\nconstructor(client: OpraHttpClient) {`;
28
- classConstBlock.body = `\n\tsuper(client);`;
29
- classConstBlock.tail = `\b\n}\n`;
30
- if (controller.controllers.size) {
31
- for (const child of controller.controllers.values()) {
32
- const generator = this.extend();
33
- generator._apiPath = node_path_1.default.join(this._apiPath, className);
34
- const f = await generator.processHttpController(child);
35
- const childClassName = (0, putil_varhelpers_1.pascalCase)(child.name) + 'Controller';
36
- file.addImport(f.filename, [childClassName]);
37
- const property = '$' + child.name.charAt(0).toLowerCase() + (0, putil_varhelpers_1.camelCase)(child.name.substring(1));
38
- classBlock.properties += `\nreadonly ${property}: ${childClassName};`;
39
- classConstBlock.body += `\nthis.${property} = new ${childClassName}(client);`;
40
- }
41
- }
42
- /** Process operations */
43
- for (const operation of controller.operations.values()) {
44
- const operationBlock = (classBlock['operation_' + operation.name] = new code_block_js_1.CodeBlock());
45
- operationBlock.doc = `
46
- /**
47
- * ${(0, string_utils_js_1.wrapJSDocString)(operation.description || operation.name + ' operation')}`;
48
- if (operation.parameters.length) {
49
- const block = new code_block_js_1.CodeBlock();
50
- block.doc = '\n *\n * RegExp parameters:';
51
- let i = 0;
52
- for (const prm of operation.parameters) {
53
- if (!(prm.name instanceof RegExp))
54
- continue;
55
- i++;
56
- block.doc +=
57
- `\n * > ${String(prm.name)} - ${prm.description || ''}` +
58
- `\n * - location: ${prm.location}` +
59
- `\n * - type: ${(0, locate_named_type_js_1.locateNamedType)(prm.type)?.name || 'any'}${prm.isArray ? '[' + prm.arraySeparator + ']' : ''}` +
60
- (prm.required ? `\n * required: ${prm.required}` : '') +
61
- (prm.deprecated ? `\n * deprecated: ${prm.deprecated}` : '');
62
- }
63
- if (i)
64
- operationBlock.doc += block;
65
- }
66
- operationBlock.doc += `\n */\n`;
67
- operationBlock.head = `${operation.name}(`;
68
- /** Process operation parameters */
69
- const mergedParams = [...controller.parameters, ...operation.parameters];
70
- const pathParams = [];
71
- const queryParams = [];
72
- const headerParams = [];
73
- if (mergedParams.length) {
74
- const pathParamsMap = {};
75
- const queryParamsMap = {};
76
- const headerParamsMap = {};
77
- for (const prm of mergedParams) {
78
- if (typeof prm.name !== 'string')
79
- continue;
80
- if (prm.location === 'path')
81
- pathParamsMap[prm.name] = prm;
82
- if (prm.location === 'query')
83
- queryParamsMap[prm.name] = prm;
84
- if (prm.location === 'header')
85
- headerParamsMap[prm.name] = prm;
86
- }
87
- pathParams.push(...Object.values(pathParamsMap));
88
- queryParams.push(...Object.values(queryParamsMap));
89
- headerParams.push(...Object.values(headerParamsMap));
90
- }
91
- let argIndex = 0;
92
- for (const prm of pathParams) {
93
- const type = (0, locate_named_type_js_1.locateNamedType)(prm.type);
94
- if (argIndex++ > 0)
95
- operationBlock.head += ', ';
96
- operationBlock.head += `${prm.name}: ${type?.name || 'any'}`;
97
- }
98
- let hasBody = false;
99
- if (operation.requestBody?.content.length) {
100
- if (argIndex++ > 0)
101
- operationBlock.head += ', ';
102
- let typeArr = [];
103
- for (const content of operation.requestBody.content) {
104
- if (content.type) {
105
- const dtFile = this._filesMap.get(content.type);
106
- if (dtFile) {
107
- const typeName = await this.resolveTypeNameOrDef(content.type, dtFile, 'field');
108
- typeArr.push(typeName);
109
- file.addImport(dtFile.filename, [typeName]);
110
- continue;
111
- }
112
- }
113
- typeArr = [];
114
- break;
115
- }
116
- if (typeArr.length) {
117
- if (operation.requestBody.partial) {
118
- file.addImport('ts-gems', ['PartialDTO']);
119
- operationBlock.head += `$body: PartialDTO<${typeArr.join(' | ')}>`;
120
- }
121
- else {
122
- file.addImport('ts-gems', ['DTO']);
123
- operationBlock.head += `$body: DTO<${typeArr.join(' | ')}>`;
124
- }
125
- }
126
- else
127
- operationBlock.head += `$body: any`;
128
- hasBody = true;
129
- }
130
- /** process query params */
131
- const isQueryRequired = queryParams.find(p => p.required);
132
- const isHeadersRequired = queryParams.find(p => p.required);
133
- if (queryParams.length) {
134
- if (argIndex++ > 0)
135
- operationBlock.head += ', ';
136
- operationBlock.head += '\n\t$params' + (isHeadersRequired || isQueryRequired ? '' : '?') + ': {\n\t';
137
- for (const prm of queryParams) {
138
- const type = (0, locate_named_type_js_1.locateNamedType)(prm.type);
139
- operationBlock.head += `/**\n * ${prm.description || ''}\n */\n`;
140
- operationBlock.head += `${prm.name}${prm.required ? '' : '?'}: `;
141
- if (type?.name) {
142
- const typeFile = await this.processDataType(type);
143
- if (typeFile) {
144
- file.addImport(typeFile.filename, [type.name]);
145
- operationBlock.head += `${type.name};\n`;
146
- continue;
147
- }
148
- }
149
- operationBlock.head += `${type?.name || 'any'};\n`;
150
- }
151
- operationBlock.head += '\b}\b';
152
- }
153
- /** process header params */
154
- if (headerParams.length) {
155
- if (argIndex++ > 0)
156
- operationBlock.head += ', \n';
157
- operationBlock.head += '\t$headers' + (isHeadersRequired ? '' : '?') + ': {\n\t';
158
- for (const prm of headerParams) {
159
- const type = (0, locate_named_type_js_1.locateNamedType)(prm.type);
160
- operationBlock.head += `/**\n * ${prm.description || ''}\n */\n`;
161
- operationBlock.head += `${prm.name}${prm.required ? '' : '?'}: `;
162
- if (type?.name) {
163
- const typeFile = await this.processDataType(type);
164
- if (typeFile) {
165
- file.addImport(typeFile.filename, [type.name]);
166
- operationBlock.head += `${type.name};\n`;
167
- continue;
168
- }
169
- }
170
- operationBlock.head += `${type?.name || 'any'};\n`;
171
- }
172
- operationBlock.head += '\b}\b';
173
- }
174
- operationBlock.head += `\n): HttpRequestObservable<any>{`;
175
- operationBlock.body = `\n\t`;
176
- operationBlock.body +=
177
- `const url = this._prepareUrl('${operation.getFullUrl()}', {` + pathParams.map(p => p.name).join(', ') + '});';
178
- operationBlock.body +=
179
- `\nreturn this[kClient].request(url, {` +
180
- (hasBody ? ' body: $body,' : '') +
181
- (queryParams.length ? ' params: $params as any,' : '') +
182
- (headerParams.length ? ' headers: $headers as any,' : '') +
183
- '});';
184
- operationBlock.tail = `\b\n};\n`;
185
- }
186
- classBlock.tail = `\b}`;
187
- return file;
188
- }
189
- exports.processHttpController = processHttpController;
@@ -1,251 +0,0 @@
1
- import { ComplexType, EnumType, MappedType, MixinType, SimpleType } from '@opra/common';
2
- import path from 'path';
3
- import { CodeBlock } from '../../code-block.js';
4
- import { wrapJSDocString } from '../utils/string-utils.js';
5
- const internalTypeNames = ['any', 'boolean', 'bigint', 'number', 'null', 'string', 'object'];
6
- export async function processDataType(dataType) {
7
- const doc = dataType.node.getDocument();
8
- if (doc.id !== this._document?.id) {
9
- const { generator } = await this.processDocument(doc);
10
- return await generator.processDataType(dataType);
11
- }
12
- const typeName = dataType.name;
13
- if (typeName && internalTypeNames.includes(typeName))
14
- return;
15
- if (!typeName)
16
- throw new TypeError(`DataType has no name`);
17
- let file = this._filesMap.get(dataType);
18
- if (file)
19
- return file;
20
- if (dataType instanceof SimpleType)
21
- file = this.addFile(path.join(this._documentRoot, '/simple-types.ts'), true);
22
- else {
23
- if (dataType instanceof EnumType)
24
- file = this.addFile(path.join(this._typesRoot, 'enums', typeName + '.ts'));
25
- else
26
- file = this.addFile(path.join(this._typesRoot, 'types', typeName + '.ts'));
27
- }
28
- this._filesMap.set(dataType, file);
29
- file = this._filesMap.get(dataType);
30
- if (file.exportTypes.includes(typeName))
31
- return file;
32
- file.exportTypes.push(typeName);
33
- const typesIndexTs = this.addFile(path.join(this._typesRoot, 'index.ts'), true);
34
- const indexTs = this.addFile('/index.ts', true);
35
- indexTs.addExport(typesIndexTs.filename);
36
- const codeBlock = (file.code['type_' + typeName] = new CodeBlock());
37
- codeBlock.head = `/**\n * ${typeName}`;
38
- if (dataType.description)
39
- codeBlock.head += `\n * ${wrapJSDocString(dataType.description || '')}`;
40
- codeBlock.head += `
41
- * @url ${path.posix.join(doc.url || this.serviceUrl, '$schema', '#types/' + typeName)}
42
- */
43
- export `;
44
- if (dataType instanceof EnumType)
45
- codeBlock.typeDef = await this.generateEnumTypeDefinition(dataType, 'scope');
46
- else if (dataType instanceof ComplexType) {
47
- codeBlock.typeDef = await this.generateComplexTypeDefinition(dataType, file, 'scope');
48
- }
49
- else if (dataType instanceof SimpleType) {
50
- codeBlock.typeDef = await this.generateSimpleTypeDefinition(dataType, 'scope');
51
- }
52
- else if (dataType instanceof MappedType) {
53
- codeBlock.typeDef = await this.generateMappedTypeDefinition(dataType, file, 'scope');
54
- }
55
- else if (dataType instanceof MixinType) {
56
- codeBlock.typeDef = await this.generateMixinTypeDefinition(dataType, file, 'scope');
57
- }
58
- else
59
- throw new TypeError(`${dataType.kind} data type (${typeName}) can not be directly exported`);
60
- typesIndexTs.addExport(file.filename);
61
- return file;
62
- }
63
- /**
64
- *
65
- */
66
- export async function generateEnumTypeDefinition(dataType, intent) {
67
- if (intent === 'field') {
68
- return ('(' +
69
- Object.keys(dataType.attributes)
70
- .map(t => `'${t}'`)
71
- .join(' | ') +
72
- ')');
73
- }
74
- if (intent !== 'scope')
75
- throw new TypeError(`Can't generate EnumType for "${intent}" intent`);
76
- if (!dataType.name)
77
- throw new TypeError(`Name required to generate EnumType for "${intent}" intent`);
78
- let out = `enum ${dataType.name} {\n\t`;
79
- for (const [value, info] of Object.entries(dataType.attributes)) {
80
- // Print JSDoc
81
- let jsDoc = '';
82
- if (dataType.attributes[value].description)
83
- jsDoc += ` * ${dataType.attributes[value].description}\n`;
84
- if (jsDoc)
85
- out += `/**\n${jsDoc} */\n`;
86
- out +=
87
- `${info.alias || value} = ` + (typeof value === 'number' ? value : "'" + String(value).replace("'", "\\'") + "'");
88
- out += ',\n\n';
89
- }
90
- return out + '\b}';
91
- }
92
- /**
93
- *
94
- */
95
- export async function generateComplexTypeDefinition(dataType, file, intent) {
96
- if (intent === 'scope' && !dataType.name) {
97
- throw new TypeError(`Name required to generate ComplexType for "${intent}" intent`);
98
- }
99
- let out = intent === 'scope' ? `interface ${dataType.name} ` : '';
100
- const ownFields = [...dataType.fields.values()].filter(f => f.origin === dataType);
101
- if (dataType.base) {
102
- const base = await this.resolveTypeNameOrDef(dataType.base, file, 'extends');
103
- const omitBaseFields = dataType.base ? ownFields.filter(f => dataType.base.fields.has(f.name)) : [];
104
- const baseDef = omitBaseFields.length
105
- ? `Omit<${base}, ${omitBaseFields.map(x => "'" + x.name + "'").join(' | ')}>`
106
- : `${base}`;
107
- if (intent === 'scope')
108
- out += `extends ${baseDef} `;
109
- else {
110
- out += baseDef;
111
- if (!ownFields.length)
112
- return out;
113
- out += ' & ';
114
- }
115
- }
116
- out += '{\n\t';
117
- let i = 0;
118
- for (const field of ownFields) {
119
- if (i++)
120
- out += '\n';
121
- // Print JSDoc
122
- out += `/**\n * ${field.description || ''}\n`;
123
- if (field.default)
124
- out += ` * @default ` + field.default + '\n';
125
- // if (field.format)
126
- // jsDoc += ` * @format ` + field.format + '\n';
127
- if (field.exclusive)
128
- out += ` * @exclusive\n`;
129
- if (field.readonly)
130
- out += ` * @readonly\n`;
131
- if (field.writeonly)
132
- out += ` * @writeonly\n`;
133
- if (field.deprecated) {
134
- out += ` * @deprecated ` + (typeof field.deprecated === 'string' ? field.deprecated : '') + '\n';
135
- }
136
- out += ' */\n';
137
- // Print field name
138
- if (field.readonly)
139
- out += 'readonly ';
140
- out += `${field.name}${field.required ? '' : '?'}: `;
141
- if (field.fixed) {
142
- const t = typeof field.fixed;
143
- out += `${t === 'number' || t === 'boolean' || t === 'bigint' ? field.fixed : "'" + field.fixed + "'"}\n`;
144
- }
145
- else {
146
- out += (await this.resolveTypeNameOrDef(field.type, file, 'field')) + `${field.isArray ? '[]' : ''};\n`;
147
- }
148
- }
149
- if (dataType.additionalFields)
150
- out += '[key: string]: any;\n';
151
- return out + '\b}';
152
- }
153
- /**
154
- *
155
- */
156
- export async function generateSimpleTypeDefinition(dataType, intent) {
157
- if (intent === 'scope' && !dataType.name) {
158
- throw new TypeError(`Name required to generate SimpleType for "${intent}" intent`);
159
- }
160
- let out = intent === 'scope' ? `type ${dataType.name} = ` : '';
161
- out += dataType.nameMappings.js || 'any';
162
- return intent === 'scope' ? out + ';' : out;
163
- }
164
- /**
165
- *
166
- */
167
- export async function generateMixinTypeDefinition(dataType, file, intent) {
168
- return (await Promise.all(dataType.types.map(t => this.resolveTypeNameOrDef(t, file, intent))))
169
- .map(t => (t.includes('|') ? '(' + t + ')' : t))
170
- .join(intent === 'extends' ? ', ' : ' & ');
171
- }
172
- /**
173
- *
174
- */
175
- export async function generateMappedTypeDefinition(dataType, file, intent) {
176
- const typeDef = await this.resolveTypeNameOrDef(dataType.base, file, intent);
177
- const pick = dataType.pick?.length ? dataType.pick : undefined;
178
- const omit = !pick && dataType.omit?.length ? dataType.omit : undefined;
179
- const partial = dataType.partial === true || (Array.isArray(dataType.partial) && dataType.partial.length > 0)
180
- ? dataType.partial
181
- : undefined;
182
- const required = dataType.required === true || (Array.isArray(dataType.required) && dataType.required.length > 0)
183
- ? dataType.required
184
- : undefined;
185
- if (!(pick || omit || partial || required))
186
- return typeDef;
187
- let out = '';
188
- if (partial === true)
189
- out += 'Partial<';
190
- else if (partial) {
191
- out += 'PartialSome<';
192
- file.addExport('ts-gems', ['PartialSome']);
193
- }
194
- if (required === true)
195
- out += 'Partial<';
196
- else if (required) {
197
- out += 'RequiredSome<';
198
- file.addExport('ts-gems', ['RequiredSome']);
199
- }
200
- if (pick)
201
- out += 'Pick<';
202
- else if (omit)
203
- out += 'Omit<';
204
- out += typeDef;
205
- if (omit || pick) {
206
- out +=
207
- ', ' +
208
- (omit || pick)
209
- .filter(x => !!x)
210
- .map(x => `'${x}'`)
211
- .join(' | ') +
212
- '>';
213
- }
214
- if (partial) {
215
- if (Array.isArray(partial)) {
216
- out +=
217
- ', ' +
218
- partial
219
- .filter(x => !!x)
220
- .map(x => `'${x}'`)
221
- .join(' | ');
222
- }
223
- out += '>';
224
- }
225
- return out;
226
- }
227
- /**
228
- *
229
- */
230
- export async function resolveTypeNameOrDef(dataType, file, intent) {
231
- if (dataType.name && !dataType.embedded) {
232
- if (internalTypeNames.includes(dataType.name))
233
- return dataType.name;
234
- const f = await this.processDataType(dataType);
235
- if (!f)
236
- return '';
237
- file.addImport(f.filename, [dataType.name], true);
238
- return dataType.name;
239
- }
240
- if (dataType instanceof SimpleType)
241
- return this.generateSimpleTypeDefinition(dataType, intent);
242
- if (dataType instanceof EnumType)
243
- return this.generateEnumTypeDefinition(dataType, intent);
244
- if (dataType instanceof MixinType)
245
- return this.generateMixinTypeDefinition(dataType, file, intent);
246
- if (dataType instanceof MappedType)
247
- return this.generateMappedTypeDefinition(dataType, file, intent);
248
- if (dataType instanceof ComplexType)
249
- return this.generateComplexTypeDefinition(dataType, file, intent);
250
- return '';
251
- }
@@ -1,184 +0,0 @@
1
- import path from 'node:path';
2
- import { camelCase, pascalCase } from 'putil-varhelpers';
3
- import { CodeBlock } from '../../code-block.js';
4
- import { locateNamedType } from '../utils/locate-named-type.js';
5
- import { wrapJSDocString } from '../utils/string-utils.js';
6
- export async function processHttpController(controller) {
7
- let file = this._filesMap.get(controller);
8
- if (file)
9
- return file;
10
- const className = pascalCase(controller.name) + 'Controller';
11
- file = this.addFile(path.join(this._apiPath, className + '.ts'));
12
- file.addImport('@opra/client', ['HttpRequestObservable', 'kClient', 'OpraHttpClient']);
13
- file.addImport(path.relative(file.dirname, '/http-controller-node.ts'), ['HttpControllerNode']);
14
- const classBlock = (file.code[className] = new CodeBlock());
15
- classBlock.doc = `/**
16
- * ${wrapJSDocString(controller.description || '')}
17
- * @class ${className}
18
- * @url ${path.posix.join(this.serviceUrl, '$schema', '#resources/' + className)}
19
- */`;
20
- classBlock.head = `\nexport class ${className} extends HttpControllerNode {\n\t`;
21
- classBlock.properties = '';
22
- const classConstBlock = (classBlock.classConstBlock = new CodeBlock());
23
- classConstBlock.head = `\n\nconstructor(client: OpraHttpClient) {`;
24
- classConstBlock.body = `\n\tsuper(client);`;
25
- classConstBlock.tail = `\b\n}\n`;
26
- if (controller.controllers.size) {
27
- for (const child of controller.controllers.values()) {
28
- const generator = this.extend();
29
- generator._apiPath = path.join(this._apiPath, className);
30
- const f = await generator.processHttpController(child);
31
- const childClassName = pascalCase(child.name) + 'Controller';
32
- file.addImport(f.filename, [childClassName]);
33
- const property = '$' + child.name.charAt(0).toLowerCase() + camelCase(child.name.substring(1));
34
- classBlock.properties += `\nreadonly ${property}: ${childClassName};`;
35
- classConstBlock.body += `\nthis.${property} = new ${childClassName}(client);`;
36
- }
37
- }
38
- /** Process operations */
39
- for (const operation of controller.operations.values()) {
40
- const operationBlock = (classBlock['operation_' + operation.name] = new CodeBlock());
41
- operationBlock.doc = `
42
- /**
43
- * ${wrapJSDocString(operation.description || operation.name + ' operation')}`;
44
- if (operation.parameters.length) {
45
- const block = new CodeBlock();
46
- block.doc = '\n *\n * RegExp parameters:';
47
- let i = 0;
48
- for (const prm of operation.parameters) {
49
- if (!(prm.name instanceof RegExp))
50
- continue;
51
- i++;
52
- block.doc +=
53
- `\n * > ${String(prm.name)} - ${prm.description || ''}` +
54
- `\n * - location: ${prm.location}` +
55
- `\n * - type: ${locateNamedType(prm.type)?.name || 'any'}${prm.isArray ? '[' + prm.arraySeparator + ']' : ''}` +
56
- (prm.required ? `\n * required: ${prm.required}` : '') +
57
- (prm.deprecated ? `\n * deprecated: ${prm.deprecated}` : '');
58
- }
59
- if (i)
60
- operationBlock.doc += block;
61
- }
62
- operationBlock.doc += `\n */\n`;
63
- operationBlock.head = `${operation.name}(`;
64
- /** Process operation parameters */
65
- const mergedParams = [...controller.parameters, ...operation.parameters];
66
- const pathParams = [];
67
- const queryParams = [];
68
- const headerParams = [];
69
- if (mergedParams.length) {
70
- const pathParamsMap = {};
71
- const queryParamsMap = {};
72
- const headerParamsMap = {};
73
- for (const prm of mergedParams) {
74
- if (typeof prm.name !== 'string')
75
- continue;
76
- if (prm.location === 'path')
77
- pathParamsMap[prm.name] = prm;
78
- if (prm.location === 'query')
79
- queryParamsMap[prm.name] = prm;
80
- if (prm.location === 'header')
81
- headerParamsMap[prm.name] = prm;
82
- }
83
- pathParams.push(...Object.values(pathParamsMap));
84
- queryParams.push(...Object.values(queryParamsMap));
85
- headerParams.push(...Object.values(headerParamsMap));
86
- }
87
- let argIndex = 0;
88
- for (const prm of pathParams) {
89
- const type = locateNamedType(prm.type);
90
- if (argIndex++ > 0)
91
- operationBlock.head += ', ';
92
- operationBlock.head += `${prm.name}: ${type?.name || 'any'}`;
93
- }
94
- let hasBody = false;
95
- if (operation.requestBody?.content.length) {
96
- if (argIndex++ > 0)
97
- operationBlock.head += ', ';
98
- let typeArr = [];
99
- for (const content of operation.requestBody.content) {
100
- if (content.type) {
101
- const dtFile = this._filesMap.get(content.type);
102
- if (dtFile) {
103
- const typeName = await this.resolveTypeNameOrDef(content.type, dtFile, 'field');
104
- typeArr.push(typeName);
105
- file.addImport(dtFile.filename, [typeName]);
106
- continue;
107
- }
108
- }
109
- typeArr = [];
110
- break;
111
- }
112
- if (typeArr.length) {
113
- if (operation.requestBody.partial) {
114
- file.addImport('ts-gems', ['PartialDTO']);
115
- operationBlock.head += `$body: PartialDTO<${typeArr.join(' | ')}>`;
116
- }
117
- else {
118
- file.addImport('ts-gems', ['DTO']);
119
- operationBlock.head += `$body: DTO<${typeArr.join(' | ')}>`;
120
- }
121
- }
122
- else
123
- operationBlock.head += `$body: any`;
124
- hasBody = true;
125
- }
126
- /** process query params */
127
- const isQueryRequired = queryParams.find(p => p.required);
128
- const isHeadersRequired = queryParams.find(p => p.required);
129
- if (queryParams.length) {
130
- if (argIndex++ > 0)
131
- operationBlock.head += ', ';
132
- operationBlock.head += '\n\t$params' + (isHeadersRequired || isQueryRequired ? '' : '?') + ': {\n\t';
133
- for (const prm of queryParams) {
134
- const type = locateNamedType(prm.type);
135
- operationBlock.head += `/**\n * ${prm.description || ''}\n */\n`;
136
- operationBlock.head += `${prm.name}${prm.required ? '' : '?'}: `;
137
- if (type?.name) {
138
- const typeFile = await this.processDataType(type);
139
- if (typeFile) {
140
- file.addImport(typeFile.filename, [type.name]);
141
- operationBlock.head += `${type.name};\n`;
142
- continue;
143
- }
144
- }
145
- operationBlock.head += `${type?.name || 'any'};\n`;
146
- }
147
- operationBlock.head += '\b}\b';
148
- }
149
- /** process header params */
150
- if (headerParams.length) {
151
- if (argIndex++ > 0)
152
- operationBlock.head += ', \n';
153
- operationBlock.head += '\t$headers' + (isHeadersRequired ? '' : '?') + ': {\n\t';
154
- for (const prm of headerParams) {
155
- const type = locateNamedType(prm.type);
156
- operationBlock.head += `/**\n * ${prm.description || ''}\n */\n`;
157
- operationBlock.head += `${prm.name}${prm.required ? '' : '?'}: `;
158
- if (type?.name) {
159
- const typeFile = await this.processDataType(type);
160
- if (typeFile) {
161
- file.addImport(typeFile.filename, [type.name]);
162
- operationBlock.head += `${type.name};\n`;
163
- continue;
164
- }
165
- }
166
- operationBlock.head += `${type?.name || 'any'};\n`;
167
- }
168
- operationBlock.head += '\b}\b';
169
- }
170
- operationBlock.head += `\n): HttpRequestObservable<any>{`;
171
- operationBlock.body = `\n\t`;
172
- operationBlock.body +=
173
- `const url = this._prepareUrl('${operation.getFullUrl()}', {` + pathParams.map(p => p.name).join(', ') + '});';
174
- operationBlock.body +=
175
- `\nreturn this[kClient].request(url, {` +
176
- (hasBody ? ' body: $body,' : '') +
177
- (queryParams.length ? ' params: $params as any,' : '') +
178
- (headerParams.length ? ' headers: $headers as any,' : '') +
179
- '});';
180
- operationBlock.tail = `\b\n};\n`;
181
- }
182
- classBlock.tail = `\b}`;
183
- return file;
184
- }