apitally 0.6.0 → 0.7.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 (198) hide show
  1. package/dist/common/client.cjs +514 -0
  2. package/dist/common/client.cjs.map +1 -0
  3. package/dist/common/client.d.cts +36 -0
  4. package/{lib/types → dist}/common/client.d.ts +13 -9
  5. package/dist/common/client.js +481 -0
  6. package/dist/common/client.js.map +1 -0
  7. package/dist/common/logging.cjs +41 -0
  8. package/dist/common/logging.cjs.map +1 -0
  9. package/dist/common/logging.d.cts +11 -0
  10. package/{lib/types → dist}/common/logging.d.ts +6 -3
  11. package/dist/common/logging.js +18 -0
  12. package/dist/common/logging.js.map +1 -0
  13. package/dist/common/packageVersions.cjs +42 -0
  14. package/dist/common/packageVersions.cjs.map +1 -0
  15. package/dist/common/packageVersions.d.cts +3 -0
  16. package/dist/common/packageVersions.d.ts +3 -0
  17. package/dist/common/packageVersions.js +18 -0
  18. package/dist/common/packageVersions.js.map +1 -0
  19. package/dist/common/paramValidation.cjs +43 -0
  20. package/dist/common/paramValidation.cjs.map +1 -0
  21. package/dist/common/paramValidation.d.cts +4 -0
  22. package/dist/common/paramValidation.d.ts +4 -0
  23. package/dist/common/paramValidation.js +19 -0
  24. package/dist/common/paramValidation.js.map +1 -0
  25. package/dist/common/requestCounter.cjs +111 -0
  26. package/dist/common/requestCounter.cjs.map +1 -0
  27. package/dist/common/requestCounter.d.cts +18 -0
  28. package/{lib/types → dist}/common/requestCounter.d.ts +7 -3
  29. package/dist/common/requestCounter.js +92 -0
  30. package/dist/common/requestCounter.js.map +1 -0
  31. package/dist/common/serverErrorCounter.cjs +133 -0
  32. package/dist/common/serverErrorCounter.cjs.map +1 -0
  33. package/dist/common/serverErrorCounter.d.cts +20 -0
  34. package/{lib/types → dist}/common/serverErrorCounter.d.ts +7 -3
  35. package/dist/common/serverErrorCounter.js +104 -0
  36. package/dist/common/serverErrorCounter.js.map +1 -0
  37. package/dist/common/types.cjs +19 -0
  38. package/dist/common/types.cjs.map +1 -0
  39. package/dist/common/types.d.cts +76 -0
  40. package/{lib/types → dist}/common/types.d.ts +17 -14
  41. package/dist/common/types.js +1 -0
  42. package/dist/common/types.js.map +1 -0
  43. package/dist/common/validationErrorCounter.cjs +76 -0
  44. package/dist/common/validationErrorCounter.cjs.map +1 -0
  45. package/dist/common/validationErrorCounter.d.cts +14 -0
  46. package/{lib/types → dist}/common/validationErrorCounter.d.ts +7 -3
  47. package/dist/common/validationErrorCounter.js +57 -0
  48. package/dist/common/validationErrorCounter.js.map +1 -0
  49. package/dist/express/index.cjs +837 -0
  50. package/dist/express/index.cjs.map +1 -0
  51. package/dist/express/index.d.cts +5 -0
  52. package/dist/express/index.d.ts +5 -0
  53. package/dist/express/index.js +801 -0
  54. package/dist/express/index.js.map +1 -0
  55. package/dist/express/listEndpoints.cjs +144 -0
  56. package/dist/express/listEndpoints.cjs.map +1 -0
  57. package/dist/express/listEndpoints.d.cts +3 -0
  58. package/dist/express/listEndpoints.d.ts +3 -0
  59. package/dist/express/listEndpoints.js +125 -0
  60. package/dist/express/listEndpoints.js.map +1 -0
  61. package/dist/express/middleware.cjs +835 -0
  62. package/dist/express/middleware.cjs.map +1 -0
  63. package/dist/express/middleware.d.cts +14 -0
  64. package/dist/express/middleware.d.ts +14 -0
  65. package/dist/express/middleware.js +801 -0
  66. package/dist/express/middleware.js.map +1 -0
  67. package/dist/fastify/index.cjs +685 -0
  68. package/dist/fastify/index.cjs.map +1 -0
  69. package/dist/fastify/index.d.cts +5 -0
  70. package/dist/fastify/index.d.ts +5 -0
  71. package/dist/fastify/index.js +649 -0
  72. package/dist/fastify/index.js.map +1 -0
  73. package/dist/fastify/plugin.cjs +679 -0
  74. package/dist/fastify/plugin.cjs.map +1 -0
  75. package/dist/fastify/plugin.d.cts +18 -0
  76. package/{lib/types → dist}/fastify/plugin.d.ts +7 -4
  77. package/dist/fastify/plugin.js +649 -0
  78. package/dist/fastify/plugin.js.map +1 -0
  79. package/dist/index.cjs +2 -0
  80. package/dist/index.cjs.map +1 -0
  81. package/dist/index.d.cts +2 -0
  82. package/dist/index.d.ts +2 -0
  83. package/dist/index.js +1 -0
  84. package/dist/index.js.map +1 -0
  85. package/dist/koa/index.cjs +655 -0
  86. package/dist/koa/index.cjs.map +1 -0
  87. package/dist/koa/index.d.cts +5 -0
  88. package/dist/koa/index.d.ts +5 -0
  89. package/dist/koa/index.js +619 -0
  90. package/dist/koa/index.js.map +1 -0
  91. package/dist/koa/middleware.cjs +655 -0
  92. package/dist/koa/middleware.cjs.map +1 -0
  93. package/dist/koa/middleware.d.cts +8 -0
  94. package/dist/koa/middleware.d.ts +8 -0
  95. package/dist/koa/middleware.js +619 -0
  96. package/dist/koa/middleware.js.map +1 -0
  97. package/dist/nestjs/index.cjs +837 -0
  98. package/dist/nestjs/index.cjs.map +1 -0
  99. package/dist/nestjs/index.d.cts +5 -0
  100. package/dist/nestjs/index.d.ts +5 -0
  101. package/dist/nestjs/index.js +801 -0
  102. package/dist/nestjs/index.js.map +1 -0
  103. package/package.json +55 -92
  104. package/lib/cjs/common/client.cjs +0 -323
  105. package/lib/cjs/common/client.cjs.map +0 -1
  106. package/lib/cjs/common/logging.cjs +0 -17
  107. package/lib/cjs/common/logging.cjs.map +0 -1
  108. package/lib/cjs/common/packageVersions.cjs +0 -16
  109. package/lib/cjs/common/packageVersions.cjs.map +0 -1
  110. package/lib/cjs/common/paramValidation.cjs +0 -16
  111. package/lib/cjs/common/paramValidation.cjs.map +0 -1
  112. package/lib/cjs/common/requestCounter.cjs +0 -108
  113. package/lib/cjs/common/requestCounter.cjs.map +0 -1
  114. package/lib/cjs/common/serverErrorCounter.cjs +0 -154
  115. package/lib/cjs/common/serverErrorCounter.cjs.map +0 -1
  116. package/lib/cjs/common/types.cjs +0 -6
  117. package/lib/cjs/common/types.cjs.map +0 -1
  118. package/lib/cjs/common/validationErrorCounter.cjs +0 -60
  119. package/lib/cjs/common/validationErrorCounter.cjs.map +0 -1
  120. package/lib/cjs/express/index.cjs +0 -13
  121. package/lib/cjs/express/index.cjs.map +0 -1
  122. package/lib/cjs/express/listEndpoints.cjs +0 -177
  123. package/lib/cjs/express/listEndpoints.cjs.map +0 -1
  124. package/lib/cjs/express/middleware.cjs +0 -189
  125. package/lib/cjs/express/middleware.cjs.map +0 -1
  126. package/lib/cjs/fastify/index.cjs +0 -14
  127. package/lib/cjs/fastify/index.cjs.map +0 -1
  128. package/lib/cjs/fastify/plugin.cjs +0 -171
  129. package/lib/cjs/fastify/plugin.cjs.map +0 -1
  130. package/lib/cjs/index.cjs +0 -6
  131. package/lib/cjs/index.cjs.map +0 -1
  132. package/lib/cjs/koa/index.cjs +0 -13
  133. package/lib/cjs/koa/index.cjs.map +0 -1
  134. package/lib/cjs/koa/middleware.cjs +0 -139
  135. package/lib/cjs/koa/middleware.cjs.map +0 -1
  136. package/lib/cjs/nestjs/index.cjs +0 -13
  137. package/lib/cjs/nestjs/index.cjs.map +0 -1
  138. package/lib/esm/common/client.js +0 -313
  139. package/lib/esm/common/client.js.map +0 -1
  140. package/lib/esm/common/logging.js +0 -11
  141. package/lib/esm/common/logging.js.map +0 -1
  142. package/lib/esm/common/packageVersions.js +0 -10
  143. package/lib/esm/common/packageVersions.js.map +0 -1
  144. package/lib/esm/common/paramValidation.js +0 -9
  145. package/lib/esm/common/paramValidation.js.map +0 -1
  146. package/lib/esm/common/requestCounter.js +0 -102
  147. package/lib/esm/common/requestCounter.js.map +0 -1
  148. package/lib/esm/common/serverErrorCounter.js +0 -143
  149. package/lib/esm/common/serverErrorCounter.js.map +0 -1
  150. package/lib/esm/common/types.js +0 -1
  151. package/lib/esm/common/types.js.map +0 -1
  152. package/lib/esm/common/validationErrorCounter.js +0 -54
  153. package/lib/esm/common/validationErrorCounter.js.map +0 -1
  154. package/lib/esm/express/index.js +0 -1
  155. package/lib/esm/express/index.js.map +0 -1
  156. package/lib/esm/express/listEndpoints.js +0 -170
  157. package/lib/esm/express/listEndpoints.js.map +0 -1
  158. package/lib/esm/express/middleware.js +0 -182
  159. package/lib/esm/express/middleware.js.map +0 -1
  160. package/lib/esm/fastify/index.js +0 -1
  161. package/lib/esm/fastify/index.js.map +0 -1
  162. package/lib/esm/fastify/plugin.js +0 -164
  163. package/lib/esm/fastify/plugin.js.map +0 -1
  164. package/lib/esm/index.js +0 -1
  165. package/lib/esm/index.js.map +0 -1
  166. package/lib/esm/koa/index.js +0 -1
  167. package/lib/esm/koa/index.js.map +0 -1
  168. package/lib/esm/koa/middleware.js +0 -132
  169. package/lib/esm/koa/middleware.js.map +0 -1
  170. package/lib/esm/nestjs/index.js +0 -1
  171. package/lib/esm/nestjs/index.js.map +0 -1
  172. package/lib/types/common/client.d.ts.map +0 -1
  173. package/lib/types/common/logging.d.ts.map +0 -1
  174. package/lib/types/common/packageVersions.d.ts +0 -2
  175. package/lib/types/common/packageVersions.d.ts.map +0 -1
  176. package/lib/types/common/paramValidation.d.ts +0 -3
  177. package/lib/types/common/paramValidation.d.ts.map +0 -1
  178. package/lib/types/common/requestCounter.d.ts.map +0 -1
  179. package/lib/types/common/serverErrorCounter.d.ts.map +0 -1
  180. package/lib/types/common/types.d.ts.map +0 -1
  181. package/lib/types/common/validationErrorCounter.d.ts.map +0 -1
  182. package/lib/types/express/index.d.ts +0 -2
  183. package/lib/types/express/index.d.ts.map +0 -1
  184. package/lib/types/express/listEndpoints.d.ts +0 -3
  185. package/lib/types/express/listEndpoints.d.ts.map +0 -1
  186. package/lib/types/express/middleware.d.ts +0 -10
  187. package/lib/types/express/middleware.d.ts.map +0 -1
  188. package/lib/types/fastify/index.d.ts +0 -2
  189. package/lib/types/fastify/index.d.ts.map +0 -1
  190. package/lib/types/fastify/plugin.d.ts.map +0 -1
  191. package/lib/types/index.d.ts +0 -2
  192. package/lib/types/index.d.ts.map +0 -1
  193. package/lib/types/koa/index.d.ts +0 -2
  194. package/lib/types/koa/index.d.ts.map +0 -1
  195. package/lib/types/koa/middleware.d.ts +0 -4
  196. package/lib/types/koa/middleware.d.ts.map +0 -1
  197. package/lib/types/nestjs/index.d.ts +0 -2
  198. package/lib/types/nestjs/index.d.ts.map +0 -1
@@ -0,0 +1,835 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
+ mod
29
+ ));
30
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
32
+
33
+ // src/express/middleware.ts
34
+ var middleware_exports = {};
35
+ __export(middleware_exports, {
36
+ useApitally: () => useApitally
37
+ });
38
+ module.exports = __toCommonJS(middleware_exports);
39
+ var import_perf_hooks = require("perf_hooks");
40
+
41
+ // src/common/client.ts
42
+ var import_crypto3 = require("crypto");
43
+ var import_fetch_retry = __toESM(require("fetch-retry"), 1);
44
+
45
+ // src/common/logging.ts
46
+ var import_winston = require("winston");
47
+ var getLogger = /* @__PURE__ */ __name(() => {
48
+ return (0, import_winston.createLogger)({
49
+ level: process.env.APITALLY_DEBUG ? "debug" : "warn",
50
+ format: import_winston.format.combine(import_winston.format.colorize(), import_winston.format.timestamp(), import_winston.format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`)),
51
+ transports: [
52
+ new import_winston.transports.Console()
53
+ ]
54
+ });
55
+ }, "getLogger");
56
+
57
+ // src/common/paramValidation.ts
58
+ function isValidClientId(clientId) {
59
+ const regexExp = /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
60
+ return regexExp.test(clientId);
61
+ }
62
+ __name(isValidClientId, "isValidClientId");
63
+ function isValidEnv(env) {
64
+ const regexExp = /^[\w-]{1,32}$/;
65
+ return regexExp.test(env);
66
+ }
67
+ __name(isValidEnv, "isValidEnv");
68
+
69
+ // src/common/requestCounter.ts
70
+ var _RequestCounter = class _RequestCounter {
71
+ requestCounts;
72
+ requestSizeSums;
73
+ responseSizeSums;
74
+ responseTimes;
75
+ requestSizes;
76
+ responseSizes;
77
+ constructor() {
78
+ this.requestCounts = /* @__PURE__ */ new Map();
79
+ this.requestSizeSums = /* @__PURE__ */ new Map();
80
+ this.responseSizeSums = /* @__PURE__ */ new Map();
81
+ this.responseTimes = /* @__PURE__ */ new Map();
82
+ this.requestSizes = /* @__PURE__ */ new Map();
83
+ this.responseSizes = /* @__PURE__ */ new Map();
84
+ }
85
+ getKey(requestInfo) {
86
+ return [
87
+ requestInfo.consumer || "",
88
+ requestInfo.method.toUpperCase(),
89
+ requestInfo.path,
90
+ requestInfo.statusCode
91
+ ].join("|");
92
+ }
93
+ addRequest(requestInfo) {
94
+ const key = this.getKey(requestInfo);
95
+ this.requestCounts.set(key, (this.requestCounts.get(key) || 0) + 1);
96
+ if (!this.responseTimes.has(key)) {
97
+ this.responseTimes.set(key, /* @__PURE__ */ new Map());
98
+ }
99
+ const responseTimeMap = this.responseTimes.get(key);
100
+ const responseTimeMsBin = Math.floor(requestInfo.responseTime / 10) * 10;
101
+ responseTimeMap.set(responseTimeMsBin, (responseTimeMap.get(responseTimeMsBin) || 0) + 1);
102
+ if (requestInfo.requestSize !== void 0) {
103
+ requestInfo.requestSize = Number(requestInfo.requestSize);
104
+ this.requestSizeSums.set(key, (this.requestSizeSums.get(key) || 0) + requestInfo.requestSize);
105
+ if (!this.requestSizes.has(key)) {
106
+ this.requestSizes.set(key, /* @__PURE__ */ new Map());
107
+ }
108
+ const requestSizeMap = this.requestSizes.get(key);
109
+ const requestSizeKbBin = Math.floor(requestInfo.requestSize / 1e3);
110
+ requestSizeMap.set(requestSizeKbBin, (requestSizeMap.get(requestSizeKbBin) || 0) + 1);
111
+ }
112
+ if (requestInfo.responseSize !== void 0) {
113
+ requestInfo.responseSize = Number(requestInfo.responseSize);
114
+ this.responseSizeSums.set(key, (this.responseSizeSums.get(key) || 0) + requestInfo.responseSize);
115
+ if (!this.responseSizes.has(key)) {
116
+ this.responseSizes.set(key, /* @__PURE__ */ new Map());
117
+ }
118
+ const responseSizeMap = this.responseSizes.get(key);
119
+ const responseSizeKbBin = Math.floor(requestInfo.responseSize / 1e3);
120
+ responseSizeMap.set(responseSizeKbBin, (responseSizeMap.get(responseSizeKbBin) || 0) + 1);
121
+ }
122
+ }
123
+ getAndResetRequests() {
124
+ const data = [];
125
+ this.requestCounts.forEach((count, key) => {
126
+ const [consumer, method, path, statusCodeStr] = key.split("|");
127
+ const responseTimes = this.responseTimes.get(key) || /* @__PURE__ */ new Map();
128
+ const requestSizes = this.requestSizes.get(key) || /* @__PURE__ */ new Map();
129
+ const responseSizes = this.responseSizes.get(key) || /* @__PURE__ */ new Map();
130
+ data.push({
131
+ consumer: consumer || null,
132
+ method,
133
+ path,
134
+ status_code: parseInt(statusCodeStr),
135
+ request_count: count,
136
+ request_size_sum: this.requestSizeSums.get(key) || 0,
137
+ response_size_sum: this.responseSizeSums.get(key) || 0,
138
+ response_times: Object.fromEntries(responseTimes),
139
+ request_sizes: Object.fromEntries(requestSizes),
140
+ response_sizes: Object.fromEntries(responseSizes)
141
+ });
142
+ });
143
+ this.requestCounts.clear();
144
+ this.requestSizeSums.clear();
145
+ this.responseSizeSums.clear();
146
+ this.responseTimes.clear();
147
+ this.requestSizes.clear();
148
+ this.responseSizes.clear();
149
+ return data;
150
+ }
151
+ };
152
+ __name(_RequestCounter, "RequestCounter");
153
+ var RequestCounter = _RequestCounter;
154
+
155
+ // src/common/serverErrorCounter.ts
156
+ var import_crypto = require("crypto");
157
+ var MAX_MSG_LENGTH = 2048;
158
+ var MAX_STACKTRACE_LENGTH = 65536;
159
+ var _ServerErrorCounter = class _ServerErrorCounter {
160
+ errorCounts;
161
+ errorDetails;
162
+ sentryEventIds;
163
+ sentry;
164
+ constructor() {
165
+ this.errorCounts = /* @__PURE__ */ new Map();
166
+ this.errorDetails = /* @__PURE__ */ new Map();
167
+ this.sentryEventIds = /* @__PURE__ */ new Map();
168
+ this.tryImportSentry();
169
+ }
170
+ addServerError(serverError) {
171
+ const key = this.getKey(serverError);
172
+ if (!this.errorDetails.has(key)) {
173
+ this.errorDetails.set(key, serverError);
174
+ }
175
+ this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
176
+ this.captureSentryEventId(key);
177
+ }
178
+ getAndResetServerErrors() {
179
+ const data = [];
180
+ this.errorCounts.forEach((count, key) => {
181
+ const serverError = this.errorDetails.get(key);
182
+ if (serverError) {
183
+ data.push({
184
+ consumer: serverError.consumer || null,
185
+ method: serverError.method,
186
+ path: serverError.path,
187
+ type: serverError.type,
188
+ msg: this.getTruncatedMessage(serverError.msg),
189
+ traceback: this.getTruncatedStack(serverError.traceback),
190
+ sentry_event_id: this.sentryEventIds.get(key) || null,
191
+ error_count: count
192
+ });
193
+ }
194
+ });
195
+ this.errorCounts.clear();
196
+ this.errorDetails.clear();
197
+ return data;
198
+ }
199
+ getKey(serverError) {
200
+ const hashInput = [
201
+ serverError.consumer || "",
202
+ serverError.method.toUpperCase(),
203
+ serverError.path,
204
+ serverError.type,
205
+ serverError.msg.trim(),
206
+ serverError.traceback.trim()
207
+ ].join("|");
208
+ return (0, import_crypto.createHash)("md5").update(hashInput).digest("hex");
209
+ }
210
+ getTruncatedMessage(msg) {
211
+ msg = msg.trim();
212
+ if (msg.length <= MAX_MSG_LENGTH) {
213
+ return msg;
214
+ }
215
+ const suffix = "... (truncated)";
216
+ const cutoff = MAX_MSG_LENGTH - suffix.length;
217
+ return msg.substring(0, cutoff) + suffix;
218
+ }
219
+ getTruncatedStack(stack) {
220
+ const suffix = "... (truncated) ...";
221
+ const cutoff = MAX_STACKTRACE_LENGTH - suffix.length;
222
+ const lines = stack.trim().split("\n");
223
+ const truncatedLines = [];
224
+ let length = 0;
225
+ for (const line of lines) {
226
+ if (length + line.length + 1 > cutoff) {
227
+ truncatedLines.push(suffix);
228
+ break;
229
+ }
230
+ truncatedLines.push(line);
231
+ length += line.length + 1;
232
+ }
233
+ return truncatedLines.join("\n");
234
+ }
235
+ captureSentryEventId(serverErrorKey) {
236
+ if (this.sentry && this.sentry.lastEventId) {
237
+ const eventId = this.sentry.lastEventId();
238
+ if (eventId) {
239
+ this.sentryEventIds.set(serverErrorKey, eventId);
240
+ }
241
+ }
242
+ }
243
+ async tryImportSentry() {
244
+ try {
245
+ this.sentry = await import("@sentry/node");
246
+ } catch (e) {
247
+ }
248
+ }
249
+ };
250
+ __name(_ServerErrorCounter, "ServerErrorCounter");
251
+ var ServerErrorCounter = _ServerErrorCounter;
252
+
253
+ // src/common/validationErrorCounter.ts
254
+ var import_crypto2 = require("crypto");
255
+ var _ValidationErrorCounter = class _ValidationErrorCounter {
256
+ errorCounts;
257
+ errorDetails;
258
+ constructor() {
259
+ this.errorCounts = /* @__PURE__ */ new Map();
260
+ this.errorDetails = /* @__PURE__ */ new Map();
261
+ }
262
+ addValidationError(validationError) {
263
+ const key = this.getKey(validationError);
264
+ if (!this.errorDetails.has(key)) {
265
+ this.errorDetails.set(key, validationError);
266
+ }
267
+ this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
268
+ }
269
+ getAndResetValidationErrors() {
270
+ const data = [];
271
+ this.errorCounts.forEach((count, key) => {
272
+ const validationError = this.errorDetails.get(key);
273
+ if (validationError) {
274
+ data.push({
275
+ consumer: validationError.consumer || null,
276
+ method: validationError.method,
277
+ path: validationError.path,
278
+ loc: validationError.loc.split("."),
279
+ msg: validationError.msg,
280
+ type: validationError.type,
281
+ error_count: count
282
+ });
283
+ }
284
+ });
285
+ this.errorCounts.clear();
286
+ this.errorDetails.clear();
287
+ return data;
288
+ }
289
+ getKey(validationError) {
290
+ const hashInput = [
291
+ validationError.consumer || "",
292
+ validationError.method.toUpperCase(),
293
+ validationError.path,
294
+ validationError.loc,
295
+ validationError.msg.trim(),
296
+ validationError.type
297
+ ].join("|");
298
+ return (0, import_crypto2.createHash)("md5").update(hashInput).digest("hex");
299
+ }
300
+ };
301
+ __name(_ValidationErrorCounter, "ValidationErrorCounter");
302
+ var ValidationErrorCounter = _ValidationErrorCounter;
303
+
304
+ // src/common/client.ts
305
+ var SYNC_INTERVAL = 6e4;
306
+ var INITIAL_SYNC_INTERVAL = 1e4;
307
+ var INITIAL_SYNC_INTERVAL_DURATION = 36e5;
308
+ var MAX_QUEUE_TIME = 36e5;
309
+ var _a;
310
+ var HTTPError = (_a = class extends Error {
311
+ response;
312
+ constructor(response) {
313
+ const reason = response.status ? `status code ${response.status}` : "an unknown error";
314
+ super(`Request failed with ${reason}`);
315
+ this.response = response;
316
+ }
317
+ }, __name(_a, "HTTPError"), _a);
318
+ var _ApitallyClient = class _ApitallyClient {
319
+ clientId;
320
+ env;
321
+ instanceUuid;
322
+ requestsDataQueue;
323
+ syncIntervalId;
324
+ appInfo;
325
+ appInfoSent = false;
326
+ requestCounter;
327
+ validationErrorCounter;
328
+ serverErrorCounter;
329
+ logger;
330
+ constructor({ clientId, env = "dev", logger }) {
331
+ if (_ApitallyClient.instance) {
332
+ throw new Error("Apitally client is already initialized");
333
+ }
334
+ if (!isValidClientId(clientId)) {
335
+ throw new Error(`Invalid client ID '${clientId}' (expecting hexadeciaml UUID format)`);
336
+ }
337
+ if (!isValidEnv(env)) {
338
+ throw new Error(`Invalid env '${env}' (expecting 1-32 alphanumeric lowercase characters and hyphens only)`);
339
+ }
340
+ _ApitallyClient.instance = this;
341
+ this.clientId = clientId;
342
+ this.env = env;
343
+ this.instanceUuid = (0, import_crypto3.randomUUID)();
344
+ this.requestsDataQueue = [];
345
+ this.requestCounter = new RequestCounter();
346
+ this.validationErrorCounter = new ValidationErrorCounter();
347
+ this.serverErrorCounter = new ServerErrorCounter();
348
+ this.logger = logger || getLogger();
349
+ this.startSync();
350
+ this.handleShutdown = this.handleShutdown.bind(this);
351
+ }
352
+ static getInstance() {
353
+ if (!_ApitallyClient.instance) {
354
+ throw new Error("Apitally client is not initialized");
355
+ }
356
+ return _ApitallyClient.instance;
357
+ }
358
+ static async shutdown() {
359
+ if (_ApitallyClient.instance) {
360
+ await _ApitallyClient.instance.handleShutdown();
361
+ }
362
+ }
363
+ async handleShutdown() {
364
+ this.stopSync();
365
+ await this.sendRequestsData();
366
+ _ApitallyClient.instance = void 0;
367
+ }
368
+ getHubUrlPrefix() {
369
+ const baseURL = process.env.APITALLY_HUB_BASE_URL || "https://hub.apitally.io";
370
+ const version = "v1";
371
+ return `${baseURL}/${version}/${this.clientId}/${this.env}/`;
372
+ }
373
+ async makeHubRequest(url, payload) {
374
+ const fetchWithRetry = (0, import_fetch_retry.default)(fetch, {
375
+ retries: 3,
376
+ retryDelay: 1e3,
377
+ retryOn: [
378
+ 408,
379
+ 429,
380
+ 500,
381
+ 502,
382
+ 503,
383
+ 504
384
+ ]
385
+ });
386
+ const response = await fetchWithRetry(this.getHubUrlPrefix() + url, {
387
+ method: "POST",
388
+ body: JSON.stringify(payload),
389
+ headers: {
390
+ "Content-Type": "application/json"
391
+ }
392
+ });
393
+ if (!response.ok) {
394
+ throw new HTTPError(response);
395
+ }
396
+ }
397
+ startSync() {
398
+ this.sync();
399
+ this.syncIntervalId = setInterval(() => {
400
+ this.sync();
401
+ }, INITIAL_SYNC_INTERVAL);
402
+ setTimeout(() => {
403
+ clearInterval(this.syncIntervalId);
404
+ this.syncIntervalId = setInterval(() => {
405
+ this.sync();
406
+ }, SYNC_INTERVAL);
407
+ }, INITIAL_SYNC_INTERVAL_DURATION);
408
+ }
409
+ async sync() {
410
+ try {
411
+ const promises = [
412
+ this.sendRequestsData()
413
+ ];
414
+ if (!this.appInfoSent) {
415
+ promises.push(this.sendAppInfo());
416
+ }
417
+ await Promise.all(promises);
418
+ } catch (error) {
419
+ this.logger.error("Error while syncing with Apitally Hub", {
420
+ error
421
+ });
422
+ }
423
+ }
424
+ stopSync() {
425
+ if (this.syncIntervalId) {
426
+ clearInterval(this.syncIntervalId);
427
+ this.syncIntervalId = void 0;
428
+ }
429
+ }
430
+ setAppInfo(appInfo) {
431
+ this.appInfo = appInfo;
432
+ this.appInfoSent = false;
433
+ this.sendAppInfo();
434
+ }
435
+ async sendAppInfo() {
436
+ if (this.appInfo) {
437
+ this.logger.debug("Sending app info to Apitally Hub");
438
+ const payload = {
439
+ instance_uuid: this.instanceUuid,
440
+ message_uuid: (0, import_crypto3.randomUUID)(),
441
+ ...this.appInfo
442
+ };
443
+ try {
444
+ await this.makeHubRequest("info", payload);
445
+ this.appInfoSent = true;
446
+ } catch (error) {
447
+ const handled = this.handleHubError(error);
448
+ if (!handled) {
449
+ this.logger.error(error.message);
450
+ this.logger.debug("Error while sending app info to Apitally Hub (will retry)", {
451
+ error
452
+ });
453
+ }
454
+ }
455
+ }
456
+ }
457
+ async sendRequestsData() {
458
+ this.logger.debug("Sending requests data to Apitally Hub");
459
+ const newPayload = {
460
+ time_offset: 0,
461
+ instance_uuid: this.instanceUuid,
462
+ message_uuid: (0, import_crypto3.randomUUID)(),
463
+ requests: this.requestCounter.getAndResetRequests(),
464
+ validation_errors: this.validationErrorCounter.getAndResetValidationErrors(),
465
+ server_errors: this.serverErrorCounter.getAndResetServerErrors()
466
+ };
467
+ this.requestsDataQueue.push([
468
+ Date.now(),
469
+ newPayload
470
+ ]);
471
+ const failedItems = [];
472
+ while (this.requestsDataQueue.length > 0) {
473
+ const queueItem = this.requestsDataQueue.shift();
474
+ if (queueItem) {
475
+ const [time, payload] = queueItem;
476
+ try {
477
+ const timeOffset = Date.now() - time;
478
+ if (timeOffset <= MAX_QUEUE_TIME) {
479
+ payload.time_offset = timeOffset / 1e3;
480
+ await this.makeHubRequest("requests", payload);
481
+ }
482
+ } catch (error) {
483
+ const handled = this.handleHubError(error);
484
+ if (!handled) {
485
+ this.logger.debug("Error while sending requests data to Apitally Hub (will retry)", {
486
+ error
487
+ });
488
+ failedItems.push(queueItem);
489
+ }
490
+ }
491
+ }
492
+ }
493
+ this.requestsDataQueue = failedItems;
494
+ }
495
+ handleHubError(error) {
496
+ if (error instanceof HTTPError) {
497
+ if (error.response.status === 404) {
498
+ this.logger.error(`Invalid Apitally client ID: '${this.clientId}'`);
499
+ this.stopSync();
500
+ return true;
501
+ }
502
+ if (error.response.status === 422) {
503
+ this.logger.error("Received validation error from Apitally Hub");
504
+ return true;
505
+ }
506
+ }
507
+ return false;
508
+ }
509
+ };
510
+ __name(_ApitallyClient, "ApitallyClient");
511
+ __publicField(_ApitallyClient, "instance");
512
+ var ApitallyClient = _ApitallyClient;
513
+
514
+ // src/common/packageVersions.ts
515
+ var import_module = require("module");
516
+ var import_meta = {};
517
+ function getPackageVersion(name) {
518
+ try {
519
+ const _require = (0, import_module.createRequire)(import_meta.url);
520
+ return _require(`${name}/package.json`).version || null;
521
+ } catch (error) {
522
+ return null;
523
+ }
524
+ }
525
+ __name(getPackageVersion, "getPackageVersion");
526
+
527
+ // src/express/listEndpoints.js
528
+ var regExpToParseExpressPathRegExp = /^\/\^\\\/(?:(:?[\w\\.-]*(?:\\\/:?[\w\\.-]*)*)|(\(\?:\(\[\^\\\/]\+\?\)\)))\\\/.*/;
529
+ var regExpToReplaceExpressPathRegExpParams = /\(\?:\(\[\^\\\/]\+\?\)\)/;
530
+ var regexpExpressParamRegexp = /\(\?:\(\[\^\\\/]\+\?\)\)/g;
531
+ var EXPRESS_ROOT_PATH_REGEXP_VALUE = "/^\\/?(?=\\/|$)/i";
532
+ var STACK_ITEM_VALID_NAMES = [
533
+ "router",
534
+ "bound dispatch",
535
+ "mounted_app"
536
+ ];
537
+ var getRouteMethods = /* @__PURE__ */ __name(function(route) {
538
+ let methods = Object.keys(route.methods);
539
+ methods = methods.filter((method) => method !== "_all");
540
+ methods = methods.map((method) => method.toUpperCase());
541
+ return methods;
542
+ }, "getRouteMethods");
543
+ var getRouteMiddlewares = /* @__PURE__ */ __name(function(route) {
544
+ return route.stack.map((item) => {
545
+ return item.handle.name || "anonymous";
546
+ });
547
+ }, "getRouteMiddlewares");
548
+ var hasParams = /* @__PURE__ */ __name(function(expressPathRegExp) {
549
+ return regexpExpressParamRegexp.test(expressPathRegExp);
550
+ }, "hasParams");
551
+ var parseExpressRoute = /* @__PURE__ */ __name(function(route, basePath) {
552
+ const paths = [];
553
+ if (Array.isArray(route.path)) {
554
+ paths.push(...route.path);
555
+ } else {
556
+ paths.push(route.path);
557
+ }
558
+ const endpoints = paths.map((path) => {
559
+ const completePath = basePath && path === "/" ? basePath : `${basePath}${path}`;
560
+ const endpoint = {
561
+ path: completePath,
562
+ methods: getRouteMethods(route),
563
+ middlewares: getRouteMiddlewares(route)
564
+ };
565
+ return endpoint;
566
+ });
567
+ return endpoints;
568
+ }, "parseExpressRoute");
569
+ var parseExpressPath = /* @__PURE__ */ __name(function(expressPathRegExp, params) {
570
+ let expressPathRegExpExec = regExpToParseExpressPathRegExp.exec(expressPathRegExp);
571
+ let parsedRegExp = expressPathRegExp.toString();
572
+ let paramIndex = 0;
573
+ while (hasParams(parsedRegExp)) {
574
+ const paramName = params[paramIndex].name;
575
+ const paramId = `:${paramName}`;
576
+ parsedRegExp = parsedRegExp.replace(regExpToReplaceExpressPathRegExpParams, paramId);
577
+ paramIndex++;
578
+ }
579
+ if (parsedRegExp !== expressPathRegExp.toString()) {
580
+ expressPathRegExpExec = regExpToParseExpressPathRegExp.exec(parsedRegExp);
581
+ }
582
+ const parsedPath = expressPathRegExpExec[1].replace(/\\\//g, "/");
583
+ return parsedPath;
584
+ }, "parseExpressPath");
585
+ var parseEndpoints = /* @__PURE__ */ __name(function(app, basePath, endpoints) {
586
+ const stack = app.stack || app._router && app._router.stack;
587
+ endpoints = endpoints || [];
588
+ basePath = basePath || "";
589
+ if (!stack) {
590
+ endpoints = addEndpoints(endpoints, [
591
+ {
592
+ path: basePath,
593
+ methods: [],
594
+ middlewares: []
595
+ }
596
+ ]);
597
+ } else {
598
+ endpoints = parseStack(stack, basePath, endpoints);
599
+ }
600
+ return endpoints;
601
+ }, "parseEndpoints");
602
+ var addEndpoints = /* @__PURE__ */ __name(function(currentEndpoints, endpointsToAdd) {
603
+ endpointsToAdd.forEach((newEndpoint) => {
604
+ const existingEndpoint = currentEndpoints.find((item) => item.path === newEndpoint.path);
605
+ if (existingEndpoint !== void 0) {
606
+ const newMethods = newEndpoint.methods.filter((method) => !existingEndpoint.methods.includes(method));
607
+ existingEndpoint.methods = existingEndpoint.methods.concat(newMethods);
608
+ } else {
609
+ currentEndpoints.push(newEndpoint);
610
+ }
611
+ });
612
+ return currentEndpoints;
613
+ }, "addEndpoints");
614
+ var parseStack = /* @__PURE__ */ __name(function(stack, basePath, endpoints) {
615
+ stack.forEach((stackItem) => {
616
+ if (stackItem.route) {
617
+ const newEndpoints = parseExpressRoute(stackItem.route, basePath);
618
+ endpoints = addEndpoints(endpoints, newEndpoints);
619
+ } else if (STACK_ITEM_VALID_NAMES.includes(stackItem.name)) {
620
+ const isExpressPathRegexp = regExpToParseExpressPathRegExp.test(stackItem.regexp);
621
+ let newBasePath = basePath;
622
+ if (isExpressPathRegexp) {
623
+ const parsedPath = parseExpressPath(stackItem.regexp, stackItem.keys);
624
+ newBasePath += `/${parsedPath}`;
625
+ } else if (!stackItem.path && stackItem.regexp && stackItem.regexp.toString() !== EXPRESS_ROOT_PATH_REGEXP_VALUE) {
626
+ const regExpPath = ` RegExp(${stackItem.regexp}) `;
627
+ newBasePath += `/${regExpPath}`;
628
+ }
629
+ endpoints = parseEndpoints(stackItem.handle, newBasePath, endpoints);
630
+ }
631
+ });
632
+ return endpoints;
633
+ }, "parseStack");
634
+ var getEndpoints = /* @__PURE__ */ __name(function(app) {
635
+ const endpoints = parseEndpoints(app);
636
+ return endpoints.flatMap((route) => route.methods.filter((method) => ![
637
+ "HEAD",
638
+ "OPTIONS"
639
+ ].includes(method.toUpperCase())).map((method) => ({
640
+ method,
641
+ path: route.path
642
+ })));
643
+ }, "getEndpoints");
644
+ var listEndpoints_default = getEndpoints;
645
+
646
+ // src/express/middleware.ts
647
+ var useApitally = /* @__PURE__ */ __name((app, config) => {
648
+ const client = new ApitallyClient(config);
649
+ const middleware = getMiddleware(app, client);
650
+ app.use(middleware);
651
+ setTimeout(() => {
652
+ client.setAppInfo(getAppInfo(app, config.appVersion));
653
+ }, 1e3);
654
+ }, "useApitally");
655
+ var getMiddleware = /* @__PURE__ */ __name((app, client) => {
656
+ const validatorInstalled = getPackageVersion("express-validator") !== null;
657
+ const celebrateInstalled = getPackageVersion("celebrate") !== null;
658
+ const nestInstalled = getPackageVersion("@nestjs/core") !== null;
659
+ const classValidatorInstalled = getPackageVersion("class-validator") !== null;
660
+ let errorHandlerConfigured = false;
661
+ return (req, res, next) => {
662
+ if (!errorHandlerConfigured) {
663
+ app.use((err, req2, res2, next2) => {
664
+ res2.locals.serverError = err;
665
+ next2(err);
666
+ });
667
+ errorHandlerConfigured = true;
668
+ }
669
+ try {
670
+ const startTime = import_perf_hooks.performance.now();
671
+ const originalJson = res.json;
672
+ res.json = (body) => {
673
+ res.locals.body = body;
674
+ return originalJson.call(res, body);
675
+ };
676
+ res.on("finish", () => {
677
+ try {
678
+ if (req.route) {
679
+ const responseTime = import_perf_hooks.performance.now() - startTime;
680
+ const consumer = getConsumer(req);
681
+ client.requestCounter.addRequest({
682
+ consumer,
683
+ method: req.method,
684
+ path: req.route.path,
685
+ statusCode: res.statusCode,
686
+ responseTime,
687
+ requestSize: req.get("content-length"),
688
+ responseSize: res.get("content-length")
689
+ });
690
+ if ((res.statusCode === 400 || res.statusCode === 422) && res.locals.body) {
691
+ const validationErrors = [];
692
+ if (validatorInstalled) {
693
+ validationErrors.push(...extractExpressValidatorErrors(res.locals.body));
694
+ }
695
+ if (celebrateInstalled) {
696
+ validationErrors.push(...extractCelebrateErrors(res.locals.body));
697
+ }
698
+ if (nestInstalled && classValidatorInstalled) {
699
+ validationErrors.push(...extractNestValidationErrors(res.locals.body));
700
+ }
701
+ validationErrors.forEach((error) => {
702
+ client.validationErrorCounter.addValidationError({
703
+ consumer,
704
+ method: req.method,
705
+ path: req.route.path,
706
+ ...error
707
+ });
708
+ });
709
+ }
710
+ if (res.statusCode === 500 && res.locals.serverError) {
711
+ const serverError = res.locals.serverError;
712
+ client.serverErrorCounter.addServerError({
713
+ consumer,
714
+ method: req.method,
715
+ path: req.route.path,
716
+ type: serverError.name,
717
+ msg: serverError.message,
718
+ traceback: serverError.stack || ""
719
+ });
720
+ }
721
+ }
722
+ } catch (error) {
723
+ client.logger.error("Error while logging request in Apitally middleware.", {
724
+ request: req,
725
+ response: res,
726
+ error
727
+ });
728
+ }
729
+ });
730
+ } catch (error) {
731
+ client.logger.error("Error in Apitally middleware.", {
732
+ request: req,
733
+ response: res,
734
+ error
735
+ });
736
+ } finally {
737
+ next();
738
+ }
739
+ };
740
+ }, "getMiddleware");
741
+ var getConsumer = /* @__PURE__ */ __name((req) => {
742
+ if (req.apitallyConsumer) {
743
+ return String(req.apitallyConsumer);
744
+ } else if (req.consumerIdentifier) {
745
+ return String(req.consumerIdentifier);
746
+ }
747
+ return null;
748
+ }, "getConsumer");
749
+ var extractExpressValidatorErrors = /* @__PURE__ */ __name((responseBody) => {
750
+ const errors = [];
751
+ if (responseBody && responseBody.errors && Array.isArray(responseBody.errors)) {
752
+ responseBody.errors.forEach((error) => {
753
+ if (error.location && error.path && error.msg && error.type) {
754
+ errors.push({
755
+ loc: `${error.location}.${error.path}`,
756
+ msg: error.msg,
757
+ type: error.type
758
+ });
759
+ }
760
+ });
761
+ }
762
+ return errors;
763
+ }, "extractExpressValidatorErrors");
764
+ var extractCelebrateErrors = /* @__PURE__ */ __name((responseBody) => {
765
+ const errors = [];
766
+ if (responseBody && responseBody.validation) {
767
+ Object.values(responseBody.validation).forEach((error) => {
768
+ if (error.source && error.keys && Array.isArray(error.keys) && error.message) {
769
+ error.keys.forEach((key) => {
770
+ errors.push({
771
+ loc: `${error.source}.${key}`,
772
+ msg: subsetJoiMessage(error.message, key),
773
+ type: ""
774
+ });
775
+ });
776
+ }
777
+ });
778
+ }
779
+ return errors;
780
+ }, "extractCelebrateErrors");
781
+ var extractNestValidationErrors = /* @__PURE__ */ __name((responseBody) => {
782
+ const errors = [];
783
+ if (responseBody && Array.isArray(responseBody.message)) {
784
+ responseBody.message.forEach((message) => {
785
+ errors.push({
786
+ loc: "",
787
+ msg: message,
788
+ type: ""
789
+ });
790
+ });
791
+ }
792
+ return errors;
793
+ }, "extractNestValidationErrors");
794
+ var subsetJoiMessage = /* @__PURE__ */ __name((message, key) => {
795
+ const messageWithKey = message.split(". ").find((message2) => message2.includes(`"${key}"`));
796
+ return messageWithKey ? messageWithKey : message;
797
+ }, "subsetJoiMessage");
798
+ var getAppInfo = /* @__PURE__ */ __name((app, appVersion) => {
799
+ const versions = [
800
+ [
801
+ "nodejs",
802
+ process.version.replace(/^v/, "")
803
+ ]
804
+ ];
805
+ const expressVersion = getPackageVersion("express");
806
+ const apitallyVersion = getPackageVersion("../..");
807
+ if (expressVersion) {
808
+ versions.push([
809
+ "express",
810
+ expressVersion
811
+ ]);
812
+ }
813
+ if (apitallyVersion) {
814
+ versions.push([
815
+ "apitally",
816
+ apitallyVersion
817
+ ]);
818
+ }
819
+ if (appVersion) {
820
+ versions.push([
821
+ "app",
822
+ appVersion
823
+ ]);
824
+ }
825
+ return {
826
+ paths: listEndpoints_default(app),
827
+ versions: Object.fromEntries(versions),
828
+ client: "js:express"
829
+ };
830
+ }, "getAppInfo");
831
+ // Annotate the CommonJS export names for ESM import in node:
832
+ 0 && (module.exports = {
833
+ useApitally
834
+ });
835
+ //# sourceMappingURL=middleware.cjs.map