@cloudnux/local-cloud-provider 0.12.0 → 0.14.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.
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
- // src/services/event-broker.ts
2
- import axios from "axios";
1
+ // src/logging/pretty-writer.ts
2
+ import chalk from "chalk";
3
+ import { EOL as EOL2 } from "os";
3
4
 
4
5
  // ../../../node_modules/lodash-es/_freeGlobal.js
5
6
  var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
@@ -963,20 +964,32 @@ var tokenUtils = {
963
964
  verifyAccessToken: verify
964
965
  };
965
966
 
966
- // ../../utils/src/logging/index.ts
967
- import chalk from "chalk";
968
- import { EOL } from "os";
969
-
970
967
  // ../../utils/src/logging/types.ts
971
968
  var logLevels = {
972
969
  fatal: -1,
973
970
  error: 0,
974
971
  warn: 1,
975
972
  info: 2,
976
- debug: 3
973
+ debug: 3,
974
+ trace: 4
977
975
  };
978
976
 
979
977
  // ../../utils/src/logging/error-to-string.ts
978
+ var safeJsonStringify = (value) => {
979
+ const seen = /* @__PURE__ */ new WeakSet();
980
+ return JSON.stringify(value, (key, currentValue) => {
981
+ if (key === "constructor") return void 0;
982
+ if (typeof currentValue === "object" && currentValue !== null) {
983
+ if (seen.has(currentValue)) return "[Circular]";
984
+ seen.add(currentValue);
985
+ }
986
+ return currentValue;
987
+ });
988
+ };
989
+ var hasOwnConstructorProp = (value) => {
990
+ if (typeof value !== "object" || value === null) return false;
991
+ return Object.prototype.hasOwnProperty.call(value, "constructor");
992
+ };
980
993
  var errorToString = (error) => {
981
994
  if (error === null) return "Null error";
982
995
  if (error === void 0) return "Undefined error";
@@ -986,13 +999,22 @@ var errorToString = (error) => {
986
999
  `Message: ${error.message}`,
987
1000
  `Stack: ${error.stack || "No stack trace available"}`,
988
1001
  // Handle additional properties that might exist on custom errors
989
- ...Object.entries(error).filter(([key]) => !["name", "message", "stack"].includes(key)).map(([key, value]) => `${key}: ${JSON.stringify(value)}`)
1002
+ ...Object.entries(error).filter(
1003
+ ([key, value]) => !["name", "message", "stack"].includes(key) && !hasOwnConstructorProp(value)
1004
+ ).map(([key, value]) => `${key}: ${safeJsonStringify(value)}`)
990
1005
  ].join("\n");
991
1006
  }
992
1007
  if (typeof error === "string") return error;
993
1008
  if (typeof error === "object") {
994
1009
  try {
995
- return JSON.stringify(error, null, 2);
1010
+ return JSON.stringify(
1011
+ error,
1012
+ (key, value) => {
1013
+ if (key === "constructor") return void 0;
1014
+ return value;
1015
+ },
1016
+ 2
1017
+ );
996
1018
  } catch {
997
1019
  return `[Object that cannot be stringified: ${Object.prototype.toString.call(error)}]`;
998
1020
  }
@@ -1000,68 +1022,130 @@ var errorToString = (error) => {
1000
1022
  return String(error);
1001
1023
  };
1002
1024
 
1025
+ // ../../utils/src/logging/writer.ts
1026
+ import { EOL } from "os";
1027
+ var jsonWriter = (entry) => {
1028
+ process.stdout.write(JSON.stringify(entry) + EOL);
1029
+ };
1030
+ var _writer = jsonWriter;
1031
+ function setWriter(writer) {
1032
+ _writer = writer;
1033
+ }
1034
+ function getWriter() {
1035
+ return _writer;
1036
+ }
1037
+
1003
1038
  // ../../utils/src/logging/index.ts
1004
- var currentLogLevel = logLevels[env("LOG_LEVEL")?.toLowerCase()] ?? logLevels.info;
1005
- var module = "default";
1006
- var requestId = "";
1007
- function initializeLogger(moduleName, requestIdValue = "") {
1008
- module = moduleName;
1009
- requestId = requestIdValue;
1010
- }
1011
- var logger = {
1012
- fatal: (message, meta) => {
1013
- if (currentLogLevel >= logLevels.fatal) {
1014
- console.error(
1015
- `[${(/* @__PURE__ */ new Date()).toTimeString()}]`,
1016
- `${chalk.bgRed.white(" fatal ")} - ${module || "unknown module"} - ${requestId || "no request ID"} - ${EOL}`,
1017
- errorToString(message),
1018
- meta ? `${EOL}${JSON.stringify(meta, null, 2)}` : ""
1019
- );
1020
- }
1021
- },
1022
- error: (message, meta) => {
1023
- if (currentLogLevel >= logLevels.error) {
1024
- console.error(
1025
- `[${(/* @__PURE__ */ new Date()).toTimeString()}]`,
1026
- `${chalk.bgRed.white(" error ")} - ${module || "unknown module"} - ${requestId || "no request ID"} - ${EOL}`,
1027
- errorToString(message),
1028
- meta ? `${EOL}${JSON.stringify(meta, null, 2)}` : ""
1029
- );
1030
- }
1031
- },
1032
- warn: (message, meta) => {
1033
- if (currentLogLevel >= logLevels.warn) {
1034
- console.warn(
1035
- `[${(/* @__PURE__ */ new Date()).toTimeString()}]`,
1036
- `${chalk.bgYellow.black(" warn ")} - ${module || "unknown module"} - ${requestId || "no request ID"} - ${EOL}`,
1037
- errorToString(message),
1038
- meta ? `${EOL}${JSON.stringify(meta, null, 2)}` : ""
1039
- );
1040
- }
1041
- },
1042
- info: (message, meta) => {
1043
- if (currentLogLevel >= logLevels.info) {
1044
- console.info(
1045
- `[${(/* @__PURE__ */ new Date()).toTimeString()}]`,
1046
- `${chalk.bgBlue.white(" info ")} - ${module || "unknown module"} - ${requestId || "no request ID"} - ${EOL}`,
1047
- message,
1048
- meta ? `${EOL}${JSON.stringify(meta, null, 2)}` : ""
1049
- );
1050
- }
1051
- },
1052
- debug: (message, meta) => {
1053
- if (currentLogLevel >= logLevels.debug) {
1054
- console.debug(
1055
- `[${(/* @__PURE__ */ new Date()).toTimeString()}]`,
1056
- `${chalk.bgWhite.black(" debug ")} - ${module || "unknown module"} - ${requestId || "no request ID"} - ${EOL}`,
1057
- message,
1058
- meta ? `${EOL}${JSON.stringify(meta, null, 2)}` : ""
1059
- );
1060
- }
1039
+ var levelValues = {
1040
+ fatal: 70,
1041
+ error: 60,
1042
+ warn: 50,
1043
+ info: 40,
1044
+ debug: 30,
1045
+ trace: 20
1046
+ };
1047
+ var currentLogLevel = 2;
1048
+ var _module = "default";
1049
+ var _requestId = "";
1050
+ function writeLine(level, mergeObject, msg, bindings) {
1051
+ getWriter()({
1052
+ level: levelValues[level],
1053
+ levelName: level,
1054
+ time: Date.now(),
1055
+ module: bindings.module || _module,
1056
+ reqId: bindings.reqId || _requestId,
1057
+ msg: level === "error" || level === "fatal" ? errorToString(msg) : msg,
1058
+ ...mergeObject ? { meta: mergeObject } : {}
1059
+ });
1060
+ }
1061
+ function createLogger(bindings = {}) {
1062
+ const currentLogLevelName = env("LOG_LEVEL")?.toLowerCase() ?? "info";
1063
+ currentLogLevel = logLevels[currentLogLevelName] ?? logLevels.info;
1064
+ return {
1065
+ level: currentLogLevelName,
1066
+ fatal: (mergeObject, msg) => {
1067
+ if (currentLogLevel >= logLevels.fatal) {
1068
+ typeof mergeObject === "string" || mergeObject instanceof Error ? writeLine("fatal", null, mergeObject, bindings) : writeLine("fatal", mergeObject, msg ?? "", bindings);
1069
+ }
1070
+ },
1071
+ error: (mergeObject, msg) => {
1072
+ if (currentLogLevel >= logLevels.error) {
1073
+ typeof mergeObject === "string" || mergeObject instanceof Error ? writeLine("error", null, mergeObject, bindings) : writeLine("error", mergeObject, msg ?? "", bindings);
1074
+ }
1075
+ },
1076
+ warn: (mergeObject, msg) => {
1077
+ if (currentLogLevel >= logLevels.warn) {
1078
+ typeof mergeObject === "string" ? writeLine("warn", null, mergeObject, bindings) : writeLine("warn", mergeObject, msg ?? "", bindings);
1079
+ }
1080
+ },
1081
+ info: (mergeObject, msg) => {
1082
+ if (currentLogLevel >= logLevels.info) {
1083
+ typeof mergeObject === "string" ? writeLine("info", null, mergeObject, bindings) : writeLine("info", mergeObject, msg ?? "", bindings);
1084
+ }
1085
+ },
1086
+ debug: (mergeObject, msg) => {
1087
+ if (currentLogLevel >= logLevels.debug) {
1088
+ typeof mergeObject === "string" ? writeLine("debug", null, mergeObject, bindings) : writeLine("debug", mergeObject, msg ?? "", bindings);
1089
+ }
1090
+ },
1091
+ trace: (mergeObject, msg) => {
1092
+ if (currentLogLevel >= logLevels.trace) {
1093
+ typeof mergeObject === "string" ? writeLine("trace", null, mergeObject, bindings) : writeLine("trace", mergeObject, msg ?? "", bindings);
1094
+ }
1095
+ },
1096
+ silent: () => {
1097
+ },
1098
+ child: (childBindings) => createLogger({ ...bindings, ...childBindings })
1099
+ };
1100
+ }
1101
+ var logger = createLogger();
1102
+
1103
+ // src/logging/pretty-writer.ts
1104
+ var levelColor = {
1105
+ fatal: chalk.bgRed.white,
1106
+ error: chalk.red,
1107
+ warn: chalk.yellow,
1108
+ info: chalk.cyan,
1109
+ debug: chalk.gray,
1110
+ trace: chalk.white
1111
+ };
1112
+ function formatTime(ms) {
1113
+ return new Date(ms).toTimeString().slice(0, 8);
1114
+ }
1115
+ function formatMeta(meta) {
1116
+ const { req, res, ...rest } = meta;
1117
+ const lines = [];
1118
+ if (req) {
1119
+ const reqParts = [`${req.method} ${req.url}`];
1120
+ if (req.remoteAddress) reqParts.push(`from ${req.remoteAddress}:${req.remotePort ?? ""}`);
1121
+ if (req.headers) reqParts.push(`headers=${JSON.stringify(req.headers, null, 2)}`);
1122
+ if (req.body !== void 0) reqParts.push(`body=${typeof req.body === "string" ? req.body : JSON.stringify(req.body, null, 2)}`);
1123
+ lines.push(chalk.dim(" req: " + reqParts.join(" ")));
1124
+ }
1125
+ if (res) {
1126
+ const resParts = [`${res.statusCode}`];
1127
+ if (res.headers) resParts.push(`headers=${JSON.stringify(res.headers, null, 2)}`);
1128
+ if (res.body !== void 0) resParts.push(`body=${typeof res.body === "string" ? res.body : JSON.stringify(res.body, null, 2)}`);
1129
+ lines.push(chalk.dim(" res: " + resParts.join(" ")));
1130
+ }
1131
+ if (Object.keys(rest).length) {
1132
+ lines.push(chalk.dim(" " + JSON.stringify(rest, null, 2)));
1061
1133
  }
1134
+ return lines.length ? EOL2 + lines.join(EOL2) : "";
1135
+ }
1136
+ var prettyWriter = (entry) => {
1137
+ const color = levelColor[entry.levelName] ?? chalk.white;
1138
+ const time = chalk.dim(formatTime(entry.time));
1139
+ const level = color(entry.levelName.toUpperCase().padEnd(5));
1140
+ const module = chalk.magenta(entry.module);
1141
+ const reqId = entry.reqId ? chalk.dim(`[${entry.reqId}]`) + " " : "";
1142
+ const meta = entry.meta ? formatMeta(entry.meta) : "";
1143
+ process.stdout.write(`${time} ${level} ${module} ${reqId}- ${entry.msg}${meta}${EOL2}`);
1062
1144
  };
1145
+ setWriter(prettyWriter);
1063
1146
 
1064
1147
  // src/services/event-broker.ts
1148
+ import axios from "axios";
1065
1149
  function createLocalEventBrokerService() {
1066
1150
  const baseURL = env("DEV_CLOUD_EVENT_BROKER_URL", "http://localhost:3000");
1067
1151
  function getQueueUrl(queueName) {
@@ -1089,6 +1173,8 @@ function createLocalEventBrokerService() {
1089
1173
  * @returns Promise resolving when publishing is complete
1090
1174
  */
1091
1175
  async publish(target, message, options) {
1176
+ if (!target)
1177
+ throw new Error("Target queue name or URL is required for publishing a message.");
1092
1178
  const queueUrl = getQueueUrl(target);
1093
1179
  const headers = {};
1094
1180
  if (options?.attributes) {
@@ -1255,7 +1341,7 @@ function createLocalStorageService() {
1255
1341
  await unlink(metadataPath);
1256
1342
  } catch (error) {
1257
1343
  if (error.code !== "ENOENT") {
1258
- logger.warn("Error deleting metadata file:", { error });
1344
+ logger.warn({ error }, "Error deleting metadata file:");
1259
1345
  }
1260
1346
  }
1261
1347
  } catch (error) {
@@ -1740,13 +1826,30 @@ function createLocalFunctionsService() {
1740
1826
  createEventRequest: (message) => {
1741
1827
  const eventRequest = {
1742
1828
  body: message.payload,
1743
- attributes: message.attributes,
1829
+ attributes: {
1830
+ ...message.attributes,
1831
+ messageId: message.id
1832
+ },
1744
1833
  requestId: message.id,
1745
1834
  timestamp: message.timestamp,
1746
1835
  attempts: message.attempts
1747
1836
  };
1748
1837
  return [eventRequest];
1749
1838
  },
1839
+ createWebSocketRequest: (connectionId, event, data, request) => {
1840
+ logger.info(request.params);
1841
+ const wsRequest = {
1842
+ connectionId,
1843
+ event,
1844
+ url: getFullUrlFromRequest(request),
1845
+ params: request.params,
1846
+ body: data,
1847
+ queryString: request.query,
1848
+ headers: request.headers,
1849
+ requestId: request.id
1850
+ };
1851
+ return [wsRequest];
1852
+ },
1750
1853
  buildHttpResponse: (context, _, reply) => {
1751
1854
  reply.headers(context.response.headers ?? {}).status(context.response.status).send(context.response.body);
1752
1855
  },
@@ -1756,26 +1859,21 @@ function createLocalFunctionsService() {
1756
1859
  }
1757
1860
  return context.response.body;
1758
1861
  },
1759
- buildEventResponse: (context) => {
1862
+ buildEventResponse: async (context) => {
1760
1863
  if (context.response.status === "error") {
1761
- throw new Error(JSON.stringify(context.response.body));
1864
+ const { messageId } = context.attributes();
1865
+ return { failureId: messageId };
1762
1866
  }
1763
- return context.response.body;
1867
+ return void 0;
1764
1868
  },
1765
- createWebSocketRequest: (connectionId, event, data) => {
1766
- const wsRequest = {
1767
- connectionId,
1768
- event,
1769
- path: "",
1770
- body: data
1771
- };
1772
- return [wsRequest];
1773
- },
1774
- buildWebSocketResponse: (context) => {
1869
+ buildWebSocketResponse: (context, _, __, ___, ____, reply) => {
1775
1870
  if (context.response.status === "error") {
1776
- throw new Error(JSON.stringify(context.response.body));
1871
+ if (reply) {
1872
+ return reply.status(context.response.statusCode ?? 500).send(context.response.body);
1873
+ }
1874
+ return void 0;
1777
1875
  }
1778
- return context.response.body;
1876
+ return void 0;
1779
1877
  }
1780
1878
  };
1781
1879
  }
@@ -1792,6 +1890,12 @@ function createLocalWebSocketService() {
1792
1890
  throw new Error("WebSocket plugin not initialized");
1793
1891
  }
1794
1892
  return _manager.sendToClient(connectionId, data);
1893
+ },
1894
+ async disconnect(connectionId) {
1895
+ if (!_manager) {
1896
+ throw new Error("WebSocket plugin not initialized");
1897
+ }
1898
+ return _manager.disconnect(connectionId);
1795
1899
  }
1796
1900
  };
1797
1901
  }
@@ -1804,34 +1908,19 @@ import fastifyPrintRoutes from "fastify-print-routes";
1804
1908
  function createRouter(options = {}) {
1805
1909
  const fastify = Fastify({
1806
1910
  maxParamLength: 1e3,
1807
- logger: options.logger ? {
1808
- transport: {
1809
- target: "pino-pretty",
1810
- options: {
1811
- colorize: true,
1812
- translateTime: "HH:MM:ss Z",
1813
- ignore: "pid,hostname"
1814
- }
1815
- }
1816
- } : void 0
1911
+ ...options.logger ? { loggerInstance: logger } : {}
1817
1912
  });
1818
1913
  fastify.register(fastifyRawBody, {
1819
1914
  field: "rawBody",
1820
1915
  encoding: "utf8"
1821
1916
  });
1822
- fastify.register(cors, {});
1917
+ fastify.register(cors, {
1918
+ "methods": ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]
1919
+ });
1823
1920
  fastify.register(fastifyPrintRoutes);
1824
1921
  fastify.addHook("onReady", () => {
1825
1922
  setWebSocketManager(fastify.websockets);
1826
1923
  });
1827
- fastify.addHook("onRequest", async (request) => {
1828
- const [pathname] = request.url.split("?");
1829
- const match = pathname.match(/^\/api\/([^/]+)(?:\/([^/]+))?/);
1830
- initializeLogger(match?.[2] || "", request.id);
1831
- });
1832
- fastify.addHook("onResponse", async () => {
1833
- initializeLogger("default", void 0);
1834
- });
1835
1924
  return fastify;
1836
1925
  }
1837
1926