@oas-tools/oas-telemetry 0.4.0 → 0.5.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 (39) hide show
  1. package/LICENSE +0 -0
  2. package/README.md +151 -133
  3. package/dist/client.cjs +14 -0
  4. package/dist/config.cjs +27 -0
  5. package/dist/controllers/pluginController.cjs +118 -0
  6. package/dist/controllers/telemetryController.cjs +92 -0
  7. package/dist/controllers/uiController.cjs +78 -0
  8. package/dist/exporters/InMemoryDbExporter.cjs +45 -42
  9. package/dist/exporters/consoleExporter.cjs +52 -0
  10. package/dist/exporters/dynamicExporter.cjs +64 -0
  11. package/dist/index.cjs +61 -271
  12. package/dist/middleware/auth.cjs +17 -0
  13. package/dist/middleware/authMiddleware.cjs +19 -0
  14. package/dist/openTelemetry.cjs +20 -0
  15. package/dist/routes/authRoutes.cjs +79 -0
  16. package/dist/routes/telemetryRoutes.cjs +31 -0
  17. package/{src/ui.js → dist/services/uiService.cjs} +1140 -813
  18. package/dist/telemetry.cjs +0 -0
  19. package/dist/types/exporters/InMemoryDbExporter.d.ts +0 -0
  20. package/dist/types/index.d.ts +0 -0
  21. package/dist/types/telemetry.d.ts +0 -0
  22. package/dist/types/ui.d.ts +0 -0
  23. package/dist/ui.cjs +0 -0
  24. package/package.json +75 -71
  25. package/src/config.js +19 -0
  26. package/src/controllers/pluginController.js +115 -0
  27. package/src/controllers/telemetryController.js +68 -0
  28. package/src/controllers/uiController.js +69 -0
  29. package/src/dev/ui/login.html +32 -0
  30. package/src/exporters/InMemoryDbExporter.js +180 -175
  31. package/src/exporters/consoleExporter.js +47 -0
  32. package/src/exporters/dynamicExporter.js +62 -0
  33. package/src/index.js +85 -310
  34. package/src/middleware/authMiddleware.js +14 -0
  35. package/src/openTelemetry.js +22 -0
  36. package/src/routes/authRoutes.js +53 -0
  37. package/src/routes/telemetryRoutes.js +38 -0
  38. package/src/services/uiService.js +1520 -0
  39. package/src/telemetry.js +0 -25
package/LICENSE CHANGED
File without changes
package/README.md CHANGED
@@ -1,133 +1,151 @@
1
- # OAS TELEMETRY
2
-
3
- OAS Telemetry offers an express middleware designed for collecting telemetry data using Open Telemetry in applications built using the OpenAPI Specification (OAS). This middleware allows developers to easily incorporate telemetry functionality into their APIs.
4
-
5
- OAS Telemetry provides a set of endpoints that can be accessed to perform various actions related to telemetry data, such as starting and stopping data collection, resetting telemetry data, listing collected data, and searching for specific telemetry records. These endpoints can be easily integrated into an Express.js application, providing developers with a convenient way to manage and analyze telemetry data.
6
-
7
- Additionally, OAS Telemetry offers customization options, allowing developers to configure the telemetry middleware according to their specific requirements.
8
-
9
- Overall, OAS Telemetry will serve as a valuable tool for developers looking to gain insights into the operation and performance of their OAS-based APIs, enabling them to monitor, debug, and optimize their applications effectively.
10
-
11
-
12
-
13
-
14
-
15
- ## Usage
16
- To use the middelware add this two lines in your index.js (ESM):
17
- ```js
18
- import oasTelemetry from 'oas-telemetry';
19
- import {readFileSync} from 'fs';
20
-
21
- app.use(oasTelemetry({
22
- spec : readFileSync('./spec/oas.yaml',{ encoding: 'utf8', flag: 'r' })
23
- }))
24
-
25
- ```
26
-
27
- ## Custom Configuration
28
-
29
- You can also customize the telemetry configuration by passing options to the middleware function. For example:
30
- ```js
31
- const customTelemetryConfig = {
32
- exporter: myCustomExporter,
33
- spec: /* OAS content in json or yaml */
34
- };
35
-
36
- app.use(oasTelemetry(customTelemetryConfig));
37
- ```
38
-
39
- ## Telemetry UI
40
-
41
- You can access the telemetry UI in the endpoint ``/telemetry``
42
-
43
-
44
- ## API Telemetry Endpoints
45
-
46
- OAS Telemetry middleware adds the following endpoints to your Express application:
47
-
48
-
49
- - /telemetry/start: Start telemetry data collection.
50
- - /telemetry/stop: Stop telemetry data collection.
51
- - /telemetry/status: Get status of telemetry.
52
- - /telemetry/reset: Reset telemetry data.
53
- - /telemetry/list: List all telemetry data.
54
- - /telemetry/find (POST): Search telemetry data.
55
- - /telemetry/heapStats: Shows v8 heapStats.
56
-
57
-
58
- ## Simple Example [ES Module](https://nodejs.org/docs/latest/api/esm.html) (*.mjs)
59
- ```js index.mjs
60
- import oasTelemetry from '@oas-tools/oas-telemetry';
61
- import express from 'express';
62
-
63
- const app = express();
64
- const port = 3000;
65
-
66
- const spec = { "paths": {
67
- "/api/v1/pets": {
68
- "get": {
69
- "summary": "Get pets",
70
- "responses":{
71
- "200": {
72
- "description": "Success"
73
- }
74
- }
75
- }
76
- }
77
- }
78
- }
79
-
80
- app.use(oasTelemetry({
81
- spec : JSON.stringify(spec)
82
- }))
83
-
84
- app.use(express.json());
85
-
86
- app.get("/api/v1/pets", (req, res) => {
87
- res.send([{ name: "rocky"},{ name: "pikachu"}]);
88
- });
89
-
90
- app.listen(port, () => {
91
- console.log(`Example app listening at http://localhost:${port}`);
92
- console.log(`Telemetry portal available at http://localhost:${port}/telemetry`);
93
- });
94
- ```
95
-
96
- ## Simple Example [Common.js Module](https://nodejs.org/docs/latest/api/modules.html) (*.cjs)
97
- ```js index.cjs
98
- let oasTelemetry = require('@oas-tools/oas-telemetry');
99
- let express = require('express');
100
-
101
- const app = express();
102
- const port = 3000;
103
-
104
- const spec = { "paths": {
105
- "/api/v1/pets": {
106
- "get": {
107
- "summary": "Get pets",
108
- "responses":{
109
- "200": {
110
- "description": "Success"
111
- }
112
- }
113
- }
114
- }
115
- }
116
- }
117
-
118
- app.use(oasTelemetry({
119
- spec : JSON.stringify(spec)
120
- }))
121
-
122
- app.use(express.json());
123
-
124
- app.get("/api/v1/pets", (req, res) => {
125
- res.send([{ name: "rocky"},{ name: "pikachu"}]);
126
- });
127
-
128
- app.listen(port, () => {
129
- console.log(`Example app listening at http://localhost:${port}`);
130
- console.log(`Telemetry portal available at http://localhost:${port}/telemetry`);
131
- });
132
- ```
133
-
1
+ # OAS TELEMETRY
2
+
3
+ OAS Telemetry offers an express middleware designed for collecting telemetry data using Open Telemetry in applications built using the OpenAPI Specification (OAS). This middleware allows developers to easily incorporate telemetry functionality into their APIs.
4
+
5
+ OAS Telemetry provides a set of endpoints that can be accessed to perform various actions related to telemetry data, such as starting and stopping data collection, resetting telemetry data, listing collected data, and searching for specific telemetry records. These endpoints can be easily integrated into an Express.js application, providing developers with a convenient way to manage and analyze telemetry data.
6
+
7
+ Additionally, OAS Telemetry offers customization options, allowing developers to configure the telemetry middleware according to their specific requirements.
8
+
9
+ Overall, OAS Telemetry will serve as a valuable tool for developers looking to gain insights into the operation and performance of their OAS-based APIs, enabling them to monitor, debug, and optimize their applications effectively.
10
+
11
+ The package now supports both ES Module (ESM) and CommonJS (CJS) formats, making it compatible with a wide range of applications. Furthermore, OAS Telemetry provides a range of plugins to extend its functionality, enabling developers to tailor telemetry data collection, alerting, and reporting to meet specific requirements. See the [Telemetry Plugins](#telemetry-plugins) section for more information.
12
+
13
+
14
+
15
+
16
+
17
+ ## Usage
18
+ To use the middelware add this two lines in your index.js (ESM):
19
+ ```js
20
+ import oasTelemetry from 'oas-telemetry';
21
+ import {readFileSync} from 'fs';
22
+
23
+ app.use(oasTelemetry({
24
+ spec : readFileSync('./spec/oas.yaml',{ encoding: 'utf8', flag: 'r' })
25
+ }))
26
+
27
+ ```
28
+
29
+ ## Custom Configuration
30
+
31
+ You can also customize the telemetry configuration by passing options to the middleware function. For example:
32
+ ```js
33
+ const customTelemetryConfig = {
34
+ exporter: myCustomExporter,
35
+ spec: /* OAS content in json or yaml */
36
+ };
37
+
38
+ app.use(oasTelemetry(customTelemetryConfig));
39
+ ```
40
+
41
+ ## Telemetry UI
42
+
43
+ You can access the telemetry UI in the endpoint ``/telemetry``
44
+
45
+
46
+ ## API Telemetry Endpoints
47
+
48
+ OAS Telemetry middleware adds the following endpoints to your Express application:
49
+
50
+
51
+ - /telemetry/start: Start telemetry data collection.
52
+ - /telemetry/stop: Stop telemetry data collection.
53
+ - /telemetry/status: Get status of telemetry.
54
+ - /telemetry/reset: Reset telemetry data.
55
+ - /telemetry/list: List all telemetry data.
56
+ - /telemetry/find (POST): Search telemetry data.
57
+ - /telemetry/heapStats: Shows v8 heapStats.
58
+
59
+ - /telemetry/plugins: List all plugins.
60
+ - /telemetry/plugins (POST): Add a plugin.
61
+
62
+
63
+ ## Simple Example [ES Module](https://nodejs.org/docs/latest/api/esm.html) (*.mjs)
64
+ ```js index.mjs
65
+ import oasTelemetry from '@oas-tools/oas-telemetry';
66
+ import express from 'express';
67
+
68
+ const app = express();
69
+ const port = 3000;
70
+
71
+ const spec = { "paths": {
72
+ "/api/v1/pets": {
73
+ "get": {
74
+ "summary": "Get pets",
75
+ "responses":{
76
+ "200": {
77
+ "description": "Success"
78
+ }
79
+ }
80
+ }
81
+ }
82
+ }
83
+ }
84
+
85
+ app.use(oasTelemetry({
86
+ spec : JSON.stringify(spec)
87
+ }))
88
+
89
+ app.use(express.json());
90
+
91
+ app.get("/api/v1/pets", (req, res) => {
92
+ res.send([{ name: "rocky"},{ name: "pikachu"}]);
93
+ });
94
+
95
+ app.listen(port, () => {
96
+ console.log(`Example app listening at http://localhost:${port}`);
97
+ console.log(`Telemetry portal available at http://localhost:${port}/telemetry`);
98
+ });
99
+ ```
100
+
101
+ ## Simple Example [Common.js Module](https://nodejs.org/docs/latest/api/modules.html) (*.cjs)
102
+ ```js index.cjs
103
+ let oasTelemetry = require('@oas-tools/oas-telemetry');
104
+ let express = require('express');
105
+
106
+ const app = express();
107
+ const port = 3000;
108
+
109
+ const spec = { "paths": {
110
+ "/api/v1/pets": {
111
+ "get": {
112
+ "summary": "Get pets",
113
+ "responses":{
114
+ "200": {
115
+ "description": "Success"
116
+ }
117
+ }
118
+ }
119
+ }
120
+ }
121
+ }
122
+
123
+ app.use(oasTelemetry({
124
+ spec : JSON.stringify(spec)
125
+ }))
126
+
127
+ app.use(express.json());
128
+
129
+ app.get("/api/v1/pets", (req, res) => {
130
+ res.send([{ name: "rocky"},{ name: "pikachu"}]);
131
+ });
132
+
133
+ app.listen(port, () => {
134
+ console.log(`Example app listening at http://localhost:${port}`);
135
+ console.log(`Telemetry portal available at http://localhost:${port}/telemetry`);
136
+ });
137
+ ```
138
+
139
+ ## Telemetry Plugins
140
+
141
+ OAS Telemetry supports a range of plugins to extend its functionality, allowing developers to tailor telemetry data collection, alerting, and reporting to meet specific requirements. Plugins enable additional features, such as integration with alerting systems, custom data exporters, and data visualization tools.
142
+
143
+ One example plugin is the **Outlier Alert Over Messaging** plugin, which can be configured to send anomaly alerts to messaging platforms like Telegram. This plugin is especially useful for monitoring abnormal response times in your API, notifying selected channels to allow rapid responses to potential issues. For setup details, refer to its [README documentation](https://github.com/oas-tools/oas-telemetry-plugin-outlier-messaging/blob/main/README.md).
144
+
145
+ OAS Telemetry plugins are flexible and support both ES Modules (ESM) and CommonJS (CJS) formats, regardless of whether your application is using ESM or CJS. This compatibility ensures that plugins work seamlessly in all configurations:
146
+ - ESM applications can use plugins in either ESM or CJS format.
147
+ - CJS applications can use plugins in either CJS or ESM format.
148
+
149
+ This flexibility makes it easy to incorporate a wide variety of plugins in your preferred module system.
150
+
151
+
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+
3
+ // client.js
4
+
5
+ function sendRequest(url, options = {}) {
6
+ const apiKey = localStorage.getItem('apiKey');
7
+ if (!options.headers) {
8
+ options.headers = {};
9
+ }
10
+ options.headers['x-api-key'] = apiKey;
11
+ return fetch(url, options);
12
+ }
13
+
14
+ // ...existing code...
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.globalOasTlmConfig = exports.default = void 0;
7
+ var _dynamicExporter = _interopRequireDefault(require("./exporters/dynamicExporter.cjs"));
8
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
9
+ //Environment variables
10
+ //OASTLM_API_KEY = 'oas-telemetry-api-key' //Cookie value for the API key
11
+ //OASTLM_MODULE_DISABLED = 'true' //Disables the module (empty middleware and no tracing)
12
+
13
+ const globalOasTlmConfig = exports.globalOasTlmConfig = {
14
+ dynamicExporter: new _dynamicExporter.default(),
15
+ baseURL: "/telemetry4",
16
+ spec: null,
17
+ specFileName: "",
18
+ autoActivate: true,
19
+ apiKeyMaxAge: 1000 * 60 * 60,
20
+ // 1 hour
21
+ password: "oas-telemetry-password",
22
+ jwtSecret: "oas-telemetry-secret"
23
+ };
24
+ //5 name alternatives. one for globals
25
+ var _default = exports.default = {
26
+ globalOasTlmConfig
27
+ };
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.registerPlugin = exports.listPlugins = exports.checkApiKey = void 0;
7
+ var _config = require("../config.cjs");
8
+ var _axios = _interopRequireDefault(require("axios"));
9
+ var _importFromString = require("import-from-string");
10
+ var _dynamicInstaller = require("dynamic-installer");
11
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
+ let dbglog = () => {};
13
+ if (process.env.OTDEBUG == "true") dbglog = console.log;
14
+ const listPlugins = (req, res) => {
15
+ res.send(_config.globalOasTlmConfig.dynamicExporter.getPlugins().map(p => {
16
+ return {
17
+ id: p.id,
18
+ name: p.name,
19
+ url: p.url,
20
+ active: p.active
21
+ };
22
+ }));
23
+ };
24
+ exports.listPlugins = listPlugins;
25
+ const registerPlugin = async (req, res) => {
26
+ let pluginResource = req.body;
27
+ dbglog(`Plugin Registration Request: = ${JSON.stringify(req.body, null, 2)}...`);
28
+ dbglog(`Getting plugin at ${pluginResource.url}...`);
29
+ let pluginCode;
30
+ if (!pluginResource.url && !pluginResource.code) {
31
+ res.status(400).send(`Plugin code or URL must be provided`);
32
+ return;
33
+ }
34
+ let module;
35
+ try {
36
+ if (pluginResource.code) {
37
+ pluginCode = pluginResource.code;
38
+ } else {
39
+ const response = await _axios.default.get(pluginResource.url);
40
+ pluginCode = response.data;
41
+ }
42
+ if (!pluginCode) {
43
+ res.status(400).send(`Plugin code could not be loaded`);
44
+ return;
45
+ }
46
+ if (pluginResource.install) {
47
+ const dependenciesStatus = await (0, _dynamicInstaller.installDependencies)(pluginResource.install);
48
+ if (!dependenciesStatus.success) {
49
+ if (pluginResource.install.ignoreErrors === true) {
50
+ console.warn(`Warning: Error installing dependencies: ${JSON.stringify(dependenciesStatus.details)}`);
51
+ } else {
52
+ res.status(400).send(`Error installing dependencies: ${JSON.stringify(dependenciesStatus.details)}`);
53
+ return;
54
+ }
55
+ }
56
+ }
57
+ dbglog("Plugin size: " + pluginCode?.length);
58
+ dbglog("Plugin format: " + pluginResource?.moduleFormat);
59
+ if (pluginResource?.moduleFormat && pluginResource.moduleFormat.toUpperCase() == "ESM") {
60
+ console.log("ESM detected");
61
+ module = await (0, _importFromString.importFromString)(pluginCode);
62
+ } else {
63
+ console.log("CJS detected (default)");
64
+ module = await (0, _importFromString.requireFromString)(pluginCode);
65
+ console.log(module);
66
+ }
67
+ } catch (error) {
68
+ console.error(`Error loading plugin: ${error}`);
69
+ res.status(400).send(`Error loading plugin: ${error}`);
70
+ return;
71
+ }
72
+ const plugin = module.default?.plugin ?? module.plugin;
73
+ if (plugin == undefined) {
74
+ res.status(400).send(`Plugin code should export a "plugin" object`);
75
+ console.log("Error in plugin code: no plugin object exported");
76
+ return;
77
+ }
78
+ for (let requiredFunction of ["load", "getName", "isConfigured"]) {
79
+ if (plugin[requiredFunction] == undefined) {
80
+ res.status(400).send(`The plugin code exports a "plugin" object, however it should have a "${requiredFunction}" method`);
81
+ console.log("Error in plugin code: some required functions are missing");
82
+ return;
83
+ }
84
+ }
85
+ try {
86
+ await plugin.load(pluginResource.config);
87
+ } catch (error) {
88
+ console.error(`Error loading plugin configuration: ${error}`);
89
+ res.status(400).send(`Error loading plugin configuration: ${error}`);
90
+ return;
91
+ }
92
+ if (plugin.isConfigured()) {
93
+ dbglog(`Loaded plugin <${plugin.getName()}>`);
94
+ pluginResource.plugin = plugin;
95
+ pluginResource.name = plugin.getName();
96
+ pluginResource.active = true;
97
+ _config.globalOasTlmConfig.dynamicExporter.pushPlugin(pluginResource);
98
+ _config.globalOasTlmConfig.dynamicExporter.activatePlugin(pluginResource.plugin);
99
+ res.status(201).send(`Plugin registered`);
100
+ } else {
101
+ console.error(`Plugin <${plugin.getName()}> can not be configured`);
102
+ res.status(400).send(`Plugin configuration problem`);
103
+ }
104
+ };
105
+ exports.registerPlugin = registerPlugin;
106
+ const checkApiKey = (req, res) => {
107
+ const apiKey = req.query.apiKey || req.body.apiKey;
108
+ if (apiKey === process.env.APIKEY) {
109
+ res.status(200).send({
110
+ valid: true
111
+ });
112
+ } else {
113
+ res.status(401).send({
114
+ valid: false
115
+ });
116
+ }
117
+ };
118
+ exports.checkApiKey = checkApiKey;
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.stopTelemetry = exports.statusTelemetry = exports.startTelemetry = exports.resetTelemetry = exports.listTelemetry = exports.heapStats = exports.findTelemetry = void 0;
7
+ var _v = _interopRequireDefault(require("v8"));
8
+ var _config = require("../config.cjs");
9
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
10
+ const startTelemetry = (req, res) => {
11
+ _config.globalOasTlmConfig.dynamicExporter.exporter.start();
12
+ res.send('Telemetry started');
13
+ };
14
+ exports.startTelemetry = startTelemetry;
15
+ const stopTelemetry = (req, res) => {
16
+ _config.globalOasTlmConfig.dynamicExporter.exporter.stop();
17
+ res.send('Telemetry stopped');
18
+ };
19
+ exports.stopTelemetry = stopTelemetry;
20
+ const statusTelemetry = (req, res) => {
21
+ const isRunning = _config.globalOasTlmConfig.dynamicExporter.exporter.isRunning() || false;
22
+ res.send({
23
+ active: isRunning
24
+ });
25
+ };
26
+ exports.statusTelemetry = statusTelemetry;
27
+ const resetTelemetry = (req, res) => {
28
+ _config.globalOasTlmConfig.dynamicExporter.exporter.reset();
29
+ res.send('Telemetry reset');
30
+ };
31
+ exports.resetTelemetry = resetTelemetry;
32
+ const listTelemetry = async (req, res) => {
33
+ try {
34
+ const spans = await _config.globalOasTlmConfig.dynamicExporter.exporter.getFinishedSpans();
35
+ res.send({
36
+ spansCount: spans.length,
37
+ spans: spans
38
+ });
39
+ } catch (err) {
40
+ console.error(err);
41
+ res.status(500).send({
42
+ error: 'Failed to list telemetry data'
43
+ });
44
+ }
45
+ };
46
+ exports.listTelemetry = listTelemetry;
47
+ const heapStats = (req, res) => {
48
+ var heapStats = _v.default.getHeapStatistics();
49
+ var roundedHeapStats = Object.getOwnPropertyNames(heapStats).reduce(function (map, stat) {
50
+ map[stat] = Math.round(heapStats[stat] / 1024 / 1024 * 1000) / 1000;
51
+ return map;
52
+ }, {});
53
+ roundedHeapStats['units'] = 'MB';
54
+ res.send(roundedHeapStats);
55
+ };
56
+ exports.heapStats = heapStats;
57
+ const findTelemetry = (req, res) => {
58
+ const body = req.body;
59
+ const search = body?.search ? body.search : {};
60
+ if (body?.flags?.containsRegex) {
61
+ try {
62
+ body.config?.regexIds?.forEach(regexId => {
63
+ if (search[regexId]) search[regexId] = new RegExp(search[regexId]);
64
+ });
65
+ } catch (e) {
66
+ console.error(e);
67
+ res.status(404).send({
68
+ spansCount: 0,
69
+ spans: [],
70
+ error: e
71
+ });
72
+ return;
73
+ }
74
+ _config.globalOasTlmConfig.dynamicExporter.exporter.find(search, (err, docs) => {
75
+ if (err) {
76
+ console.error(err);
77
+ res.status(404).send({
78
+ spansCount: 0,
79
+ spans: [],
80
+ error: err
81
+ });
82
+ return;
83
+ }
84
+ const spans = docs;
85
+ res.send({
86
+ spansCount: spans.length,
87
+ spans: spans
88
+ });
89
+ });
90
+ }
91
+ };
92
+ exports.findTelemetry = findTelemetry;
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.specLoader = exports.mainPage = exports.detailPage = exports.apiPage = void 0;
7
+ var _config = require("../config.cjs");
8
+ var _fs = require("fs");
9
+ var _path = _interopRequireDefault(require("path"));
10
+ var _jsYaml = _interopRequireDefault(require("js-yaml"));
11
+ var _uiService = _interopRequireDefault(require("../services/uiService.cjs"));
12
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
+ const apiPage = (req, res) => {
14
+ const baseURL = _config.globalOasTlmConfig.baseURL;
15
+ let text = `
16
+ <h1>Telemetry API routes:</h1>
17
+ <ul>
18
+ <li><a href="${baseURL}/start">${baseURL}/start</a></li>
19
+ <li><a href="${baseURL}/stop">${baseURL}/stop</a></li>
20
+ <li><a href="${baseURL}/status">${baseURL}/status</a></li>
21
+ <li><a href="${baseURL}/reset">${baseURL}/reset</a></li>
22
+ <li><a href="${baseURL}/list">${baseURL}/list</a></li>
23
+ <li><a href="${baseURL}/heapStats">${baseURL}/heapStats</a></li>
24
+ <li>${baseURL}/find [POST]</li>
25
+ </ul>
26
+ `;
27
+ res.send(text);
28
+ };
29
+ exports.apiPage = apiPage;
30
+ const mainPage = (req, res) => {
31
+ const baseURL = _config.globalOasTlmConfig.baseURL;
32
+ res.set('Content-Type', 'text/html');
33
+ res.send((0, _uiService.default)(baseURL).main);
34
+ };
35
+ exports.mainPage = mainPage;
36
+ const detailPage = (req, res) => {
37
+ const baseURL = _config.globalOasTlmConfig.baseURL;
38
+ res.set('Content-Type', 'text/html');
39
+ res.send((0, _uiService.default)(baseURL).detail);
40
+ };
41
+ exports.detailPage = detailPage;
42
+ const specLoader = (req, res) => {
43
+ if (_config.globalOasTlmConfig.specFileName) {
44
+ try {
45
+ const data = (0, _fs.readFileSync)(_config.globalOasTlmConfig.specFileName, {
46
+ encoding: 'utf8',
47
+ flag: 'r'
48
+ });
49
+ const extension = _path.default.extname(_config.globalOasTlmConfig.specFileName);
50
+ let json = data;
51
+ if (extension == _jsYaml.default) json = JSON.stringify(_jsYaml.default.SafeLoad(data), null, 2);
52
+ res.setHeader('Content-Type', 'application/json');
53
+ res.send(json);
54
+ } catch (e) {
55
+ console.error(`ERROR loading spec file ${_config.globalOasTlmConfig.specFileName}: ${e}`);
56
+ }
57
+ } else if (_config.globalOasTlmConfig.spec) {
58
+ let spec = false;
59
+ try {
60
+ spec = JSON.parse(_config.globalOasTlmConfig.spec);
61
+ } catch (ej) {
62
+ try {
63
+ spec = JSON.stringify(_jsYaml.default.load(_config.globalOasTlmConfig.spec), null, 2);
64
+ } catch (ey) {
65
+ console.error(`Error parsing spec: ${ej} - ${ey}`);
66
+ }
67
+ }
68
+ if (!spec) {
69
+ res.status(404);
70
+ } else {
71
+ res.setHeader('Content-Type', 'application/json');
72
+ res.send(spec);
73
+ }
74
+ } else {
75
+ res.status(404);
76
+ }
77
+ };
78
+ exports.specLoader = specLoader;