@asyncapi/cli 3.2.0 → 3.3.0

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 (191) hide show
  1. package/assets/create-template/templates/default/package-lock.json +4 -3
  2. package/lib/apps/api/app.d.ts +15 -0
  3. package/lib/apps/api/app.js +89 -0
  4. package/lib/apps/api/configs/development.json +16 -0
  5. package/lib/apps/api/configs/production.json +16 -0
  6. package/lib/apps/api/configs/test.json +16 -0
  7. package/lib/apps/api/constants.d.ts +1 -0
  8. package/lib/apps/api/constants.js +4 -0
  9. package/lib/apps/api/controllers/bundle.controller.d.ts +7 -0
  10. package/lib/apps/api/controllers/bundle.controller.js +44 -0
  11. package/lib/apps/api/controllers/convert.controller.d.ts +11 -0
  12. package/lib/apps/api/controllers/convert.controller.js +69 -0
  13. package/lib/apps/api/controllers/diff.controller.d.ts +7 -0
  14. package/lib/apps/api/controllers/diff.controller.js +42 -0
  15. package/lib/apps/api/controllers/docs.controller.d.ts +6 -0
  16. package/lib/apps/api/controllers/docs.controller.js +24 -0
  17. package/lib/apps/api/controllers/generate.controller.d.ts +22 -0
  18. package/lib/apps/api/controllers/generate.controller.js +176 -0
  19. package/lib/apps/api/controllers/help.controller.d.ts +6 -0
  20. package/lib/apps/api/controllers/help.controller.js +101 -0
  21. package/lib/apps/api/controllers/parse.controller.d.ts +10 -0
  22. package/lib/apps/api/controllers/parse.controller.js +35 -0
  23. package/lib/apps/api/controllers/validate.controller.d.ts +10 -0
  24. package/lib/apps/api/controllers/validate.controller.js +50 -0
  25. package/lib/apps/api/exceptions/problem.exception.d.ts +14 -0
  26. package/lib/apps/api/exceptions/problem.exception.js +10 -0
  27. package/lib/apps/api/index.d.ts +9 -0
  28. package/lib/apps/api/index.js +21 -0
  29. package/lib/apps/api/middlewares/problem.middleware.d.ts +6 -0
  30. package/lib/apps/api/middlewares/problem.middleware.js +27 -0
  31. package/lib/apps/api/middlewares/validation.middleware.d.ts +12 -0
  32. package/lib/apps/api/middlewares/validation.middleware.js +236 -0
  33. package/lib/apps/api/server.d.ts +3 -0
  34. package/lib/apps/api/server.js +19 -0
  35. package/lib/{commands → apps/cli/commands}/bundle.d.ts +1 -1
  36. package/lib/{commands → apps/cli/commands}/bundle.js +3 -3
  37. package/lib/{commands → apps/cli/commands}/config/analytics.d.ts +1 -1
  38. package/lib/{commands → apps/cli/commands}/config/analytics.js +4 -3
  39. package/lib/{commands → apps/cli/commands}/config/context/add.d.ts +1 -1
  40. package/lib/{commands → apps/cli/commands}/config/context/add.js +12 -6
  41. package/lib/{commands → apps/cli/commands}/config/context/current.d.ts +1 -1
  42. package/lib/{commands → apps/cli/commands}/config/context/current.js +4 -4
  43. package/lib/{commands → apps/cli/commands}/config/context/edit.d.ts +1 -1
  44. package/lib/{commands → apps/cli/commands}/config/context/edit.js +12 -6
  45. package/lib/{commands → apps/cli/commands}/config/context/index.d.ts +1 -1
  46. package/lib/{commands → apps/cli/commands}/config/context/index.js +1 -1
  47. package/lib/{commands → apps/cli/commands}/config/context/init.d.ts +1 -1
  48. package/lib/{commands → apps/cli/commands}/config/context/init.js +7 -4
  49. package/lib/{commands → apps/cli/commands}/config/context/list.d.ts +1 -1
  50. package/lib/{commands → apps/cli/commands}/config/context/list.js +4 -4
  51. package/lib/{commands → apps/cli/commands}/config/context/remove.d.ts +1 -1
  52. package/lib/{commands → apps/cli/commands}/config/context/remove.js +8 -5
  53. package/lib/{commands → apps/cli/commands}/config/context/use.d.ts +1 -1
  54. package/lib/{commands → apps/cli/commands}/config/context/use.js +8 -5
  55. package/lib/{commands → apps/cli/commands}/config/index.d.ts +1 -1
  56. package/lib/{commands → apps/cli/commands}/config/index.js +1 -1
  57. package/lib/{commands → apps/cli/commands}/config/versions.d.ts +1 -1
  58. package/lib/{commands → apps/cli/commands}/config/versions.js +2 -2
  59. package/lib/{commands → apps/cli/commands}/convert.d.ts +2 -7
  60. package/lib/apps/cli/commands/convert.js +85 -0
  61. package/lib/{commands → apps/cli/commands}/diff.d.ts +11 -2
  62. package/lib/{commands → apps/cli/commands}/diff.js +85 -31
  63. package/lib/{commands → apps/cli/commands}/format.d.ts +1 -1
  64. package/lib/{commands → apps/cli/commands}/format.js +4 -4
  65. package/lib/{commands → apps/cli/commands}/generate/fromTemplate.d.ts +4 -5
  66. package/lib/{commands → apps/cli/commands}/generate/fromTemplate.js +89 -122
  67. package/lib/{commands → apps/cli/commands}/generate/index.d.ts +1 -1
  68. package/lib/{commands → apps/cli/commands}/generate/index.js +1 -1
  69. package/lib/{commands → apps/cli/commands}/generate/models.d.ts +6 -1
  70. package/lib/{commands → apps/cli/commands}/generate/models.js +48 -9
  71. package/lib/{commands → apps/cli/commands}/new/file.d.ts +1 -1
  72. package/lib/{commands → apps/cli/commands}/new/file.js +11 -8
  73. package/lib/{commands → apps/cli/commands}/new/glee.d.ts +2 -2
  74. package/lib/{commands → apps/cli/commands}/new/glee.js +4 -4
  75. package/lib/{commands → apps/cli/commands}/new/index.d.ts +1 -1
  76. package/lib/{commands → apps/cli/commands}/new/index.js +1 -1
  77. package/lib/{commands → apps/cli/commands}/new/template.d.ts +1 -1
  78. package/lib/{commands → apps/cli/commands}/new/template.js +10 -8
  79. package/lib/{commands → apps/cli/commands}/optimize.d.ts +1 -1
  80. package/lib/{commands → apps/cli/commands}/optimize.js +71 -30
  81. package/lib/{commands → apps/cli/commands}/pretty.d.ts +1 -1
  82. package/lib/{commands → apps/cli/commands}/pretty.js +8 -5
  83. package/lib/apps/cli/commands/start/api.d.ts +11 -0
  84. package/lib/apps/cli/commands/start/api.js +23 -0
  85. package/lib/{commands → apps/cli/commands}/start/index.d.ts +1 -1
  86. package/lib/{commands → apps/cli/commands}/start/index.js +1 -1
  87. package/lib/{commands → apps/cli/commands}/start/preview.d.ts +1 -1
  88. package/lib/{commands → apps/cli/commands}/start/preview.js +9 -6
  89. package/lib/{commands → apps/cli/commands}/start/studio.d.ts +1 -1
  90. package/lib/{commands → apps/cli/commands}/start/studio.js +10 -7
  91. package/lib/{commands → apps/cli/commands}/validate.d.ts +4 -2
  92. package/lib/apps/cli/commands/validate.js +94 -0
  93. package/lib/{core → apps/cli/internal}/base.d.ts +1 -1
  94. package/lib/{core → apps/cli/internal}/base.js +12 -4
  95. package/lib/apps/cli/internal/flags/bundle.flags.js +26 -0
  96. package/lib/apps/cli/internal/flags/config/analytics.flags.js +24 -0
  97. package/lib/{core → apps/cli/internal}/flags/config/context.flags.js +1 -1
  98. package/lib/{core → apps/cli/internal}/flags/convert.flags.js +9 -2
  99. package/lib/{core → apps/cli/internal}/flags/diff.flags.d.ts +1 -1
  100. package/lib/{core → apps/cli/internal}/flags/diff.flags.js +3 -3
  101. package/lib/{core → apps/cli/internal}/flags/generate/fromTemplate.flags.js +12 -12
  102. package/lib/{core → apps/cli/internal}/flags/generate/models.flags.js +2 -2
  103. package/lib/{core → apps/cli/internal}/flags/global.flags.js +1 -1
  104. package/lib/{core → apps/cli/internal}/flags/new/file.flags.js +7 -2
  105. package/lib/{core → apps/cli/internal}/flags/optimize.flags.js +24 -4
  106. package/lib/apps/cli/internal/flags/parser.flags.d.ts +10 -0
  107. package/lib/apps/cli/internal/flags/parser.flags.js +28 -0
  108. package/lib/{core → apps/cli/internal}/flags/proxy.flags.js +3 -3
  109. package/lib/apps/cli/internal/flags/start/api.flags.d.ts +5 -0
  110. package/lib/apps/cli/internal/flags/start/api.flags.js +20 -0
  111. package/lib/apps/cli/internal/flags/start/preview.flags.js +31 -0
  112. package/lib/{core → apps/cli/internal}/flags/start/studio.flags.js +9 -2
  113. package/lib/{core → apps/cli/internal}/flags/validate.flags.d.ts +1 -1
  114. package/lib/{core → apps/cli/internal}/flags/validate.flags.js +2 -2
  115. package/lib/{core → apps/cli/internal}/globals.d.ts +1 -1
  116. package/lib/{core → apps/cli/internal}/globals.js +2 -4
  117. package/lib/{core → apps/cli/internal}/hooks/command_not_found/myhook.js +14 -4
  118. package/lib/{core → domains}/models/Context.js +1 -1
  119. package/lib/{core → domains}/models/Preview.js +35 -19
  120. package/lib/{core → domains}/models/SpecificationFile.d.ts +2 -2
  121. package/lib/{core → domains}/models/SpecificationFile.js +8 -5
  122. package/lib/{core → domains}/models/Studio.js +4 -4
  123. package/lib/domains/services/archiver.service.d.ts +17 -0
  124. package/lib/domains/services/archiver.service.js +53 -0
  125. package/lib/domains/services/base.service.d.ts +6 -0
  126. package/lib/domains/services/base.service.js +26 -0
  127. package/lib/domains/services/convert.service.d.ts +12 -0
  128. package/lib/domains/services/convert.service.js +65 -0
  129. package/lib/domains/services/generator.service.d.ts +15 -0
  130. package/lib/domains/services/generator.service.js +95 -0
  131. package/lib/domains/services/validation.service.d.ts +54 -0
  132. package/lib/domains/services/validation.service.js +288 -0
  133. package/lib/{core/errors → errors}/specification-file.js +1 -1
  134. package/lib/{core/errors → errors}/validation-error.js +6 -5
  135. package/lib/interfaces/index.d.ts +87 -0
  136. package/lib/interfaces/index.js +7 -0
  137. package/lib/utils/ajv.d.ts +2 -0
  138. package/lib/utils/ajv.js +18 -0
  139. package/lib/utils/app-openapi.d.ts +4 -0
  140. package/lib/utils/app-openapi.js +28 -0
  141. package/lib/{core/utils/generator.js → utils/fileWatcher.js} +8 -2
  142. package/lib/utils/logger.d.ts +6 -0
  143. package/lib/utils/logger.js +33 -0
  144. package/lib/utils/retrieve-language.d.ts +1 -0
  145. package/lib/utils/retrieve-language.js +9 -0
  146. package/lib/utils/temp-dir.d.ts +2 -0
  147. package/lib/utils/temp-dir.js +25 -0
  148. package/oclif.manifest.json +109 -1
  149. package/package.json +36 -10
  150. package/lib/commands/convert.js +0 -132
  151. package/lib/commands/validate.js +0 -47
  152. package/lib/core/flags/bundle.flags.js +0 -14
  153. package/lib/core/flags/config/analytics.flags.js +0 -13
  154. package/lib/core/flags/start/preview.flags.js +0 -15
  155. package/lib/core/parser.d.ts +0 -35
  156. package/lib/core/parser.js +0 -230
  157. /package/lib/{core → apps/cli/internal}/flags/bundle.flags.d.ts +0 -0
  158. /package/lib/{core → apps/cli/internal}/flags/config/analytics.flags.d.ts +0 -0
  159. /package/lib/{core → apps/cli/internal}/flags/config/context.flags.d.ts +0 -0
  160. /package/lib/{core → apps/cli/internal}/flags/convert.flags.d.ts +0 -0
  161. /package/lib/{core → apps/cli/internal}/flags/format.flags.d.ts +0 -0
  162. /package/lib/{core → apps/cli/internal}/flags/format.flags.js +0 -0
  163. /package/lib/{core → apps/cli/internal}/flags/generate/fromTemplate.flags.d.ts +0 -0
  164. /package/lib/{core → apps/cli/internal}/flags/generate/models.flags.d.ts +0 -0
  165. /package/lib/{core → apps/cli/internal}/flags/global.flags.d.ts +0 -0
  166. /package/lib/{core → apps/cli/internal}/flags/new/file.flags.d.ts +0 -0
  167. /package/lib/{core → apps/cli/internal}/flags/new/glee.flags.d.ts +0 -0
  168. /package/lib/{core → apps/cli/internal}/flags/new/glee.flags.js +0 -0
  169. /package/lib/{core → apps/cli/internal}/flags/new/template.flags.d.ts +0 -0
  170. /package/lib/{core → apps/cli/internal}/flags/new/template.flags.js +0 -0
  171. /package/lib/{core → apps/cli/internal}/flags/optimize.flags.d.ts +0 -0
  172. /package/lib/{core → apps/cli/internal}/flags/pretty.flags.d.ts +0 -0
  173. /package/lib/{core → apps/cli/internal}/flags/pretty.flags.js +0 -0
  174. /package/lib/{core → apps/cli/internal}/flags/proxy.flags.d.ts +0 -0
  175. /package/lib/{core → apps/cli/internal}/flags/start/preview.flags.d.ts +0 -0
  176. /package/lib/{core → apps/cli/internal}/flags/start/studio.flags.d.ts +0 -0
  177. /package/lib/{core → apps/cli/internal}/hooks/command_not_found/myhook.d.ts +0 -0
  178. /package/lib/{core → domains}/models/Context.d.ts +0 -0
  179. /package/lib/{core → domains}/models/Preview.d.ts +0 -0
  180. /package/lib/{core → domains}/models/Studio.d.ts +0 -0
  181. /package/lib/{core/errors → errors}/context-error.d.ts +0 -0
  182. /package/lib/{core/errors → errors}/context-error.js +0 -0
  183. /package/lib/{core/errors → errors}/diff-error.d.ts +0 -0
  184. /package/lib/{core/errors → errors}/diff-error.js +0 -0
  185. /package/lib/{core/errors → errors}/generator-error.d.ts +0 -0
  186. /package/lib/{core/errors → errors}/generator-error.js +0 -0
  187. /package/lib/{core/errors → errors}/specification-file.d.ts +0 -0
  188. /package/lib/{core/errors → errors}/validation-error.d.ts +0 -0
  189. /package/lib/{core/utils/generator.d.ts → utils/fileWatcher.d.ts} +0 -0
  190. /package/lib/{core/utils → utils}/scoreCalculator.d.ts +0 -0
  191. /package/lib/{core/utils → utils}/scoreCalculator.js +0 -0
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DEFAULT_PORT = void 0;
4
4
  exports.startPreview = startPreview;
5
5
  const tslib_1 = require("tslib");
6
- const specification_file_1 = require("../errors/specification-file");
6
+ const specification_file_1 = require("../../errors/specification-file");
7
7
  const fs_1 = require("fs");
8
8
  const bundler_1 = tslib_1.__importDefault(require("@asyncapi/bundler"));
9
9
  const http_1 = require("http");
@@ -30,11 +30,13 @@ function startPreview(filePath, base, baseDirectory, xOrigin, suppressLogs, port
30
30
  throw new specification_file_1.SpecificationFileNotFound(filePath);
31
31
  }
32
32
  const baseDir = path_1.default.dirname(path_1.default.resolve(filePath));
33
- (0, bundler_1.default)(filePath).then((doc) => {
33
+ (0, bundler_1.default)(filePath)
34
+ .then((doc) => {
34
35
  if (doc) {
35
36
  bundleError = false;
36
37
  }
37
- }).catch((err) => {
38
+ })
39
+ .catch((err) => {
38
40
  if (suppressLogs) {
39
41
  console.log(defaultErrorMessage);
40
42
  }
@@ -57,13 +59,13 @@ function startPreview(filePath, base, baseDirectory, xOrigin, suppressLogs, port
57
59
  sendQueuedMessages();
58
60
  });
59
61
  wsServer.on('close', (socket) => {
60
- sockets.splice(sockets.findIndex(s => s === socket));
62
+ sockets.splice(sockets.findIndex((s) => s === socket));
61
63
  });
62
64
  app.prepare().then(() => {
63
65
  if (filePath && !bundleError) {
64
66
  messageQueue.push(JSON.stringify({
65
67
  type: 'preview:connected',
66
- code: 'Preview server connected'
68
+ code: 'Preview server connected',
67
69
  }));
68
70
  sendQueuedMessages();
69
71
  findPathsToWatchFromSchemaRef(filePath, baseDir);
@@ -75,14 +77,18 @@ function startPreview(filePath, base, baseDirectory, xOrigin, suppressLogs, port
75
77
  base,
76
78
  baseDir: baseDirectory,
77
79
  xOrigin,
78
- }).then((intitalDocument) => {
80
+ })
81
+ .then((intitalDocument) => {
79
82
  messageQueue.push(JSON.stringify({
80
83
  type: 'preview:file:added',
81
- code: (path_1.default.extname(filePath) === '.yaml' || path_1.default.extname(filePath) === '.yml') ?
82
- intitalDocument.yml() : intitalDocument.string()
84
+ code: path_1.default.extname(filePath) === '.yaml' ||
85
+ path_1.default.extname(filePath) === '.yml'
86
+ ? intitalDocument.yml()
87
+ : intitalDocument.string(),
83
88
  }));
84
89
  sendQueuedMessages();
85
- }).catch((e) => {
90
+ })
91
+ .catch((e) => {
86
92
  if (suppressLogs) {
87
93
  console.log(defaultErrorMessage);
88
94
  }
@@ -96,14 +102,18 @@ function startPreview(filePath, base, baseDirectory, xOrigin, suppressLogs, port
96
102
  base,
97
103
  baseDir: baseDirectory,
98
104
  xOrigin,
99
- }).then((modifiedDocument) => {
105
+ })
106
+ .then((modifiedDocument) => {
100
107
  messageQueue.push(JSON.stringify({
101
108
  type: 'preview:file:changed',
102
- code: (path_1.default.extname(filePath) === '.yaml' || path_1.default.extname(filePath) === '.yml') ?
103
- modifiedDocument.yml() : modifiedDocument.string()
109
+ code: path_1.default.extname(filePath) === '.yaml' ||
110
+ path_1.default.extname(filePath) === '.yml'
111
+ ? modifiedDocument.yml()
112
+ : modifiedDocument.string(),
104
113
  }));
105
114
  sendQueuedMessages();
106
- }).catch((error) => {
115
+ })
116
+ .catch((error) => {
107
117
  if (suppressLogs) {
108
118
  console.log(defaultErrorMessage);
109
119
  }
@@ -124,7 +134,8 @@ function startPreview(filePath, base, baseDirectory, xOrigin, suppressLogs, port
124
134
  }
125
135
  const server = (0, http_1.createServer)((req, res) => handle(req, res));
126
136
  server.on('upgrade', (request, socket, head) => {
127
- if (request.url === '/preview-server' && request.headers['origin'] === `http://localhost:${port}`) {
137
+ if (request.url === '/preview-server' &&
138
+ request.headers['origin'] === `http://localhost:${port}`) {
128
139
  console.log('🔗 WebSocket connection established for the preview.');
129
140
  wsServer.handleUpgrade(request, socket, head, (sock) => {
130
141
  wsServer.emit('connection', sock, request);
@@ -136,7 +147,8 @@ function startPreview(filePath, base, baseDirectory, xOrigin, suppressLogs, port
136
147
  }
137
148
  });
138
149
  if (!bundleError) {
139
- server.listen(port, () => {
150
+ server
151
+ .listen(port, () => {
140
152
  const url = `http://localhost:${port}?previewServer=${port}&studio-version=${package_json_1.version}`;
141
153
  console.log(`🎉 Connected to Preview Server running at ${(0, picocolors_1.blueBright)(url)}.`);
142
154
  console.log(`🌐 Open this URL in your web browser: ${(0, picocolors_1.blueBright)(url)}`);
@@ -152,7 +164,8 @@ function startPreview(filePath, base, baseDirectory, xOrigin, suppressLogs, port
152
164
  if (!bundleError) {
153
165
  (0, open_1.default)(url);
154
166
  }
155
- }).on('error', (error) => {
167
+ })
168
+ .on('error', (error) => {
156
169
  console.error(`Failed to start server on port ${port}:`, error.message);
157
170
  });
158
171
  }
@@ -167,9 +180,12 @@ function sendQueuedMessages() {
167
180
  }
168
181
  }
169
182
  function isLocalRefAPath(key, value) {
170
- return (typeof value === 'string' && key === '$ref' &&
171
- (value.startsWith('.') || value.startsWith('./') ||
172
- value.startsWith('../') || !value.startsWith('#')));
183
+ return (typeof value === 'string' &&
184
+ key === '$ref' &&
185
+ (value.startsWith('.') ||
186
+ value.startsWith('./') ||
187
+ value.startsWith('../') ||
188
+ !value.startsWith('#')));
173
189
  }
174
190
  function findPathsToWatchFromSchemaRef(filePath, baseDir) {
175
191
  if (filePath && !isValidFilePath(filePath)) {
@@ -1,4 +1,4 @@
1
- import { fileFormat } from 'core/flags/format.flags';
1
+ import { fileFormat } from '../../apps/cli/internal/flags/format.flags';
2
2
  export declare class Specification {
3
3
  private readonly spec;
4
4
  private readonly filePath?;
@@ -13,7 +13,7 @@ export declare class Specification {
13
13
  text(): string;
14
14
  getFilePath(): string | undefined;
15
15
  getFileURL(): string | undefined;
16
- getKind(): "file" | "url" | undefined;
16
+ getKind(): "url" | "file" | undefined;
17
17
  getSource(): string | undefined;
18
18
  toSourceString(): string;
19
19
  static fromFile(filepath: string): Promise<Specification>;
@@ -14,14 +14,14 @@ const path_1 = tslib_1.__importDefault(require("path"));
14
14
  const url_1 = require("url");
15
15
  const js_yaml_1 = tslib_1.__importDefault(require("js-yaml"));
16
16
  const Context_1 = require("./Context");
17
- const specification_file_1 = require("../errors/specification-file");
18
- const context_error_1 = require("../errors/context-error");
17
+ const specification_file_1 = require("../../errors/specification-file");
18
+ const context_error_1 = require("../../errors/context-error");
19
19
  const https_proxy_agent_1 = require("https-proxy-agent");
20
20
  const { readFile, lstat } = fs_1.promises;
21
21
  const allowedFileNames = [
22
22
  'asyncapi.json',
23
23
  'asyncapi.yml',
24
- 'asyncapi.yaml'
24
+ 'asyncapi.yaml',
25
25
  ];
26
26
  const TYPE_CONTEXT_NAME = 'context-name';
27
27
  const TYPE_FILE_PATH = 'file-path';
@@ -121,7 +121,9 @@ class Specification {
121
121
  console.log(error);
122
122
  throw new specification_file_1.ErrorLoadingSpec('url', targetUrl);
123
123
  }
124
- return new Specification(yield (response === null || response === void 0 ? void 0 : response.text()), { fileURL: targetUrl });
124
+ return new Specification((yield (response === null || response === void 0 ? void 0 : response.text())), {
125
+ fileURL: targetUrl,
126
+ });
125
127
  });
126
128
  }
127
129
  }
@@ -143,6 +145,7 @@ exports.default = SpecificationFile;
143
145
  /* eslint-disable sonarjs/cognitive-complexity */
144
146
  function load(filePathOrContextName, loadType) {
145
147
  return tslib_1.__awaiter(this, void 0, void 0, function* () {
148
+ // NOSONAR
146
149
  try {
147
150
  if (filePathOrContextName) {
148
151
  if (loadType === null || loadType === void 0 ? void 0 : loadType.file) {
@@ -251,7 +254,7 @@ function detectSpecFile() {
251
254
  // We did our best...
252
255
  }
253
256
  })));
254
- return existingFileNames.find(filename => filename !== undefined);
257
+ return existingFileNames.find((filename) => filename !== undefined);
255
258
  });
256
259
  }
257
260
  function retrieveFileFormat(content) {
@@ -4,7 +4,7 @@ exports.DEFAULT_PORT = void 0;
4
4
  exports.start = start;
5
5
  const tslib_1 = require("tslib");
6
6
  const fs_1 = require("fs");
7
- const specification_file_1 = require("../errors/specification-file");
7
+ const specification_file_1 = require("../../errors/specification-file");
8
8
  const http_1 = require("http");
9
9
  const ws_1 = require("ws");
10
10
  const chokidar_1 = tslib_1.__importDefault(require("chokidar"));
@@ -20,6 +20,7 @@ exports.DEFAULT_PORT = 3210;
20
20
  function isValidFilePath(filePath) {
21
21
  return (0, fs_1.existsSync)(filePath);
22
22
  }
23
+ // eslint-disable-next-line sonarjs/cognitive-complexity
23
24
  function start(filePath, port = exports.DEFAULT_PORT) {
24
25
  if (filePath && !isValidFilePath(filePath)) {
25
26
  throw new specification_file_1.SpecificationFileNotFound(filePath);
@@ -70,7 +71,7 @@ function start(filePath, port = exports.DEFAULT_PORT) {
70
71
  });
71
72
  });
72
73
  wsServer.on('close', (socket) => {
73
- sockets.splice(sockets.findIndex(s => s === socket));
74
+ sockets.splice(sockets.findIndex((s) => s === socket));
74
75
  });
75
76
  app.prepare().then(() => {
76
77
  if (filePath) {
@@ -141,6 +142,5 @@ function getFileContent(filePath) {
141
142
  });
142
143
  }
143
144
  function saveFileContent(filePath, fileContent) {
144
- writeFile(filePath, fileContent, { encoding: 'utf8' })
145
- .catch(console.error);
145
+ writeFile(filePath, fileContent, { encoding: 'utf8' }).catch(console.error);
146
146
  }
@@ -0,0 +1,17 @@
1
+ import archiver, { Archiver } from 'archiver';
2
+ import { Response } from 'express';
3
+ /**
4
+ * Service wrapping the `archiver` module:
5
+ - easier zip creation
6
+ - adding proper `Content-Type` header
7
+ - easier adding an AsyncAPI document to the archive
8
+ - easier stream finalization
9
+ */
10
+ export declare class ArchiverService {
11
+ createZip(res?: Response): archiver.Archiver;
12
+ appendDirectory(archive: Archiver, from: string, to: string): void;
13
+ appendAsyncAPIDocument(archive: Archiver, asyncapi: string, fileName?: string): void;
14
+ finalize(archive: Archiver): Promise<void>;
15
+ createTempDirectory(): Promise<string>;
16
+ removeTempDirectory(tmpDir: string): Promise<void>;
17
+ }
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ArchiverService = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const archiver_1 = tslib_1.__importDefault(require("archiver"));
6
+ const retrieve_language_1 = require("../../utils/retrieve-language");
7
+ const temp_dir_1 = require("../../utils/temp-dir");
8
+ /**
9
+ * Service wrapping the `archiver` module:
10
+ - easier zip creation
11
+ - adding proper `Content-Type` header
12
+ - easier adding an AsyncAPI document to the archive
13
+ - easier stream finalization
14
+ */
15
+ class ArchiverService {
16
+ createZip(res) {
17
+ const zip = (0, archiver_1.default)('zip', { zlib: { level: 9 } });
18
+ if (res) {
19
+ zip.pipe(res);
20
+ res.attachment('asyncapi.zip');
21
+ }
22
+ return zip;
23
+ }
24
+ appendDirectory(archive, from, to) {
25
+ archive.directory(from, to);
26
+ }
27
+ appendAsyncAPIDocument(archive, asyncapi, fileName = 'asyncapi') {
28
+ asyncapi = JSON.stringify(asyncapi);
29
+ const language = (0, retrieve_language_1.retrieveLangauge)(asyncapi);
30
+ if (language === 'yaml') {
31
+ archive.append(asyncapi, { name: `${fileName}.yml` });
32
+ }
33
+ else {
34
+ archive.append(asyncapi, { name: `${fileName}.json` });
35
+ }
36
+ }
37
+ finalize(archive) {
38
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
39
+ yield new Promise((resolve) => {
40
+ // wait for end stream
41
+ archive.on('end', resolve);
42
+ archive.finalize();
43
+ });
44
+ });
45
+ }
46
+ createTempDirectory() {
47
+ return (0, temp_dir_1.createTempDirectory)();
48
+ }
49
+ removeTempDirectory(tmpDir) {
50
+ return (0, temp_dir_1.removeTempDirectory)(tmpDir);
51
+ }
52
+ }
53
+ exports.ArchiverService = ArchiverService;
@@ -0,0 +1,6 @@
1
+ import { ServiceResult } from '../../interfaces';
2
+ export declare abstract class BaseService {
3
+ protected createSuccessResult<T>(data: T): ServiceResult<T>;
4
+ protected createErrorResult(error: string, diagnostics?: any[]): ServiceResult;
5
+ protected handleServiceError(error: any): Promise<ServiceResult>;
6
+ }
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseService = void 0;
4
+ const tslib_1 = require("tslib");
5
+ class BaseService {
6
+ createSuccessResult(data) {
7
+ return {
8
+ success: true,
9
+ data,
10
+ };
11
+ }
12
+ createErrorResult(error, diagnostics) {
13
+ return {
14
+ success: false,
15
+ error,
16
+ diagnostics,
17
+ };
18
+ }
19
+ handleServiceError(error) {
20
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
21
+ const errorMessage = error instanceof Error ? error.message : String(error);
22
+ return this.createErrorResult(errorMessage);
23
+ });
24
+ }
25
+ }
26
+ exports.BaseService = BaseService;
@@ -0,0 +1,12 @@
1
+ import { ConversionOptions, ConversionResult, ServiceResult } from '../../interfaces';
2
+ import { Specification } from '../models/SpecificationFile';
3
+ import { BaseService } from './base.service';
4
+ export declare class ConversionService extends BaseService {
5
+ /**
6
+ * Handles the conversion of AsyncAPI, Postman or OpenAPI documents based on the provided flags.
7
+ */
8
+ convertDocument(specFile: Specification, options: ConversionOptions): Promise<ServiceResult<ConversionResult>>;
9
+ handleLogging(specFile: Specification, flags: ConversionOptions): string;
10
+ private formatConvertedFile;
11
+ handleOutput(outputPath: string, convertedFileFormatted: string): Promise<void>;
12
+ }
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConversionService = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const base_service_1 = require("./base.service");
6
+ const converter_1 = require("@asyncapi/converter");
7
+ const picocolors_1 = require("picocolors");
8
+ const fs_1 = require("fs");
9
+ class ConversionService extends base_service_1.BaseService {
10
+ /**
11
+ * Handles the conversion of AsyncAPI, Postman or OpenAPI documents based on the provided flags.
12
+ */
13
+ convertDocument(specFile, options) {
14
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
15
+ var _a, _b, _c;
16
+ let convertedDocument;
17
+ switch (options.format) {
18
+ case 'asyncapi':
19
+ convertedDocument = (0, converter_1.convert)((_a = specFile.text()) !== null && _a !== void 0 ? _a : '', options['target-version'] || '3.0.0');
20
+ break;
21
+ case 'openapi':
22
+ convertedDocument = (0, converter_1.convertOpenAPI)((_b = specFile.text()) !== null && _b !== void 0 ? _b : '', specFile.toJson().openapi, {
23
+ perspective: options.perspective,
24
+ });
25
+ break;
26
+ case 'postman-collection':
27
+ convertedDocument = (0, converter_1.convertPostman)((_c = specFile.text()) !== null && _c !== void 0 ? _c : '', '3.0.0', {
28
+ perspective: options.perspective,
29
+ });
30
+ break;
31
+ default:
32
+ return this.createErrorResult(`Unsupported conversion format: ${options.format}`);
33
+ }
34
+ return this.createSuccessResult({
35
+ convertedDocument: this.formatConvertedFile(convertedDocument),
36
+ originalFormat: options.format,
37
+ });
38
+ });
39
+ }
40
+ handleLogging(specFile, flags) {
41
+ const sourcePath = specFile.getFilePath() || specFile.getFileURL();
42
+ const targetVersion = flags['target-version'] || 'latest';
43
+ const outputMap = {
44
+ asyncapi: 'AsyncAPI document',
45
+ openapi: 'OpenAPI document',
46
+ 'postman-collection': 'Postman Collection',
47
+ };
48
+ return `🎉 The ${outputMap[flags.format]} from ${(0, picocolors_1.cyan)(sourcePath)} has been successfully converted to AsyncAPI version ${(0, picocolors_1.green)(targetVersion)}!!`;
49
+ }
50
+ // Helper function to format the converted file
51
+ formatConvertedFile(convertedFile) {
52
+ return typeof convertedFile === 'object'
53
+ ? JSON.stringify(convertedFile, null, 4)
54
+ : convertedFile;
55
+ }
56
+ // Helper function to handle output
57
+ handleOutput(outputPath, convertedFileFormatted) {
58
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
59
+ yield fs_1.promises.writeFile(`${outputPath}`, convertedFileFormatted, {
60
+ encoding: 'utf8',
61
+ });
62
+ });
63
+ }
64
+ }
65
+ exports.ConversionService = ConversionService;
@@ -0,0 +1,15 @@
1
+ import { GenerationOptions, GenerationResult, ServiceResult } from '../../interfaces';
2
+ import { Specification } from '../models/SpecificationFile';
3
+ import { BaseService } from './base.service';
4
+ export declare class GeneratorService extends BaseService {
5
+ private defaultInteractive;
6
+ constructor(interactive?: boolean);
7
+ private templatesNotSupportingV3;
8
+ /**
9
+ * Verify that a given template support v3, if not, return the link to the issue that needs to be solved.
10
+ */
11
+ private verifyTemplateSupportForV3;
12
+ private checkV3NotSupported;
13
+ generate(asyncapi: Specification, template: string, output: string, options: GenerationOptions, genOption: any, interactive?: boolean): Promise<ServiceResult<GenerationResult>>;
14
+ generateUsingNewGenerator(asyncapi: Specification, template: string, output: string, options: any, genOption: any): Promise<ServiceResult<GenerationResult>>;
15
+ }
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GeneratorService = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const base_service_1 = require("./base.service");
6
+ const generator_1 = tslib_1.__importDefault(require("@asyncapi/generator"));
7
+ const generator_v2_1 = tslib_1.__importDefault(require("generator-v2"));
8
+ const prompts_1 = require("@clack/prompts");
9
+ const path_1 = tslib_1.__importDefault(require("path"));
10
+ const os_1 = tslib_1.__importDefault(require("os"));
11
+ const picocolors_1 = require("picocolors");
12
+ class GeneratorService extends base_service_1.BaseService {
13
+ constructor(interactive = false) {
14
+ super();
15
+ this.templatesNotSupportingV3 = {
16
+ '@asyncapi/minimaltemplate': 'some link', // For testing purpose
17
+ '@asyncapi/dotnet-nats-template': 'https://github.com/asyncapi/dotnet-nats-template/issues/384',
18
+ '@asyncapi/ts-nats-template': 'https://github.com/asyncapi/ts-nats-template/issues/545',
19
+ '@asyncapi/python-paho-template': 'https://github.com/asyncapi/python-paho-template/issues/189',
20
+ '@asyncapi/nodejs-ws-template': 'https://github.com/asyncapi/nodejs-ws-template/issues/294',
21
+ '@asyncapi/java-spring-cloud-stream-template': 'https://github.com/asyncapi/java-spring-cloud-stream-template/issues/336',
22
+ '@asyncapi/go-watermill-template': 'https://github.com/asyncapi/go-watermill-template/issues/243',
23
+ '@asyncapi/java-spring-template': 'https://github.com/asyncapi/java-spring-template/issues/308',
24
+ '@asyncapi/php-template': 'https://github.com/asyncapi/php-template/issues/191',
25
+ };
26
+ this.defaultInteractive = interactive;
27
+ }
28
+ /**
29
+ * Verify that a given template support v3, if not, return the link to the issue that needs to be solved.
30
+ */
31
+ verifyTemplateSupportForV3(template) {
32
+ if (this.templatesNotSupportingV3[`${template}`] !== undefined) {
33
+ return this.templatesNotSupportingV3[`${template}`];
34
+ }
35
+ return undefined;
36
+ }
37
+ checkV3NotSupported(asyncapi, template) {
38
+ if (asyncapi.isAsyncAPI3()) {
39
+ const v3IssueLink = this.verifyTemplateSupportForV3(template);
40
+ if (v3IssueLink !== undefined) {
41
+ return `${template} template does not support AsyncAPI v3 documents, please checkout ${v3IssueLink}`;
42
+ }
43
+ }
44
+ }
45
+ generate(asyncapi_1, template_1, output_1, options_1, genOption_1) {
46
+ return tslib_1.__awaiter(this, arguments, void 0, function* (asyncapi, template, output, options, genOption, interactive = this.defaultInteractive) {
47
+ const v3NotSupported = this.checkV3NotSupported(asyncapi, template);
48
+ if (v3NotSupported) {
49
+ return this.createErrorResult(v3NotSupported);
50
+ }
51
+ const generator = new generator_1.default(template, output || path_1.default.resolve(os_1.default.tmpdir(), 'asyncapi-generator'), options);
52
+ const s = interactive
53
+ ? (0, prompts_1.spinner)()
54
+ : { start: () => null, stop: (string) => console.log(string) };
55
+ s.start('Generation in progress. Keep calm and wait a bit');
56
+ try {
57
+ yield generator.generateFromString(asyncapi.text(), Object.assign(Object.assign({}, genOption), { path: asyncapi }));
58
+ }
59
+ catch (err) {
60
+ console.log(err);
61
+ s.stop('Generation failed');
62
+ return this.createErrorResult(err.message, err.diagnostics);
63
+ }
64
+ s.stop(`${(0, picocolors_1.yellow)('Check out your shiny new generated files at ') + (0, picocolors_1.magenta)(output) + (0, picocolors_1.yellow)('.')}\n`);
65
+ return this.createSuccessResult({
66
+ success: true,
67
+ outputPath: output,
68
+ });
69
+ });
70
+ }
71
+ generateUsingNewGenerator(asyncapi, template, output, options, genOption) {
72
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
73
+ const v3NotSupported = this.checkV3NotSupported(asyncapi, template);
74
+ if (v3NotSupported) {
75
+ return this.createErrorResult(v3NotSupported);
76
+ }
77
+ const logs = [];
78
+ const generator = new generator_v2_1.default(template, output || path_1.default.resolve(os_1.default.tmpdir(), 'asyncapi-generator'), options);
79
+ try {
80
+ yield generator.generateFromString(asyncapi.text(), Object.assign(Object.assign({}, genOption), { path: asyncapi }));
81
+ }
82
+ catch (err) {
83
+ logs.push('Generation failed');
84
+ return this.createErrorResult(err.message, err.diagnostics);
85
+ }
86
+ logs.push(`${(0, picocolors_1.yellow)('Check out your shiny new generated files at ') + (0, picocolors_1.magenta)(output) + (0, picocolors_1.yellow)('.')}\n`);
87
+ return this.createSuccessResult({
88
+ success: true,
89
+ outputPath: output,
90
+ logs,
91
+ });
92
+ });
93
+ }
94
+ }
95
+ exports.GeneratorService = GeneratorService;
@@ -0,0 +1,54 @@
1
+ import { BaseService } from './base.service';
2
+ import { ValidationOptions, ValidationResult, ServiceResult, ParsedDocument, DiagnosticsFormat, SeverityKind } from '../../interfaces';
3
+ import type { Diagnostic } from '@asyncapi/parser/cjs';
4
+ import { Specification } from '../models/SpecificationFile';
5
+ import { ParseOptions } from '@asyncapi/parser';
6
+ import { ParserOptions } from '@asyncapi/parser/cjs/parser';
7
+ export declare enum ValidationStatus {
8
+ INVALID = "invalid",
9
+ VALID = "valid"
10
+ }
11
+ export declare class ValidationService extends BaseService {
12
+ private parser;
13
+ constructor(parserOptions?: ParserOptions);
14
+ /**
15
+ * Determine validation status from diagnostics
16
+ */
17
+ private determineDiagnosticsStatus;
18
+ /**
19
+ * Parses an AsyncAPI document and returns the parsed result
20
+ */
21
+ parseDocument(specFile: Specification, parseOptions?: ParseOptions, options?: ValidationOptions): Promise<ServiceResult<ParsedDocument>>;
22
+ /**
23
+ * Validates an AsyncAPI document
24
+ */
25
+ validateDocument(specFile: Specification, options?: ValidationOptions): Promise<ServiceResult<ValidationResult>>;
26
+ /**
27
+ * Helper to build and register a custom parser with suppressed rules
28
+ */
29
+ private buildAndRegisterCustomParser;
30
+ /**
31
+ * Save validation diagnostics to file
32
+ */
33
+ saveDiagnosticsToFile(outputPath: string, format: DiagnosticsFormat, formatOutput: string): Promise<ServiceResult<string>>;
34
+ /**
35
+ * Generate governance message based on validation results
36
+ */
37
+ generateGovernanceMessage(sourceString: string, hasIssues: boolean, isFailSeverity: boolean): string;
38
+ /**
39
+ * Check if diagnostics contain failure severity issues
40
+ */
41
+ private hasFailSeverity;
42
+ /**
43
+ * Format validation diagnostics output
44
+ */
45
+ formatDiagnosticsOutput(diagnostics: Diagnostic[], format?: DiagnosticsFormat, failSeverity?: SeverityKind): string;
46
+ /**
47
+ * Format diagnostics in stylish format with severity grouping
48
+ */
49
+ private formatStylish;
50
+ /**
51
+ * Get colored severity title
52
+ */
53
+ private getSeverityTitle;
54
+ }