-
-
Notifications
You must be signed in to change notification settings - Fork 169
/
fromTemplate.ts
427 lines (385 loc) · 16.2 KB
/
fromTemplate.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
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import { Flags, Args } from '@oclif/core';
import Command from '../../base';
// eslint-disable-next-line
// @ts-ignore
import AsyncAPIGenerator from '@asyncapi/generator';
import path from 'path';
import os from 'os';
import fs from 'fs';
import { load, Specification } from '../../models/SpecificationFile';
import { watchFlag } from '../../flags';
import { isLocalTemplate, Watcher } from '../../utils/generator';
import { ValidationError } from '../../errors/validation-error';
import { GeneratorError } from '../../errors/generator-error';
import { Parser } from '@asyncapi/parser';
import { intro, isCancel, spinner, text } from '@clack/prompts';
import { inverse, yellow, magenta, green, red } from 'picocolors';
import fetch from 'node-fetch';
interface IMapBaseUrlToFlag {
url: string,
folder: string
}
interface ParsedFlags {
params: Record<string, string>,
disableHooks: Record<string, string>,
mapBaseUrlToFolder: IMapBaseUrlToFlag
}
const templatesNotSupportingV3: Record<string, string> = {
'@asyncapi/minimaltemplate': 'some link', // For testing purpose
'@asyncapi/dotnet-nats-template': 'https://github.com/asyncapi/dotnet-nats-template/issues/384',
'@asyncapi/ts-nats-template': 'https://github.com/asyncapi/ts-nats-template/issues/545',
'@asyncapi/python-paho-template': 'https://github.com/asyncapi/python-paho-template/issues/189',
'@asyncapi/nodejs-ws-template': 'https://github.com/asyncapi/nodejs-ws-template/issues/294',
'@asyncapi/java-spring-cloud-stream-template': 'https://github.com/asyncapi/java-spring-cloud-stream-template/issues/336',
'@asyncapi/go-watermill-template': 'https://github.com/asyncapi/go-watermill-template/issues/243',
'@asyncapi/java-spring-template': 'https://github.com/asyncapi/java-spring-template/issues/308',
'@asyncapi/php-template': 'https://github.com/asyncapi/php-template/issues/191'
};
/**
* Verify that a given template support v3, if not, return the link to the issue that needs to be solved.
*/
function verifyTemplateSupportForV3(template: string) {
if (templatesNotSupportingV3[`${template}`] !== undefined) {
return templatesNotSupportingV3[`${template}`];
}
return undefined;
}
export default class Template extends Command {
static description = 'Generates whatever you want using templates compatible with AsyncAPI Generator.';
static examples = [
'asyncapi generate fromTemplate asyncapi.yaml @asyncapi/html-template --param version=1.0.0 singleFile=true --output ./docs --force-write'
];
static flags = {
help: Flags.help({ char: 'h' }),
'disable-hook': Flags.string({
char: 'd',
description: 'Disable a specific hook type or hooks from a given hook type',
multiple: true
}),
'no-interactive': Flags.boolean({
description: 'Disable interactive mode and run with the provided flags.',
required: false,
default: false,
}),
install: Flags.boolean({
char: 'i',
default: false,
description: 'Installs the template and its dependencies (defaults to false)'
}),
debug: Flags.boolean({
description: 'Enable more specific errors in the console'
}),
'no-overwrite': Flags.string({
char: 'n',
multiple: true,
description: 'Glob or path of the file(s) to skip when regenerating'
}),
output: Flags.string({
char: 'o',
description: 'Directory where to put the generated files (defaults to current directory)',
}),
'force-write': Flags.boolean({
default: false,
description: 'Force writing of the generated files to given directory even if it is a git repo with unstaged files or not empty dir (defaults to false)'
}),
watch: watchFlag(
'Watches the template directory and the AsyncAPI document, and re-generate the files when changes occur. Ignores the output directory.'
),
param: Flags.string({
char: 'p',
description: 'Additional param to pass to templates',
multiple: true
}),
'map-base-url': Flags.string({
description: 'Maps all schema references from base url to local folder'
}),
'registry-url': Flags.string({
default: 'https://registry.npmjs.org',
description: 'Specifies the URL of the private registry for fetching templates and dependencies'
}),
'registry-auth': Flags.string({
description: 'The registry username and password encoded with base64, formatted as username:password'
}),
'registry-token': Flags.string({
description: 'The npm registry authentication token, that can be passed instead of base64 encoded username and password'
})
};
static args = {
asyncapi: Args.string({description: '- Local path, url or context-name pointing to AsyncAPI file', required: true}),
template: Args.string({description: '- Name of the generator template like for example @asyncapi/html-template or https://github.com/asyncapi/html-template', required: true}),
};
parser = new Parser();
async run() {
const { args, flags } = await this.parse(Template); // NOSONAR
const interactive = !flags['no-interactive'];
let { asyncapi, template } = args;
let output = flags.output as string;
if (interactive) {
intro(inverse('AsyncAPI Generator'));
const parsedArgs = await this.parseArgs(args, output);
asyncapi = parsedArgs.asyncapi;
template = parsedArgs.template;
output = parsedArgs.output;
}
const parsedFlags = this.parseFlags(flags['disable-hook'], flags['param'], flags['map-base-url'], flags['registry.url'], flags['registry.auth'], flags['registry.token']);
const options = {
forceWrite: flags['force-write'],
install: flags.install,
debug: flags.debug,
templateParams: parsedFlags.params,
noOverwriteGlobs: flags['no-overwrite'],
mapBaseUrlToFolder: parsedFlags.mapBaseUrlToFolder,
disabledHooks: parsedFlags.disableHooks,
registry: {
url: flags['registry-url'],
auth: flags['registry-auth'],
token: flags['registry-token']
}
};
const asyncapiInput = (await load(asyncapi)) || (await load());
this.specFile = asyncapiInput;
this.metricsMetadata.template = template;
const watchTemplate = flags['watch'];
const genOption: any = {};
if (flags['map-base-url']) {
genOption.resolve = {resolve: this.getMapBaseUrlToFolderResolver(parsedFlags.mapBaseUrlToFolder)};
}
if (asyncapiInput.isAsyncAPI3()) {
const v3IssueLink = verifyTemplateSupportForV3(template);
if (v3IssueLink !== undefined) {
this.error(`${template} template does not support AsyncAPI v3 documents, please checkout ${v3IssueLink}`);
}
}
await this.generate(asyncapi, template, output, options, genOption, interactive);
if (watchTemplate) {
const watcherHandler = this.watcherHandler(asyncapi, template, output, options, genOption, interactive);
await this.runWatchMode(asyncapi, template, output, watcherHandler);
}
}
private async parseArgs(args: Record<string, any>, output?: string): Promise<{ asyncapi: string; template: string; output: string; }> {
let asyncapi = args['asyncapi'];
let template = args['template'];
const cancellationMessage = 'Operation cancelled';
if (!asyncapi) {
asyncapi = await text({
message: 'Please provide the path to the AsyncAPI document',
placeholder: 'asyncapi.yaml',
defaultValue: 'asyncapi.yaml',
validate(value: string) {
if (!value) {
return 'The path to the AsyncAPI document is required';
} else if (!fs.existsSync(value)) {
return 'The file does not exist';
}
}
});
}
if (isCancel(asyncapi)) {
this.error(cancellationMessage, { exit: 1 });
}
if (!template) {
template = await text({
message: 'Please provide the name of the generator template',
placeholder: '@asyncapi/html-template',
defaultValue: '@asyncapi/html-template',
});
}
if (!output) {
output = await text({
message: 'Please provide the output directory',
placeholder: './docs',
validate(value: string) {
if (!value) {
return 'The output directory is required';
} else if (typeof value !== 'string') {
return 'The output directory must be a string';
}
}
}) as string;
}
if (isCancel(output) || isCancel(template)) {
this.error(cancellationMessage, { exit: 1 });
}
return { asyncapi, template, output };
}
private parseFlags(disableHooks?: string[], params?: string[], mapBaseUrl?: string, registryUrl?: string, registryAuth?:string, registryToken?:string): ParsedFlags {
return {
params: this.paramParser(params),
disableHooks: this.disableHooksParser(disableHooks),
mapBaseUrlToFolder: this.mapBaseURLParser(mapBaseUrl),
registryURLValidation: this.registryURLParser(registryUrl),
registryAuthentication: this.registryValidation(registryUrl, registryAuth, registryToken)
} as ParsedFlags;
}
private registryURLParser(input?:string) {
if (!input) { return; }
const isURL = /^https?:/;
if (!isURL.test(input.toLowerCase())) {
throw new Error('Invalid --registry-url flag. The param requires a valid http/https url.');
}
}
private async registryValidation(registryUrl?:string, registryAuth?:string, registryToken?:string) {
if (!registryUrl) { return; }
try {
const response = await fetch(registryUrl as string);
if (response.status === 401 && !registryAuth && !registryToken) {
this.error('You Need to pass either registryAuth in username:password encoded in Base64 or need to pass registryToken', { exit: 1 });
}
} catch (error: any) {
this.error(`Can't fetch registryURL: ${registryUrl}`, { exit: 1 });
}
}
private paramParser(inputs?: string[]) {
if (!inputs) { return {}; }
const params: Record<string, any> = {};
for (const input of inputs) {
if (!input.includes('=')) { throw new Error(`Invalid param ${input}. It must be in the format of --param name1=value1 name2=value2 `); }
const [paramName, paramValue] = input.split(/=(.+)/, 2);
params[String(paramName)] = paramValue;
}
return params;
}
private disableHooksParser(inputs?: string[]) {
if (!inputs) { return {}; }
const disableHooks: Record<string, any> = {};
for (const input of inputs) {
const [hookType, hookNames] = input.split(/=/);
if (!hookType) { throw new Error('Invalid --disable-hook flag. It must be in the format of: --disable-hook <hookType> or --disable-hook <hookType>=<hookName1>,<hookName2>,...'); }
if (hookNames) {
disableHooks[String(hookType)] = hookNames.split(',');
} else {
disableHooks[String(hookType)] = true;
}
}
return disableHooks;
}
private mapBaseURLParser(input?: string) {
if (!input) { return; }
const mapBaseURLToFolder: any = {};
const re = /(.*):(.*)/g; // NOSONAR
let mapping: any[] | null = [];
if ((mapping = re.exec(input)) === null || mapping.length !== 3) {
throw new Error('Invalid --map-base-url flag. A mapping <url>:<folder> with delimiter : expected.');
}
mapBaseURLToFolder.url = mapping[1].replace(/\/$/, '');
mapBaseURLToFolder.folder = path.resolve(mapping[2]);
const isURL = /^https?:/;
if (!isURL.test(mapBaseURLToFolder.url.toLowerCase())) {
throw new Error('Invalid --map-base-url flag. The mapping <url>:<folder> requires a valid http/https url and valid folder with delimiter `:`.');
}
return mapBaseURLToFolder;
}
private async generate(asyncapi: string | undefined, template: string, output: string, options: any, genOption: any, interactive = true) {
let specification: Specification;
try {
specification = await load(asyncapi);
} catch (err: any) {
return this.error(
new ValidationError({
type: 'invalid-file',
filepath: asyncapi,
}),
{ exit: 1 },
);
}
const generator = new AsyncAPIGenerator(template, output || path.resolve(os.tmpdir(), 'asyncapi-generator'), options);
const s = interactive ? spinner() : { start: () => null, stop: (string: string) => console.log(string) };
s.start('Generation in progress. Keep calm and wait a bit');
try {
await generator.generateFromString(specification.text(), genOption);
} catch (err: any) {
s.stop('Generation failed');
throw new GeneratorError(err);
}
s.stop(`${yellow('Check out your shiny new generated files at ') + magenta(output) + yellow('.')}\n`);
}
private async runWatchMode(asyncapi: string | undefined, template: string, output: string, watchHandler: ReturnType<typeof this.watcherHandler>) {
const specification = await load(asyncapi);
const watchDir = path.resolve(template);
const outputPath = path.resolve(watchDir, output);
const transpiledTemplatePath = path.resolve(watchDir, AsyncAPIGenerator.TRANSPILED_TEMPLATE_LOCATION);
const ignorePaths = [outputPath, transpiledTemplatePath];
const specificationFile = specification.getFilePath();
// Template name is needed as it is not always a part of the cli commad
// There is a use case that you run generator from a root of the template with `./` path
let templateName = '';
try {
// eslint-disable-next-line
templateName = require(path.resolve(watchDir, 'package.json')).name;
} catch (err: any) {
// intentional
}
let watcher;
if (specificationFile) { // is local AsyncAPI file
this.log(`[WATCHER] Watching for changes in the template directory ${magenta(watchDir)} and in the AsyncAPI file ${magenta(specificationFile)}`);
watcher = new Watcher([specificationFile, watchDir], ignorePaths);
} else {
this.log(`[WATCHER] Watching for changes in the template directory ${magenta(watchDir)}`);
watcher = new Watcher(watchDir, ignorePaths);
}
// Must check template in its installation path in generator to use isLocalTemplate function
if (!await isLocalTemplate(path.resolve(AsyncAPIGenerator.DEFAULT_TEMPLATES_DIR, templateName))) {
this.warn(`WARNING: ${template} is a remote template. Changes may be lost on subsequent installations.`);
}
await watcher.watch(watchHandler, (paths: any) => {
this.error(`[WATCHER] Could not find the file path ${paths}, are you sure it still exists? If it has been deleted or moved please rerun the generator.`, {
exit: 1,
});
});
}
private watcherHandler(asyncapi: string, template: string, output: string, options: Record<string, any>, genOption: any, interactive: boolean): (changedFiles: Record<string, any>) => Promise<void> {
return async (changedFiles: Record<string, any>): Promise<void> => {
console.clear();
console.log('[WATCHER] Change detected');
for (const [, value] of Object.entries(changedFiles)) {
let eventText;
switch (value.eventType) {
case 'changed':
eventText = green(value.eventType);
break;
case 'removed':
eventText = red(value.eventType);
break;
case 'renamed':
eventText = yellow(value.eventType);
break;
default:
eventText = yellow(value.eventType);
}
this.log(`\t${magenta(value.path)} was ${eventText}`);
}
try {
await this.generate(asyncapi, template, output, options, genOption, interactive);
} catch (err: any) {
throw new GeneratorError(err);
}
};
}
private getMapBaseUrlToFolderResolver = (urlToFolder: IMapBaseUrlToFlag) => {
return {
order: 1,
canRead() {
return true;
},
read(file: any) {
const baseUrl = urlToFolder.url;
const baseDir = urlToFolder.folder;
return new Promise(((resolve, reject) => {
let localpath = file.url;
localpath = localpath.replace(baseUrl,baseDir);
try {
fs.readFile(localpath, (err, data) => {
if (err) {
reject(`Error opening file "${localpath}"`);
} else {
resolve(data);
}
});
} catch (err) {
reject(`Error opening file "${localpath}"`);
}
}));
}
};
};
}