@avtechno/sfr 1.0.13 → 1.0.15

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.
@@ -0,0 +1,33 @@
1
+ import Joi from "joi";
2
+ import { REST } from "./templates.mjs";
3
+ export default REST({
4
+ cfg: {
5
+ base_dir: "example",
6
+ public: false,
7
+ },
8
+ validators: {
9
+ "get-something": {
10
+ "name": Joi.string().required(),
11
+ "age": Joi.number().required(),
12
+ }
13
+ },
14
+ handlers: {
15
+ GET: {
16
+ "get-something": {
17
+ description: "Get something I guess?",
18
+ async fn(req, res) {
19
+ const result = await this.db_call();
20
+ res.status(200).json({
21
+ data: result
22
+ });
23
+ }
24
+ }
25
+ }
26
+ },
27
+ controllers: {
28
+ async db_call() {
29
+ /* Perform database calls here through accessing the "this" context (if injections are set) */
30
+ return "Something";
31
+ }
32
+ }
33
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,84 @@
1
+ /// <reference path="types/index.d.ts" />
2
+ import yaml from "js-yaml";
3
+ import path from "path";
4
+ import fs from "fs/promises";
5
+ import { REST, WS, MQ } from "./templates.mjs";
6
+ import { SFRPipeline } from "./sfr-pipeline.mjs";
7
+ import { MQLib, BroadcastMQ, TargetedMQ } from "./mq.mjs";
8
+ const cwd = process.cwd();
9
+ export default async (cfg, oas_cfg, connectors, base_url) => {
10
+ //TODO: Verify connectors
11
+ const sfr = new SFRPipeline(cfg, oas_cfg, connectors);
12
+ // Returned service artifacts for both OpenAPI and AsyncAPI are written into the server directory
13
+ // An express static endpoint is pointed to this directory for service directory.
14
+ const documents = await sfr.init(base_url);
15
+ write_service_discovery(cfg, documents); //Writes services to output dir (cfg.out)
16
+ return {
17
+ ...oas_cfg,
18
+ documents
19
+ };
20
+ };
21
+ async function write_service_discovery(cfg, documents) {
22
+ //Setup files in case they do not exist.
23
+ //Setup output folder
24
+ await fs.mkdir(path.join(cwd, cfg.out), { recursive: true });
25
+ // Loop over each protocol
26
+ for (let [protocol, documentation] of Object.entries(documents)) {
27
+ //Strictly await for setup to create dirs for each protocol.
28
+ await fs.mkdir(path.join(cwd, cfg.out, protocol.toLowerCase()), { recursive: true });
29
+ //Convert documentation into service manifest.
30
+ //OpenAPI Documents : paths
31
+ //AsyncAPI Documents : channels
32
+ switch (protocol) {
33
+ case "REST":
34
+ {
35
+ documentation = documentation;
36
+ for (const [path, methods] of Object.entries(documentation.paths)) {
37
+ write_to_file(cfg, `rest/${path}`, methods);
38
+ }
39
+ }
40
+ break;
41
+ case "WS":
42
+ {
43
+ }
44
+ break;
45
+ case "MQ": {
46
+ documentation = documentation;
47
+ write_to_file(cfg, "mq/index.yaml", documentation);
48
+ }
49
+ }
50
+ }
51
+ }
52
+ //Tasked with recursively creating directories and spec files.
53
+ async function write_to_file(cfg, dir, data) {
54
+ //Path is a slash(/) delimited string, with the end delimiter indicating the filename to be used.
55
+ const paths = dir.split("/");
56
+ //Indicates a root file
57
+ if (paths.length === 1) {
58
+ await fs.writeFile(path.join(cwd, cfg.out, paths[0]), yaml.dump(data), { flag: "w+" });
59
+ }
60
+ else { //Indicates a nested file
61
+ const file = paths.pop(); //Pops the path array to be used for dir creation
62
+ await fs.mkdir(path.join(cwd, cfg.out, ...paths), { recursive: true });
63
+ fs.writeFile(path.join(cwd, cfg.out, ...paths, `${file}.yml`), yaml.dump(data), { flag: "w+" });
64
+ }
65
+ }
66
+ function inject(injections) {
67
+ SFRPipeline.injections.rest.handlers = {
68
+ ...SFRPipeline.injections.rest.handlers,
69
+ ...injections.handlers
70
+ };
71
+ SFRPipeline.injections.rest.controllers = {
72
+ ...SFRPipeline.injections.rest.controllers,
73
+ ...injections.controllers
74
+ };
75
+ SFRPipeline.injections.mq.handlers = {
76
+ ...SFRPipeline.injections.mq.handlers,
77
+ ...injections.handlers
78
+ };
79
+ SFRPipeline.injections.mq.controllers = {
80
+ ...SFRPipeline.injections.mq.controllers,
81
+ ...injections.controllers
82
+ };
83
+ }
84
+ export { REST, WS, MQ, MQLib, BroadcastMQ, TargetedMQ, inject };
@@ -0,0 +1,37 @@
1
+ import winston from 'winston';
2
+ // Define log levels
3
+ const levels = {
4
+ error: 0,
5
+ warn: 1,
6
+ info: 2,
7
+ http: 3,
8
+ verbose: 4,
9
+ debug: 5,
10
+ silly: 6,
11
+ };
12
+ // Define colors for each level
13
+ const colors = {
14
+ error: 'red',
15
+ warn: 'yellow',
16
+ info: 'green',
17
+ http: 'magenta',
18
+ verbose: 'cyan',
19
+ debug: 'blue',
20
+ silly: 'gray',
21
+ };
22
+ // Add colors to Winston
23
+ winston.addColors(colors);
24
+ // Define the format for logs
25
+ const format = winston.format.combine(winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' }), winston.format.colorize({ all: true }), winston.format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}${info.metadata ? ` ${JSON.stringify(info.metadata)}` : ''}`));
26
+ // Create the Winston logger
27
+ const logger = winston.createLogger({
28
+ level: process.env.NODE_ENV === 'development' && Boolean(process.env.DEBUG_SFR) ? 'debug' : 'info',
29
+ levels,
30
+ format,
31
+ transports: [
32
+ // Console transport
33
+ new winston.transports.Console(),
34
+ ],
35
+ });
36
+ // Export the logger
37
+ export { logger };
package/dist/mq.mjs ADDED
@@ -0,0 +1,239 @@
1
+ import { connect } from "amqplib";
2
+ /**
3
+ * MQLib class for establishing a connection to the message queue and creating channels.
4
+ */
5
+ export class MQLib {
6
+ connection;
7
+ channel;
8
+ /**
9
+ * Initializes the connection and channel to the message queue.
10
+ *
11
+ * @param MQ_URL - The URL of the message queue.
12
+ * @example
13
+ * const mqLib = new MQLib();
14
+ * await mqLib.init("amqp://localhost");
15
+ */
16
+ async init(MQ_URL) {
17
+ await connect(MQ_URL)
18
+ .then(async (v) => {
19
+ //@ts-ignore
20
+ this.connection = v;
21
+ this.channel = await v.createChannel();
22
+ });
23
+ }
24
+ /**
25
+ * Returns the connection object.
26
+ *
27
+ * @returns The connection object to the message queue.
28
+ */
29
+ get_connection() {
30
+ return this.connection;
31
+ }
32
+ /**
33
+ * Returns the channel object.
34
+ *
35
+ * @returns The channel object to the message queue.
36
+ */
37
+ get_channel() {
38
+ return this.channel;
39
+ }
40
+ }
41
+ export class BaseMQ {
42
+ channel;
43
+ type;
44
+ constructor(channel, type) {
45
+ this.channel = channel;
46
+ this.type = type;
47
+ }
48
+ }
49
+ /**
50
+ * BroadcastMQ class to handle different types of broadcast communication patterns: Fanout, Direct, and Topic.
51
+ */
52
+ export class BroadcastMQ extends BaseMQ {
53
+ channel;
54
+ type;
55
+ exchange_options;
56
+ constructor(channel, type, exchange_options) {
57
+ super(channel, type);
58
+ this.channel = channel;
59
+ this.type = type;
60
+ this.exchange_options = exchange_options;
61
+ this.exchange_options = exchange_options || { durable: false };
62
+ }
63
+ /**
64
+ * Publishes a message to the specified exchange based on the communication pattern.
65
+ *
66
+ * @param exchange - The name of the exchange to send the message to.
67
+ * @param key - The routing key or pattern to use, depending on the communication pattern.
68
+ * @param payload - The message to be sent.
69
+ * @param options - Additional publishing options.
70
+ * @example
71
+ * // Publish a message to a 'logsExchange' with a routing key 'error' for a routing pattern.
72
+ * const mq = new BroadcastMQ(channel, "Direct");
73
+ * mq.publish("logsExchange", "error", { level: "error", message: "Something went wrong" });
74
+ */
75
+ async publish(exchange, key = "", payload, options) {
76
+ switch (this.type) {
77
+ case "Fanout": {
78
+ await this.channel.assertExchange(exchange, "fanout", this.exchange_options);
79
+ this.channel.publish(exchange, key, encode_payload(payload), options);
80
+ break;
81
+ }
82
+ case "Direct": {
83
+ await this.channel.assertExchange(exchange, "direct", this.exchange_options);
84
+ this.channel.publish(exchange, key, encode_payload(payload), options);
85
+ break;
86
+ }
87
+ case "Topic": {
88
+ await this.channel.assertExchange(exchange, "topic", this.exchange_options);
89
+ this.channel.publish(exchange, key, encode_payload(payload), options);
90
+ break;
91
+ }
92
+ }
93
+ }
94
+ /**
95
+ * Subscribes to an exchange to receive messages based on the communication pattern.
96
+ *
97
+ * @param exchange - The name of the exchange to subscribe to.
98
+ * @param key - The routing key or pattern to listen for.
99
+ * @param cfg - Configuration options for the consumer, including the callback function.
100
+ * @param options - Additional consumption options.
101
+ * @example
102
+ * // Subscribe to the 'logsExchange' for all 'error' messages in the Direct pattern.
103
+ * const mq = new BroadcastMQ(channel, "Direct");
104
+ * mq.subscribe("logsExchange", "error", { fn: handleErrorLogs, options: { noAck: true } });
105
+ */
106
+ async subscribe(exchange, key, cfg) {
107
+ let fn = cfg.fn.bind({ channel: this.channel, type: this.type });
108
+ switch (this.type) {
109
+ case "Fanout": {
110
+ await this.channel.assertExchange(exchange, "fanout", this.exchange_options);
111
+ const { queue } = await this.channel.assertQueue("", { exclusive: true });
112
+ this.channel.bindQueue(queue, exchange, "");
113
+ this.channel.consume(queue, (v) => fn(parse_payload(v)), cfg.options);
114
+ break;
115
+ }
116
+ case "Direct": {
117
+ await this.channel.assertExchange(exchange, "direct", this.exchange_options);
118
+ const { queue } = await this.channel.assertQueue("", { exclusive: true });
119
+ await this.channel.bindQueue(queue, exchange, key);
120
+ this.channel.consume(queue, (v) => fn(parse_payload(v)), cfg.options);
121
+ break;
122
+ }
123
+ case "Topic": {
124
+ await this.channel.assertExchange(exchange, "topic", this.exchange_options);
125
+ const { queue } = await this.channel.assertQueue("", { exclusive: true });
126
+ this.channel.bindQueue(queue, exchange, key);
127
+ this.channel.consume(queue, (v) => fn(parse_payload(v)), cfg.options);
128
+ break;
129
+ }
130
+ }
131
+ }
132
+ set_options(options) {
133
+ this.exchange_options = options;
134
+ }
135
+ }
136
+ /**
137
+ * TargetedMQ class to handle Point-to-Point and Request-Reply communication patterns.
138
+ */
139
+ export class TargetedMQ extends BaseMQ {
140
+ channel;
141
+ type;
142
+ queue_options;
143
+ constructor(channel, type, queue_options) {
144
+ super(channel, type);
145
+ this.channel = channel;
146
+ this.type = type;
147
+ this.queue_options = queue_options;
148
+ this.queue_options = queue_options || { durable: true };
149
+ }
150
+ /**
151
+ * Sends a message to the specified queue depending on the communication pattern.
152
+ *
153
+ * @param binding - The name of the queue or binding to send the message to.
154
+ * @param payload - The message to be sent.
155
+ * @param options - Additional publishing options.
156
+ * @example
157
+ * // Send a message to a queue for point-to-point communication
158
+ * const mq = new TargetedMQ(channel, "Point-to-Point");
159
+ * mq.produce("taskQueue", { taskId: 1, action: "process" });
160
+ */
161
+ async produce(binding, payload, options) {
162
+ /* Alter produce strategy depending on the instance's configured comm pattern */
163
+ switch (this.type) {
164
+ case "Point-to-Point": {
165
+ await this.channel.assertQueue(binding, this.queue_options);
166
+ return this.channel.sendToQueue(binding, encode_payload(payload), options);
167
+ }
168
+ case "Request-Reply": {
169
+ await this.channel.assertQueue(binding, this.queue_options);
170
+ return this.channel.sendToQueue(binding, encode_payload(payload), options);
171
+ }
172
+ }
173
+ }
174
+ /**
175
+ * Consumes messages from the specified queue based on the communication pattern.
176
+ *
177
+ * @param queue - The name of the queue to consume messages from.
178
+ * @param cfg - Configuration options for the consumer, including the callback function.
179
+ * @example
180
+ * // Consume a message from the 'taskQueue' in a Point-to-Point communication pattern
181
+ * const mq = new TargetedMQ(channel, "Point-to-Point");
182
+ * mq.consume("taskQueue", { fn: processTask, options: { noAck: true } });
183
+ */
184
+ async consume(queue, cfg) {
185
+ let fn = cfg.fn.bind({ channel: this.channel, type: this.type });
186
+ switch (this.type) {
187
+ case "Point-to-Point": {
188
+ await this.channel.assertQueue(queue, this.queue_options);
189
+ this.channel.consume(queue, (v) => fn(parse_payload(v)), cfg.options);
190
+ break;
191
+ }
192
+ case "Request-Reply": {
193
+ await this.channel.assertQueue(queue, this.queue_options);
194
+ this.channel.consume(queue, (v) => fn(parse_payload(v)), cfg.options);
195
+ break;
196
+ }
197
+ }
198
+ }
199
+ /**
200
+ * Sends a reply to the message sender in a Request-Reply pattern.
201
+ *
202
+ * @param msg - The original message to reply to.
203
+ * @param payload - The reply message to send back to the requester.
204
+ * @example
205
+ * // Send a response back to the client in a Request-Reply pattern
206
+ * const mq = new TargetedMQ(channel, "Request-Reply");
207
+ * mq.reply(msg, { result: "Processed successfully" });
208
+ */
209
+ async reply(msg, payload) {
210
+ if (this.type !== "Request-Reply")
211
+ return;
212
+ this.channel.sendToQueue(msg.properties.replyTo, encode_payload(payload), { correlationId: msg.properties.correlationId });
213
+ this.channel.ack(msg);
214
+ }
215
+ set_options(options) {
216
+ this.queue_options = options;
217
+ }
218
+ }
219
+ /* Helper Functions */
220
+ /**
221
+ * Parses the payload of a message.
222
+ *
223
+ * @param msg - The consumed message.
224
+ * @returns The parsed message content.
225
+ */
226
+ function parse_payload(msg) {
227
+ if (!msg)
228
+ return {};
229
+ return { ...msg, content: JSON.parse(msg.content.toString()) };
230
+ }
231
+ /**
232
+ * Encodes a message as a Buffer to be sent over the message queue.
233
+ *
234
+ * @param msg - The message to be encoded.
235
+ * @returns The encoded message as a Buffer.
236
+ */
237
+ function encode_payload(msg) {
238
+ return Buffer.from(JSON.stringify(msg));
239
+ }
@@ -0,0 +1,454 @@
1
+ import path from "path";
2
+ import fs from "fs/promises";
3
+ import { template } from "./util.mjs";
4
+ import { BroadcastMQ, TargetedMQ } from "./mq.mjs";
5
+ import j2s from "joi-to-swagger";
6
+ import { logger } from "./logger.mjs";
7
+ const CWD = process.cwd();
8
+ const PATTERNS = ["Point-to-Point", "Request-Reply", "Fanout", "Direct", "Topic"];
9
+ const TARGETED_PATTERN = ["Point-to-Point", "Request-Reply"];
10
+ const DEBUG_FLAG = Boolean(process.env.DEBUG_SFR);
11
+ export class SFRPipeline {
12
+ cfg;
13
+ oas_cfg;
14
+ comms;
15
+ base_url;
16
+ pattern_channels;
17
+ mount_data = {
18
+ rest: 0,
19
+ ws: 0,
20
+ mq: 0
21
+ };
22
+ /* Contains values that are injected into each protocol's handlers. */
23
+ static injections = {
24
+ rest: {
25
+ handlers: {},
26
+ controllers: {}
27
+ },
28
+ mq: {
29
+ handlers: {},
30
+ controllers: {}
31
+ },
32
+ };
33
+ constructor(cfg, oas_cfg, comms) {
34
+ this.cfg = cfg;
35
+ this.oas_cfg = oas_cfg;
36
+ this.comms = comms;
37
+ }
38
+ async init(base_url) {
39
+ this.base_url = base_url;
40
+ if (this.comms["MQ"]) {
41
+ //Create channels for each type of Communication Pattern
42
+ const channels = await Promise.all(PATTERNS.map(async (v) => {
43
+ const mq = TARGETED_PATTERN.includes(v) ? new TargetedMQ(this.comms["MQ"], v) : new BroadcastMQ(this.comms["MQ"], v);
44
+ return [v, mq];
45
+ }));
46
+ this.pattern_channels = Object.fromEntries(channels);
47
+ SFRPipeline.injections.rest.handlers = {
48
+ ...SFRPipeline.injections.rest.handlers,
49
+ mq: this.pattern_channels
50
+ };
51
+ SFRPipeline.injections.mq.handlers = {
52
+ ...SFRPipeline.injections.mq.handlers,
53
+ mq: this.pattern_channels
54
+ };
55
+ }
56
+ //Declarations for each protocol in key/value pairs.
57
+ let protocols = await this.file_parsing();
58
+ //Filter protocols that have been parsed if its' associated SFRProtocol has been defined
59
+ /* @ts-ignore */
60
+ protocols = Object.fromEntries(Object.entries(protocols).filter(([k]) => this.comms[k]).map(([k, v]) => [k, v]));
61
+ await this.fn_binding(protocols);
62
+ if (DEBUG_FLAG)
63
+ this.print_to_console();
64
+ return this.spec_generation(protocols);
65
+ }
66
+ // Handles the parsing of SFR files from the directory specified under cfg.out config.
67
+ // It returns a standard NamespaceDeclaration containing each declaration of each supported protocol.
68
+ async file_parsing() {
69
+ //These are the officially supported protocols of the SFR library
70
+ const SUPPORTED_PROTOCOLS = ["rest", "ws", "mq"];
71
+ /*
72
+ Look for folders that match the supported protocols listed above in the designated directory
73
+
74
+ cfg.root = "Specifies the working directory"
75
+ cfg.path = "Specifies the API directory i.e: where SFR files reside"
76
+ cfg.out = "Specifies the directory where the resulting OAS documents are outputted"
77
+ */
78
+ const directory = path.join(CWD, this.cfg.root);
79
+ let paths = SUPPORTED_PROTOCOLS.map((v) => path.join(directory, `${this.cfg.path}/${v}`));
80
+ //Create the directories if it doesn't exist.
81
+ await Promise.all(paths.map((v) => fs.mkdir(v, { recursive: true })));
82
+ //Recursively retrieve all SFRs of each protocol
83
+ let sfr_paths = await Promise.all(paths.map((path) => resolve_sfrs(path)));
84
+ //Import SFRs
85
+ const protocols = await Promise.all(sfr_paths.map((protocol) => import_sfrs(protocol)));
86
+ const REST = protocols[0];
87
+ const WS = protocols[1];
88
+ const MQ = protocols[2];
89
+ if (DEBUG_FLAG) {
90
+ logger.info(`${Object.keys(protocols[0]).length} REST SFR`);
91
+ logger.info(`${Object.keys(protocols[1]).length} WS SFR`);
92
+ logger.info(`${Object.keys(protocols[2]).length} MQ SFR`);
93
+ }
94
+ return { REST, WS, MQ };
95
+ }
96
+ // Handles the binding of the components of each SFR (e.g: executing validators of matching endpoints, injecting controllers to each handler, etc.)
97
+ //Owing to their differing nature, spec generation and fn_binding is handled this way so as to split up the individual logics involved in parsing them.
98
+ async fn_binding(protocols) {
99
+ Object.entries(protocols).forEach(([protocol, declaration]) => {
100
+ switch (protocol) {
101
+ case "REST":
102
+ this.bind_rest_fns(declaration);
103
+ break;
104
+ case "WS":
105
+ this.bind_ws_fns(declaration);
106
+ break;
107
+ case "MQ":
108
+ this.bind_mq_fns(declaration);
109
+ break;
110
+ }
111
+ });
112
+ }
113
+ /* Fn Binding */
114
+ async bind_rest_fns(declaration) {
115
+ const comms = this.comms["REST"];
116
+ if (!comms)
117
+ throw new Error(`FN Binding failed: \nREST protocol lacks it's associated SFRProtocols`);
118
+ Object.entries(declaration).forEach(([namespace, module]) => {
119
+ let { cfg, validators, handlers } = module.content;
120
+ //Set base_directory
121
+ /*
122
+ Directory Order:
123
+ this.base_url -> Folder Structure -> cfg.base_dir
124
+ */
125
+ let base_dir = "";
126
+ if (this.base_url)
127
+ base_dir = `/${this.base_url}`;
128
+ if (module.dir)
129
+ base_dir += `/${module.dir.toString().replaceAll(",", "/")}`;
130
+ if (cfg.base_dir)
131
+ base_dir += `/${cfg.base_dir}`;
132
+ logger.info(`[SFR ${module.name}] resolved path: ${base_dir}/${namespace}`);
133
+ const is_public = Boolean(cfg.public);
134
+ //Loop over all methods and their respective handlers
135
+ Object.entries(handlers).forEach(([method, handler_map]) => {
136
+ for (const [name, handler] of Object.entries(handler_map).filter(([k]) => validators[k])) {
137
+ const dir = `${base_dir}/${namespace}/${name}`;
138
+ const validator = validators[name];
139
+ const validator_type = typeof validator !== "function" ? "joi" : "multer";
140
+ /* bind validators */
141
+ switch (validator_type) {
142
+ case "joi":
143
+ {
144
+ comms[method.toLowerCase()](dir, (req, res, next) => {
145
+ let error = true;
146
+ if (is_public) {
147
+ //if(!req.session.user)return res.status(401).json({error : "Session not found."});
148
+ }
149
+ const validator_keys = Object.keys(validator);
150
+ if (validator_keys.length) {
151
+ error = template(validator, method === "GET" ? req.query : req.body);
152
+ if (error)
153
+ return res.status(400).json({ error });
154
+ }
155
+ next();
156
+ });
157
+ }
158
+ break;
159
+ case "multer":
160
+ {
161
+ comms[method.toLowerCase()](dir, validator);
162
+ /* @ts-ignore */
163
+ comms.use((err, req, res, next) => {
164
+ let temp = { error: err.message, details: err.cause };
165
+ if (err)
166
+ return res.status(400).json(temp);
167
+ next();
168
+ });
169
+ }
170
+ break;
171
+ }
172
+ /* Bind to express app */
173
+ comms[method.toLowerCase()](dir, handler.fn);
174
+ this.mount_data.rest++;
175
+ }
176
+ });
177
+ });
178
+ }
179
+ async bind_ws_fns(declaration) {
180
+ }
181
+ async bind_mq_fns(declaration) {
182
+ const comms = this.comms["MQ"];
183
+ if (!comms)
184
+ throw new Error(`FN Binding failed: \nMQ protocol lacks it's associated SFRProtocols`);
185
+ Object.entries(declaration).forEach(([namespace, module]) => {
186
+ let { cfg, validators, handlers } = module.content;
187
+ //Set base_directory
188
+ let base_dir = cfg.base_dir ? `/${cfg.base_dir}` : "";
189
+ if (this.base_url)
190
+ base_dir = `/${this.base_url}/${base_dir}`;
191
+ if (module.dir)
192
+ base_dir = `${module.dir.toString().replaceAll(",", "/")}/${base_dir}`;
193
+ const is_public = Boolean(cfg.public);
194
+ //Loop over all methods and their respective handlers
195
+ Object.entries(handlers).forEach(([pattern, handler_map]) => {
196
+ //Get associated MQ for pattern
197
+ let mq = this.pattern_channels[pattern];
198
+ //Get all valid handlers (i.e: those with matching validators)
199
+ const valid_handlers = Object.entries(handler_map).filter(([k]) => validators[k]);
200
+ //Loop over each handler
201
+ for (let [name, handler] of valid_handlers) {
202
+ const dir = `${base_dir}${namespace}/${name}`;
203
+ const validator = validators[name];
204
+ //const validator_type = typeof validator !== "function" ? "joi" : "multer"; // TODO: Dynamically update parameter content based on validator type.
205
+ let validator_fn = function (msg) {
206
+ const validator_keys = Object.keys(validator);
207
+ if (validator_keys.length) {
208
+ const error = template(validator, msg.content);
209
+ if (error) {
210
+ if (mq instanceof TargetedMQ) {
211
+ if (error) {
212
+ switch (pattern) {
213
+ case "Request-Reply":
214
+ mq.reply(msg, { error });
215
+ break;
216
+ default: mq.channel.reject(msg, false);
217
+ }
218
+ }
219
+ }
220
+ if (mq instanceof BroadcastMQ)
221
+ mq.channel.reject(msg, false);
222
+ return; //Return immediately to avoid executing handler fn (which may contain reply or ack calls.)
223
+ }
224
+ }
225
+ handler.fn(msg);
226
+ };
227
+ /* bind validators */
228
+ if (mq instanceof TargetedMQ) {
229
+ mq.consume(dir, {
230
+ options: handler.options,
231
+ fn: validator_fn
232
+ });
233
+ }
234
+ if (mq instanceof BroadcastMQ) {
235
+ mq.subscribe(dir, handler.key, {
236
+ options: handler.options,
237
+ fn: validator_fn
238
+ });
239
+ }
240
+ this.mount_data.mq++;
241
+ }
242
+ });
243
+ });
244
+ }
245
+ // Generate OpenAPI and AsyncAPI specification.
246
+ spec_generation(protocols) {
247
+ // Holds the key/value pair of protocols and their respective API Documentation
248
+ const documents = Object.entries(protocols).map(([protocol, declaration]) => {
249
+ switch (protocol) {
250
+ case "REST": return [protocol, this.generate_open_api_document(declaration)];
251
+ case "WS": return [protocol, this.generate_async_api_document(declaration)];
252
+ case "MQ": return [protocol, this.generate_async_api_document(declaration)];
253
+ default: throw new Error(`Failed to generate SFR Spec: ${protocol} protocol is unknown.`);
254
+ }
255
+ });
256
+ return Object.fromEntries(documents);
257
+ }
258
+ generate_open_api_document(declaration) {
259
+ // This will hold the final OpenAPI Document.
260
+ const spec = {
261
+ openapi: "3.0.0",
262
+ info: Object.assign({}, this.oas_cfg),
263
+ paths: {}
264
+ };
265
+ // Iterate through each protocol (e.g., REST, WS, MQ)
266
+ Object.entries(declaration).forEach(([namespace, module]) => {
267
+ const { cfg, handlers, validators } = module.content;
268
+ //Set base_directory
269
+ let base_dir = cfg.base_dir ? `/${cfg.base_dir}/` : "/";
270
+ if (this.base_url)
271
+ base_dir = `/${this.base_url}${base_dir}`;
272
+ if (module.dir)
273
+ base_dir = `${module.dir.toString().replaceAll(",", "/")}/${base_dir}`;
274
+ // Collect the OpenAPI path object for each handler (method)
275
+ for (let [method, handler_map] of Object.entries(handlers)) {
276
+ //Transform method to lowercase
277
+ method = method.toLowerCase();
278
+ // Define the operation (method) for this endpoint
279
+ for (const [endpoint, body] of Object.entries(handler_map)) {
280
+ const validator = validators[endpoint];
281
+ // Skip if no matching validator
282
+ if (!validator)
283
+ continue;
284
+ const validator_type = typeof validator !== "function" ? "joi" : "multer";
285
+ //Default tags are used for service and router level classification (developer platform)
286
+ let default_tags = [
287
+ `sfr-router:${namespace}`,
288
+ `sfr-service:${this.oas_cfg.title || "unspecified"}`
289
+ ];
290
+ if (body.tags && Array.isArray(body.tags))
291
+ default_tags.push(...body.tags);
292
+ const operation_id = `${base_dir}${namespace}/${endpoint}`;
293
+ const document = {
294
+ operationId: `${method.toUpperCase()}:${operation_id}`,
295
+ summary: body.summary || "",
296
+ description: body.description || "",
297
+ tags: default_tags,
298
+ public: Boolean(cfg.public),
299
+ responses: {
300
+ "200": {
301
+ description: "Successful operation",
302
+ content: { "application/json": { schema: { type: "object" } } }
303
+ },
304
+ "400": {
305
+ description: "An error has occured",
306
+ content: { "application/json": { schema: { type: "object" } } }
307
+ }
308
+ }
309
+ };
310
+ //Insert either a parameter or a requestBody according to the method type
311
+ if (validator_type === "joi") {
312
+ document[method === "GET" ? "parameters" : "requestBody"] = j2s(validator).swagger;
313
+ }
314
+ //Haven't found a library for converting multer validators to swagger doc
315
+ if (validator_type === "multer") {
316
+ }
317
+ //Create path if it does not exist.
318
+ if (!spec.paths[operation_id])
319
+ spec.paths[operation_id] = {};
320
+ if (!spec.paths[operation_id][method.toLowerCase()])
321
+ spec.paths[operation_id][method.toLowerCase()] = document;
322
+ }
323
+ }
324
+ });
325
+ //Conform to OAPI standards by appending "x-property" on each field under "meta"
326
+ /* @ts-ignore */
327
+ spec.info.meta = Object.fromEntries(Object.entries(spec.info.meta).map(([k, v]) => [`x-${k}`, v]));
328
+ return spec;
329
+ }
330
+ // Method to generate an AsyncAPI document from an MQNamespaceDeclaration
331
+ generate_async_api_document(declaration) {
332
+ // This will hold the final AsyncAPI Document.
333
+ const spec = {
334
+ asyncapi: '3.0.0',
335
+ info: Object.assign({}, this.oas_cfg),
336
+ channels: {},
337
+ operations: {},
338
+ components: {
339
+ messages: {},
340
+ },
341
+ };
342
+ //Conform to OAPI standards by appending "x-property" on each field under "meta"
343
+ /* @ts-ignore */
344
+ spec.info.meta = Object.fromEntries(Object.entries(spec.info.meta).map(([k, v]) => [`x-${k}`, v]));
345
+ Object.entries(declaration).forEach(([namespace, module]) => {
346
+ let { cfg, validators, handlers } = module.content;
347
+ //Set base_directory
348
+ let base_dir = cfg.base_dir ? `/${cfg.base_dir}/` : "";
349
+ if (this.base_url)
350
+ base_dir = `/${this.base_url}/${base_dir}`;
351
+ if (module.dir)
352
+ base_dir = `${module.dir.toString().replaceAll(",", "/")}/${base_dir}`;
353
+ const is_public = Boolean(cfg.public);
354
+ //Loop over all methods and their respective handlers
355
+ Object.entries(handlers).forEach(([pattern, handler_map]) => {
356
+ //Get associated MQ for pattern
357
+ let mq = this.pattern_channels[pattern];
358
+ //Get all valid handlers (i.e: those with matching validators)
359
+ const valid_handlers = Object.entries(handler_map).filter(([k]) => validators[k]);
360
+ //Loop over each handler
361
+ for (let [name, handler] of valid_handlers) {
362
+ const dir = `${base_dir}${namespace}/${name}`;
363
+ const validator = validators[name];
364
+ const validator_type = typeof validator !== "function" ? "joi" : "multer"; // TODO: Dynamically update parameter content based on validator type.
365
+ const channel_document = {
366
+ address: dir,
367
+ messages: {}
368
+ };
369
+ const operation_document = {
370
+ action: "receive",
371
+ summary: handler.summary || "",
372
+ description: handler.description || "",
373
+ channel: `#/channels/${name}`
374
+ };
375
+ //Insert either a parameter or a requestBody according to the method type
376
+ if (validator_type === "joi") {
377
+ channel_document.messages[`${name}-message`] = {
378
+ name: `${name}-message`,
379
+ payload: j2s(validator).swagger
380
+ };
381
+ }
382
+ //Haven't found a library for converting multer validators to swagger doc
383
+ if (validator_type === "multer") {
384
+ }
385
+ spec.channels[name] = channel_document;
386
+ spec.operations[name] = operation_document;
387
+ }
388
+ });
389
+ });
390
+ return spec;
391
+ }
392
+ // Method to print SFR info to console
393
+ print_to_console() {
394
+ console.log(`____________________________
395
+ | | Mounted
396
+ | ░██████╗███████╗██████╗░ | REST : ${this.mount_data.rest}
397
+ | ██╔════╝██╔════╝██╔══██╗ | WS : ${this.mount_data.ws}
398
+ | ╚█████╗░█████╗░░██████╔╝ | MQ : ${this.mount_data.mq}
399
+ | ░╚═══██╗██╔══╝░░██╔══██╗ |-----------
400
+ | ██████╔╝██║░░░░░██║░░██║ | Protocols
401
+ | ╚═════╝░╚═╝░░░░░╚═╝░░╚═╝ | REST : ${this.comms["REST"] ? "✅" : "❌"}
402
+ | Single File Router | MQ : ${this.comms["MQ"] ? "✅" : "❌"}
403
+ | | WS : ${this.comms["WS"] ? "✅" : "❌"}
404
+ ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯`);
405
+ }
406
+ }
407
+ /* Utility fns */
408
+ /* File Parsing */
409
+ async function resolve_sfrs(dir, prefix) {
410
+ //Get Directory Contents
411
+ const contents = await fs.readdir(dir);
412
+ const results = [];
413
+ //Loop over contents
414
+ await Promise.all(contents.map(async (v) => {
415
+ const content_path = path.join(dir, v);
416
+ const is_dir = (await fs.lstat(content_path)).isDirectory();
417
+ //If Directory, perform a recursion and return output of contents.map fn.
418
+ if (is_dir) {
419
+ const dir_output = await resolve_sfrs(content_path, prefix ? `${prefix}/${v}` : v);
420
+ results.push(dir_output);
421
+ return;
422
+ }
423
+ ;
424
+ let output = { name: v, path: content_path };
425
+ if (prefix)
426
+ output.dir = prefix.split("/");
427
+ results.push(output);
428
+ }));
429
+ return results.flat();
430
+ }
431
+ async function import_sfrs(protocol_files) {
432
+ const protocols = await Promise.all(protocol_files.map(async (v) => {
433
+ const import_task = await import(`file:///${v.path}`);
434
+ return [v.name.replace(".mjs", ""), {
435
+ ...v,
436
+ content: import_task.default
437
+ }];
438
+ }));
439
+ //Removes SFRs without body.
440
+ return Object.fromEntries(protocols.filter((v) => v[1].content));
441
+ }
442
+ // Method to generate JSON schema for the payload based on handler metadata
443
+ function generate_json_schema(metadata) {
444
+ return {
445
+ type: 'object',
446
+ properties: {
447
+ example_field: {
448
+ type: 'string',
449
+ ...metadata
450
+ },
451
+ },
452
+ required: ['example_field'],
453
+ };
454
+ }
@@ -0,0 +1,47 @@
1
+ //Previous Name: RequestHandlerFactory
2
+ //Dependencies are imported and used by the functions below
3
+ import { SFRPipeline } from "./sfr-pipeline.mjs";
4
+ export function REST(struct) {
5
+ const validators = struct.validators || {};
6
+ const controllers = struct.controllers || {};
7
+ const handlers = struct.handlers || {};
8
+ const cfg = struct.cfg || {};
9
+ //Bind controller injections to each controllers
10
+ Object.entries(controllers).map(([k, v]) => controllers[k] = v.bind({ ...SFRPipeline.injections.rest.controllers }));
11
+ //Bind handler injections and SFR controllers into each handlers.
12
+ Object.entries(handlers).forEach(([method, handlermap]) => {
13
+ Object.entries(handlermap).forEach(([k, v]) => {
14
+ /* @ts-ignore */
15
+ handlers[method][k] = { ...v, fn: v.fn.bind({ ...controllers, ...SFRPipeline.injections.rest.handlers }) };
16
+ });
17
+ });
18
+ /* @ts-ignore */
19
+ return { validators, controllers, handlers, cfg };
20
+ }
21
+ export function WS(struct) {
22
+ const validators = struct.validators || {};
23
+ const controllers = struct.controllers || {};
24
+ const handlers = struct.handlers || {};
25
+ const cfg = struct.cfg || {};
26
+ //Dependency injection happens here...npm
27
+ return { validators, controllers, handlers, cfg };
28
+ }
29
+ export function MQ(struct) {
30
+ const validators = struct.validators || {};
31
+ const controllers = struct.controllers || {};
32
+ const handlers = struct.handlers || {};
33
+ const cfg = struct.cfg || {};
34
+ //Bind controller injections to each controllers
35
+ Object.entries(controllers).map(([k, v]) => controllers[k] = v.bind({ ...SFRPipeline.injections.mq.controllers }));
36
+ //Bind handler injections and SFR controllers into each handlers.
37
+ Object.entries(handlers).forEach(([pattern, handlermap]) => {
38
+ Object.entries(handlermap).forEach(([k, v]) => {
39
+ /* @ts-ignore */
40
+ const { mq } = (SFRPipeline.injections.mq.handlers || {});
41
+ /* @ts-ignore */
42
+ handlers[pattern][k] = { ...v, fn: v.fn.bind({ ...controllers, mq: mq ? mq[pattern] : null }) };
43
+ });
44
+ });
45
+ /* @ts-ignore */
46
+ return { validators, controllers, handlers, cfg };
47
+ }
@@ -0,0 +1,11 @@
1
+ declare const _default: {
2
+ GET: {
3
+ "get-something": {
4
+ description: string;
5
+ fn(req: import("express").Request<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>, res: import("express").Response<any, Record<string, any>>): Promise<void>;
6
+ };
7
+ };
8
+ } & {
9
+ db_call(): Promise<string>;
10
+ };
11
+ export default _default;
@@ -0,0 +1,7 @@
1
+ /// <reference path="../../src/types/index.d.ts" />
2
+ import { REST, WS, MQ } from "./templates.mjs";
3
+ import { MQLib, BroadcastMQ, TargetedMQ } from "./mq.mjs";
4
+ declare const _default: (cfg: ParserCFG, oas_cfg: OASConfig, connectors: SFRProtocols, base_url?: string) => Promise<ServiceManifest>;
5
+ export default _default;
6
+ declare function inject(injections: InjectedFacilities): void;
7
+ export { REST, WS, MQ, MQLib, BroadcastMQ, TargetedMQ, inject };
@@ -0,0 +1,3 @@
1
+ import winston from 'winston';
2
+ declare const logger: winston.Logger;
3
+ export { logger };
@@ -0,0 +1,114 @@
1
+ import { ChannelModel, Options, Channel, ConsumeMessage } from "amqplib";
2
+ /**
3
+ * MQLib class for establishing a connection to the message queue and creating channels.
4
+ */
5
+ export declare class MQLib {
6
+ private connection?;
7
+ private channel?;
8
+ /**
9
+ * Initializes the connection and channel to the message queue.
10
+ *
11
+ * @param MQ_URL - The URL of the message queue.
12
+ * @example
13
+ * const mqLib = new MQLib();
14
+ * await mqLib.init("amqp://localhost");
15
+ */
16
+ init(MQ_URL: string): Promise<void>;
17
+ /**
18
+ * Returns the connection object.
19
+ *
20
+ * @returns The connection object to the message queue.
21
+ */
22
+ get_connection(): ChannelModel;
23
+ /**
24
+ * Returns the channel object.
25
+ *
26
+ * @returns The channel object to the message queue.
27
+ */
28
+ get_channel(): Channel;
29
+ }
30
+ export declare class BaseMQ {
31
+ channel: Channel;
32
+ protected type: CommunicationPattern;
33
+ constructor(channel: Channel, type: CommunicationPattern);
34
+ }
35
+ /**
36
+ * BroadcastMQ class to handle different types of broadcast communication patterns: Fanout, Direct, and Topic.
37
+ */
38
+ export declare class BroadcastMQ extends BaseMQ {
39
+ channel: Channel;
40
+ protected type: CommunicationPattern;
41
+ protected exchange_options?: Options.AssertExchange;
42
+ constructor(channel: Channel, type: CommunicationPattern, exchange_options?: Options.AssertExchange);
43
+ /**
44
+ * Publishes a message to the specified exchange based on the communication pattern.
45
+ *
46
+ * @param exchange - The name of the exchange to send the message to.
47
+ * @param key - The routing key or pattern to use, depending on the communication pattern.
48
+ * @param payload - The message to be sent.
49
+ * @param options - Additional publishing options.
50
+ * @example
51
+ * // Publish a message to a 'logsExchange' with a routing key 'error' for a routing pattern.
52
+ * const mq = new BroadcastMQ(channel, "Direct");
53
+ * mq.publish("logsExchange", "error", { level: "error", message: "Something went wrong" });
54
+ */
55
+ publish(exchange: string, key: string, payload: any, options?: Options.Publish): Promise<void>;
56
+ /**
57
+ * Subscribes to an exchange to receive messages based on the communication pattern.
58
+ *
59
+ * @param exchange - The name of the exchange to subscribe to.
60
+ * @param key - The routing key or pattern to listen for.
61
+ * @param cfg - Configuration options for the consumer, including the callback function.
62
+ * @param options - Additional consumption options.
63
+ * @example
64
+ * // Subscribe to the 'logsExchange' for all 'error' messages in the Direct pattern.
65
+ * const mq = new BroadcastMQ(channel, "Direct");
66
+ * mq.subscribe("logsExchange", "error", { fn: handleErrorLogs, options: { noAck: true } });
67
+ */
68
+ subscribe(exchange: string, key: string, cfg: ConsumerConfig): Promise<void>;
69
+ set_options(options: Options.AssertExchange): void;
70
+ }
71
+ /**
72
+ * TargetedMQ class to handle Point-to-Point and Request-Reply communication patterns.
73
+ */
74
+ export declare class TargetedMQ extends BaseMQ {
75
+ channel: Channel;
76
+ protected type: CommunicationPattern;
77
+ protected queue_options?: Options.AssertQueue;
78
+ constructor(channel: Channel, type: CommunicationPattern, queue_options?: Options.AssertQueue);
79
+ /**
80
+ * Sends a message to the specified queue depending on the communication pattern.
81
+ *
82
+ * @param binding - The name of the queue or binding to send the message to.
83
+ * @param payload - The message to be sent.
84
+ * @param options - Additional publishing options.
85
+ * @example
86
+ * // Send a message to a queue for point-to-point communication
87
+ * const mq = new TargetedMQ(channel, "Point-to-Point");
88
+ * mq.produce("taskQueue", { taskId: 1, action: "process" });
89
+ */
90
+ produce(binding: string, payload: any, options?: Options.Publish): Promise<boolean>;
91
+ /**
92
+ * Consumes messages from the specified queue based on the communication pattern.
93
+ *
94
+ * @param queue - The name of the queue to consume messages from.
95
+ * @param cfg - Configuration options for the consumer, including the callback function.
96
+ * @example
97
+ * // Consume a message from the 'taskQueue' in a Point-to-Point communication pattern
98
+ * const mq = new TargetedMQ(channel, "Point-to-Point");
99
+ * mq.consume("taskQueue", { fn: processTask, options: { noAck: true } });
100
+ */
101
+ consume(queue: string, cfg: ConsumerConfig): Promise<void>;
102
+ /**
103
+ * Sends a reply to the message sender in a Request-Reply pattern.
104
+ *
105
+ * @param msg - The original message to reply to.
106
+ * @param payload - The reply message to send back to the requester.
107
+ * @example
108
+ * // Send a response back to the client in a Request-Reply pattern
109
+ * const mq = new TargetedMQ(channel, "Request-Reply");
110
+ * mq.reply(msg, { result: "Processed successfully" });
111
+ */
112
+ reply(msg: ConsumeMessage, payload: any): Promise<void>;
113
+ set_options(options: Options.AssertQueue): void;
114
+ }
@@ -0,0 +1,33 @@
1
+ export declare class SFRPipeline {
2
+ private cfg;
3
+ private oas_cfg;
4
+ private comms;
5
+ base_url: string;
6
+ pattern_channels: PatternMQSet;
7
+ mount_data: {
8
+ rest: number;
9
+ ws: number;
10
+ mq: number;
11
+ };
12
+ static injections: {
13
+ rest: {
14
+ handlers: {};
15
+ controllers: {};
16
+ };
17
+ mq: {
18
+ handlers: {};
19
+ controllers: {};
20
+ };
21
+ };
22
+ constructor(cfg: ParserCFG, oas_cfg: OASConfig, comms: SFRProtocols);
23
+ init(base_url?: string): Promise<ServiceDocuments>;
24
+ private file_parsing;
25
+ private fn_binding;
26
+ private bind_rest_fns;
27
+ private bind_ws_fns;
28
+ private bind_mq_fns;
29
+ private spec_generation;
30
+ private generate_open_api_document;
31
+ private generate_async_api_document;
32
+ private print_to_console;
33
+ }
@@ -0,0 +1,8 @@
1
+ export declare function REST<V, H, C>(struct: RESTHandlerDescriptor<V, H, C>): H & C;
2
+ export declare function WS<V, H, C>(struct: WSHandlerDescriptor<V, H, C>): {
3
+ validators: RequestValidators;
4
+ controllers: RequestControllers;
5
+ handlers: WSRequestHandlers;
6
+ cfg: SFRConfig;
7
+ };
8
+ export declare function MQ<V, H, C>(struct: MQHandlerDescriptor<V, H, C>): H & C;
@@ -0,0 +1,7 @@
1
+ import { Response } from "express";
2
+ import Joi from "joi";
3
+ export declare function get_stats(dirs: string[], base_dir: string): Promise<string[]>;
4
+ export declare function assess_namespace(stats: string[], dir: string): Promise<any>;
5
+ export declare const template: (rule: object, v: object) => string | false;
6
+ export declare const object_id: Joi.StringSchema<string>;
7
+ export declare const handle_res: (controller: Promise<any>, res: Response) => void;
package/dist/util.mjs ADDED
@@ -0,0 +1,25 @@
1
+ import fs from "fs/promises";
2
+ import path from "path";
3
+ import Joi from "joi";
4
+ export async function get_stats(dirs, base_dir) {
5
+ let temp = await Promise.all(dirs.map((v) => fs.lstat(path.join(base_dir, v)).then((stats) => ({ stats, dir: v }))));
6
+ const result = temp.filter(({ stats }) => stats.isFile()).map((v) => v.dir);
7
+ return result;
8
+ }
9
+ export async function assess_namespace(stats, dir) {
10
+ let dirs = stats.map((v) => `file:///${dir.replaceAll("\\", "/")}/${v}`);
11
+ const result = await Promise.all(dirs.map((d) => import(d).then((v) => [d.replace(".mjs", "").substring(d.lastIndexOf("/") + 1), v.default]))).then(Object.fromEntries);
12
+ return result;
13
+ }
14
+ export const template = (rule, v) => _validate(Joi.object(rule).validate(v));
15
+ function _validate(expression) {
16
+ let result = expression.error;
17
+ return result ? result.details[0].message : false;
18
+ }
19
+ export const object_id = Joi.string().hex().length(24).required();
20
+ /* QoLs */
21
+ export const handle_res = (controller, res) => {
22
+ controller
23
+ .then((data) => res.json({ data }))
24
+ .catch((error) => res.status(400).json({ error }));
25
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avtechno/sfr",
3
- "version": "1.0.13",
3
+ "version": "1.0.15",
4
4
  "description": "An opinionated way of writing services using ExpressJS.",
5
5
  "type": "module",
6
6
  "files": [
@@ -11,6 +11,8 @@ const CWD = process.cwd();
11
11
  const PATTERNS: CommunicationPattern[] = ["Point-to-Point", "Request-Reply", "Fanout", "Direct", "Topic"];
12
12
  const TARGETED_PATTERN = ["Point-to-Point", "Request-Reply"];
13
13
 
14
+ const DEBUG_FLAG = Boolean(process.env.DEBUG_SFR);
15
+
14
16
  export class SFRPipeline {
15
17
  base_url: string;
16
18
  pattern_channels: PatternMQSet;
@@ -32,7 +34,7 @@ export class SFRPipeline {
32
34
  },
33
35
  }
34
36
 
35
- constructor(private cfg: ParserCFG, private oas_cfg: OASConfig, private comms: SFRProtocols, private debug? : boolean) { }
37
+ constructor(private cfg: ParserCFG, private oas_cfg: OASConfig, private comms: SFRProtocols) { }
36
38
 
37
39
  async init(base_url?: string): Promise<ServiceDocuments> {
38
40
  this.base_url = base_url;
@@ -66,7 +68,7 @@ export class SFRPipeline {
66
68
  protocols = Object.fromEntries(Object.entries(protocols).filter(([k])=> this.comms[k]).map(([k, v])=> [k, v]));
67
69
  await this.fn_binding(protocols);
68
70
 
69
- if(this.debug)this.print_to_console();
71
+ if(DEBUG_FLAG)this.print_to_console();
70
72
 
71
73
  return this.spec_generation(protocols);
72
74
  }
@@ -96,7 +98,7 @@ export class SFRPipeline {
96
98
  const WS: WSNamespaceDeclaration = protocols[1];
97
99
  const MQ: MQNamespaceDeclaration = protocols[2];
98
100
 
99
- if(this.debug){
101
+ if(DEBUG_FLAG){
100
102
  logger.info(`${Object.keys(protocols[0]).length} REST SFR`)
101
103
  logger.info(`${Object.keys(protocols[1]).length} WS SFR`)
102
104
  logger.info(`${Object.keys(protocols[2]).length} MQ SFR`)
@@ -280,12 +280,16 @@ declare type ParserCFG = {
280
280
 
281
281
  declare type Channel = import("amqplib").Channel;
282
282
  declare type ConsumeMessage = import("amqplib").ConsumeMessage;
283
+ declare type Message = import("amqplib").Message;
283
284
  declare type QueueOptions = import("amqplib").Options.AssertQueue;
284
285
  declare type ConsumeOptions = import("amqplib").Options.Consume;
285
286
 
287
+ declare type ParsedMessage = {
288
+ content : object
289
+ } | Message
286
290
  declare type ConsumerConfig = {
287
291
  options?: ConsumeOptions;
288
- fn: ((msg: ConsumeMessage) => void);
292
+ fn: ((msg: ParsedMessage) => void);
289
293
  } & ThisType<ConsumerContext>;
290
294
  declare type ConsumerContext = {
291
295
  name: string;
@@ -354,7 +358,7 @@ declare type TopicOptions = MQConsumeOptions & {
354
358
  }
355
359
 
356
360
 
357
- declare type MQRequestHandler = (msg: (ConsumeMessage & { content: any }) | null) => void;
361
+ declare type MQRequestHandler = (msg:ParsedMessage) => void;
358
362
 
359
363
 
360
364
  declare type MQRequestCtx = {