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,655 @@
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/koa/middleware.ts
34
+ var middleware_exports = {};
35
+ __export(middleware_exports, {
36
+ useApitally: () => useApitally
37
+ });
38
+ module.exports = __toCommonJS(middleware_exports);
39
+
40
+ // src/common/client.ts
41
+ var import_crypto3 = require("crypto");
42
+ var import_fetch_retry = __toESM(require("fetch-retry"), 1);
43
+
44
+ // src/common/logging.ts
45
+ var import_winston = require("winston");
46
+ var getLogger = /* @__PURE__ */ __name(() => {
47
+ return (0, import_winston.createLogger)({
48
+ level: process.env.APITALLY_DEBUG ? "debug" : "warn",
49
+ format: import_winston.format.combine(import_winston.format.colorize(), import_winston.format.timestamp(), import_winston.format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`)),
50
+ transports: [
51
+ new import_winston.transports.Console()
52
+ ]
53
+ });
54
+ }, "getLogger");
55
+
56
+ // src/common/paramValidation.ts
57
+ function isValidClientId(clientId) {
58
+ 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;
59
+ return regexExp.test(clientId);
60
+ }
61
+ __name(isValidClientId, "isValidClientId");
62
+ function isValidEnv(env) {
63
+ const regexExp = /^[\w-]{1,32}$/;
64
+ return regexExp.test(env);
65
+ }
66
+ __name(isValidEnv, "isValidEnv");
67
+
68
+ // src/common/requestCounter.ts
69
+ var _RequestCounter = class _RequestCounter {
70
+ requestCounts;
71
+ requestSizeSums;
72
+ responseSizeSums;
73
+ responseTimes;
74
+ requestSizes;
75
+ responseSizes;
76
+ constructor() {
77
+ this.requestCounts = /* @__PURE__ */ new Map();
78
+ this.requestSizeSums = /* @__PURE__ */ new Map();
79
+ this.responseSizeSums = /* @__PURE__ */ new Map();
80
+ this.responseTimes = /* @__PURE__ */ new Map();
81
+ this.requestSizes = /* @__PURE__ */ new Map();
82
+ this.responseSizes = /* @__PURE__ */ new Map();
83
+ }
84
+ getKey(requestInfo) {
85
+ return [
86
+ requestInfo.consumer || "",
87
+ requestInfo.method.toUpperCase(),
88
+ requestInfo.path,
89
+ requestInfo.statusCode
90
+ ].join("|");
91
+ }
92
+ addRequest(requestInfo) {
93
+ const key = this.getKey(requestInfo);
94
+ this.requestCounts.set(key, (this.requestCounts.get(key) || 0) + 1);
95
+ if (!this.responseTimes.has(key)) {
96
+ this.responseTimes.set(key, /* @__PURE__ */ new Map());
97
+ }
98
+ const responseTimeMap = this.responseTimes.get(key);
99
+ const responseTimeMsBin = Math.floor(requestInfo.responseTime / 10) * 10;
100
+ responseTimeMap.set(responseTimeMsBin, (responseTimeMap.get(responseTimeMsBin) || 0) + 1);
101
+ if (requestInfo.requestSize !== void 0) {
102
+ requestInfo.requestSize = Number(requestInfo.requestSize);
103
+ this.requestSizeSums.set(key, (this.requestSizeSums.get(key) || 0) + requestInfo.requestSize);
104
+ if (!this.requestSizes.has(key)) {
105
+ this.requestSizes.set(key, /* @__PURE__ */ new Map());
106
+ }
107
+ const requestSizeMap = this.requestSizes.get(key);
108
+ const requestSizeKbBin = Math.floor(requestInfo.requestSize / 1e3);
109
+ requestSizeMap.set(requestSizeKbBin, (requestSizeMap.get(requestSizeKbBin) || 0) + 1);
110
+ }
111
+ if (requestInfo.responseSize !== void 0) {
112
+ requestInfo.responseSize = Number(requestInfo.responseSize);
113
+ this.responseSizeSums.set(key, (this.responseSizeSums.get(key) || 0) + requestInfo.responseSize);
114
+ if (!this.responseSizes.has(key)) {
115
+ this.responseSizes.set(key, /* @__PURE__ */ new Map());
116
+ }
117
+ const responseSizeMap = this.responseSizes.get(key);
118
+ const responseSizeKbBin = Math.floor(requestInfo.responseSize / 1e3);
119
+ responseSizeMap.set(responseSizeKbBin, (responseSizeMap.get(responseSizeKbBin) || 0) + 1);
120
+ }
121
+ }
122
+ getAndResetRequests() {
123
+ const data = [];
124
+ this.requestCounts.forEach((count, key) => {
125
+ const [consumer, method, path, statusCodeStr] = key.split("|");
126
+ const responseTimes = this.responseTimes.get(key) || /* @__PURE__ */ new Map();
127
+ const requestSizes = this.requestSizes.get(key) || /* @__PURE__ */ new Map();
128
+ const responseSizes = this.responseSizes.get(key) || /* @__PURE__ */ new Map();
129
+ data.push({
130
+ consumer: consumer || null,
131
+ method,
132
+ path,
133
+ status_code: parseInt(statusCodeStr),
134
+ request_count: count,
135
+ request_size_sum: this.requestSizeSums.get(key) || 0,
136
+ response_size_sum: this.responseSizeSums.get(key) || 0,
137
+ response_times: Object.fromEntries(responseTimes),
138
+ request_sizes: Object.fromEntries(requestSizes),
139
+ response_sizes: Object.fromEntries(responseSizes)
140
+ });
141
+ });
142
+ this.requestCounts.clear();
143
+ this.requestSizeSums.clear();
144
+ this.responseSizeSums.clear();
145
+ this.responseTimes.clear();
146
+ this.requestSizes.clear();
147
+ this.responseSizes.clear();
148
+ return data;
149
+ }
150
+ };
151
+ __name(_RequestCounter, "RequestCounter");
152
+ var RequestCounter = _RequestCounter;
153
+
154
+ // src/common/serverErrorCounter.ts
155
+ var import_crypto = require("crypto");
156
+ var MAX_MSG_LENGTH = 2048;
157
+ var MAX_STACKTRACE_LENGTH = 65536;
158
+ var _ServerErrorCounter = class _ServerErrorCounter {
159
+ errorCounts;
160
+ errorDetails;
161
+ sentryEventIds;
162
+ sentry;
163
+ constructor() {
164
+ this.errorCounts = /* @__PURE__ */ new Map();
165
+ this.errorDetails = /* @__PURE__ */ new Map();
166
+ this.sentryEventIds = /* @__PURE__ */ new Map();
167
+ this.tryImportSentry();
168
+ }
169
+ addServerError(serverError) {
170
+ const key = this.getKey(serverError);
171
+ if (!this.errorDetails.has(key)) {
172
+ this.errorDetails.set(key, serverError);
173
+ }
174
+ this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
175
+ this.captureSentryEventId(key);
176
+ }
177
+ getAndResetServerErrors() {
178
+ const data = [];
179
+ this.errorCounts.forEach((count, key) => {
180
+ const serverError = this.errorDetails.get(key);
181
+ if (serverError) {
182
+ data.push({
183
+ consumer: serverError.consumer || null,
184
+ method: serverError.method,
185
+ path: serverError.path,
186
+ type: serverError.type,
187
+ msg: this.getTruncatedMessage(serverError.msg),
188
+ traceback: this.getTruncatedStack(serverError.traceback),
189
+ sentry_event_id: this.sentryEventIds.get(key) || null,
190
+ error_count: count
191
+ });
192
+ }
193
+ });
194
+ this.errorCounts.clear();
195
+ this.errorDetails.clear();
196
+ return data;
197
+ }
198
+ getKey(serverError) {
199
+ const hashInput = [
200
+ serverError.consumer || "",
201
+ serverError.method.toUpperCase(),
202
+ serverError.path,
203
+ serverError.type,
204
+ serverError.msg.trim(),
205
+ serverError.traceback.trim()
206
+ ].join("|");
207
+ return (0, import_crypto.createHash)("md5").update(hashInput).digest("hex");
208
+ }
209
+ getTruncatedMessage(msg) {
210
+ msg = msg.trim();
211
+ if (msg.length <= MAX_MSG_LENGTH) {
212
+ return msg;
213
+ }
214
+ const suffix = "... (truncated)";
215
+ const cutoff = MAX_MSG_LENGTH - suffix.length;
216
+ return msg.substring(0, cutoff) + suffix;
217
+ }
218
+ getTruncatedStack(stack) {
219
+ const suffix = "... (truncated) ...";
220
+ const cutoff = MAX_STACKTRACE_LENGTH - suffix.length;
221
+ const lines = stack.trim().split("\n");
222
+ const truncatedLines = [];
223
+ let length = 0;
224
+ for (const line of lines) {
225
+ if (length + line.length + 1 > cutoff) {
226
+ truncatedLines.push(suffix);
227
+ break;
228
+ }
229
+ truncatedLines.push(line);
230
+ length += line.length + 1;
231
+ }
232
+ return truncatedLines.join("\n");
233
+ }
234
+ captureSentryEventId(serverErrorKey) {
235
+ if (this.sentry && this.sentry.lastEventId) {
236
+ const eventId = this.sentry.lastEventId();
237
+ if (eventId) {
238
+ this.sentryEventIds.set(serverErrorKey, eventId);
239
+ }
240
+ }
241
+ }
242
+ async tryImportSentry() {
243
+ try {
244
+ this.sentry = await import("@sentry/node");
245
+ } catch (e) {
246
+ }
247
+ }
248
+ };
249
+ __name(_ServerErrorCounter, "ServerErrorCounter");
250
+ var ServerErrorCounter = _ServerErrorCounter;
251
+
252
+ // src/common/validationErrorCounter.ts
253
+ var import_crypto2 = require("crypto");
254
+ var _ValidationErrorCounter = class _ValidationErrorCounter {
255
+ errorCounts;
256
+ errorDetails;
257
+ constructor() {
258
+ this.errorCounts = /* @__PURE__ */ new Map();
259
+ this.errorDetails = /* @__PURE__ */ new Map();
260
+ }
261
+ addValidationError(validationError) {
262
+ const key = this.getKey(validationError);
263
+ if (!this.errorDetails.has(key)) {
264
+ this.errorDetails.set(key, validationError);
265
+ }
266
+ this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
267
+ }
268
+ getAndResetValidationErrors() {
269
+ const data = [];
270
+ this.errorCounts.forEach((count, key) => {
271
+ const validationError = this.errorDetails.get(key);
272
+ if (validationError) {
273
+ data.push({
274
+ consumer: validationError.consumer || null,
275
+ method: validationError.method,
276
+ path: validationError.path,
277
+ loc: validationError.loc.split("."),
278
+ msg: validationError.msg,
279
+ type: validationError.type,
280
+ error_count: count
281
+ });
282
+ }
283
+ });
284
+ this.errorCounts.clear();
285
+ this.errorDetails.clear();
286
+ return data;
287
+ }
288
+ getKey(validationError) {
289
+ const hashInput = [
290
+ validationError.consumer || "",
291
+ validationError.method.toUpperCase(),
292
+ validationError.path,
293
+ validationError.loc,
294
+ validationError.msg.trim(),
295
+ validationError.type
296
+ ].join("|");
297
+ return (0, import_crypto2.createHash)("md5").update(hashInput).digest("hex");
298
+ }
299
+ };
300
+ __name(_ValidationErrorCounter, "ValidationErrorCounter");
301
+ var ValidationErrorCounter = _ValidationErrorCounter;
302
+
303
+ // src/common/client.ts
304
+ var SYNC_INTERVAL = 6e4;
305
+ var INITIAL_SYNC_INTERVAL = 1e4;
306
+ var INITIAL_SYNC_INTERVAL_DURATION = 36e5;
307
+ var MAX_QUEUE_TIME = 36e5;
308
+ var _a;
309
+ var HTTPError = (_a = class extends Error {
310
+ response;
311
+ constructor(response) {
312
+ const reason = response.status ? `status code ${response.status}` : "an unknown error";
313
+ super(`Request failed with ${reason}`);
314
+ this.response = response;
315
+ }
316
+ }, __name(_a, "HTTPError"), _a);
317
+ var _ApitallyClient = class _ApitallyClient {
318
+ clientId;
319
+ env;
320
+ instanceUuid;
321
+ requestsDataQueue;
322
+ syncIntervalId;
323
+ appInfo;
324
+ appInfoSent = false;
325
+ requestCounter;
326
+ validationErrorCounter;
327
+ serverErrorCounter;
328
+ logger;
329
+ constructor({ clientId, env = "dev", logger }) {
330
+ if (_ApitallyClient.instance) {
331
+ throw new Error("Apitally client is already initialized");
332
+ }
333
+ if (!isValidClientId(clientId)) {
334
+ throw new Error(`Invalid client ID '${clientId}' (expecting hexadeciaml UUID format)`);
335
+ }
336
+ if (!isValidEnv(env)) {
337
+ throw new Error(`Invalid env '${env}' (expecting 1-32 alphanumeric lowercase characters and hyphens only)`);
338
+ }
339
+ _ApitallyClient.instance = this;
340
+ this.clientId = clientId;
341
+ this.env = env;
342
+ this.instanceUuid = (0, import_crypto3.randomUUID)();
343
+ this.requestsDataQueue = [];
344
+ this.requestCounter = new RequestCounter();
345
+ this.validationErrorCounter = new ValidationErrorCounter();
346
+ this.serverErrorCounter = new ServerErrorCounter();
347
+ this.logger = logger || getLogger();
348
+ this.startSync();
349
+ this.handleShutdown = this.handleShutdown.bind(this);
350
+ }
351
+ static getInstance() {
352
+ if (!_ApitallyClient.instance) {
353
+ throw new Error("Apitally client is not initialized");
354
+ }
355
+ return _ApitallyClient.instance;
356
+ }
357
+ static async shutdown() {
358
+ if (_ApitallyClient.instance) {
359
+ await _ApitallyClient.instance.handleShutdown();
360
+ }
361
+ }
362
+ async handleShutdown() {
363
+ this.stopSync();
364
+ await this.sendRequestsData();
365
+ _ApitallyClient.instance = void 0;
366
+ }
367
+ getHubUrlPrefix() {
368
+ const baseURL = process.env.APITALLY_HUB_BASE_URL || "https://hub.apitally.io";
369
+ const version = "v1";
370
+ return `${baseURL}/${version}/${this.clientId}/${this.env}/`;
371
+ }
372
+ async makeHubRequest(url, payload) {
373
+ const fetchWithRetry = (0, import_fetch_retry.default)(fetch, {
374
+ retries: 3,
375
+ retryDelay: 1e3,
376
+ retryOn: [
377
+ 408,
378
+ 429,
379
+ 500,
380
+ 502,
381
+ 503,
382
+ 504
383
+ ]
384
+ });
385
+ const response = await fetchWithRetry(this.getHubUrlPrefix() + url, {
386
+ method: "POST",
387
+ body: JSON.stringify(payload),
388
+ headers: {
389
+ "Content-Type": "application/json"
390
+ }
391
+ });
392
+ if (!response.ok) {
393
+ throw new HTTPError(response);
394
+ }
395
+ }
396
+ startSync() {
397
+ this.sync();
398
+ this.syncIntervalId = setInterval(() => {
399
+ this.sync();
400
+ }, INITIAL_SYNC_INTERVAL);
401
+ setTimeout(() => {
402
+ clearInterval(this.syncIntervalId);
403
+ this.syncIntervalId = setInterval(() => {
404
+ this.sync();
405
+ }, SYNC_INTERVAL);
406
+ }, INITIAL_SYNC_INTERVAL_DURATION);
407
+ }
408
+ async sync() {
409
+ try {
410
+ const promises = [
411
+ this.sendRequestsData()
412
+ ];
413
+ if (!this.appInfoSent) {
414
+ promises.push(this.sendAppInfo());
415
+ }
416
+ await Promise.all(promises);
417
+ } catch (error) {
418
+ this.logger.error("Error while syncing with Apitally Hub", {
419
+ error
420
+ });
421
+ }
422
+ }
423
+ stopSync() {
424
+ if (this.syncIntervalId) {
425
+ clearInterval(this.syncIntervalId);
426
+ this.syncIntervalId = void 0;
427
+ }
428
+ }
429
+ setAppInfo(appInfo) {
430
+ this.appInfo = appInfo;
431
+ this.appInfoSent = false;
432
+ this.sendAppInfo();
433
+ }
434
+ async sendAppInfo() {
435
+ if (this.appInfo) {
436
+ this.logger.debug("Sending app info to Apitally Hub");
437
+ const payload = {
438
+ instance_uuid: this.instanceUuid,
439
+ message_uuid: (0, import_crypto3.randomUUID)(),
440
+ ...this.appInfo
441
+ };
442
+ try {
443
+ await this.makeHubRequest("info", payload);
444
+ this.appInfoSent = true;
445
+ } catch (error) {
446
+ const handled = this.handleHubError(error);
447
+ if (!handled) {
448
+ this.logger.error(error.message);
449
+ this.logger.debug("Error while sending app info to Apitally Hub (will retry)", {
450
+ error
451
+ });
452
+ }
453
+ }
454
+ }
455
+ }
456
+ async sendRequestsData() {
457
+ this.logger.debug("Sending requests data to Apitally Hub");
458
+ const newPayload = {
459
+ time_offset: 0,
460
+ instance_uuid: this.instanceUuid,
461
+ message_uuid: (0, import_crypto3.randomUUID)(),
462
+ requests: this.requestCounter.getAndResetRequests(),
463
+ validation_errors: this.validationErrorCounter.getAndResetValidationErrors(),
464
+ server_errors: this.serverErrorCounter.getAndResetServerErrors()
465
+ };
466
+ this.requestsDataQueue.push([
467
+ Date.now(),
468
+ newPayload
469
+ ]);
470
+ const failedItems = [];
471
+ while (this.requestsDataQueue.length > 0) {
472
+ const queueItem = this.requestsDataQueue.shift();
473
+ if (queueItem) {
474
+ const [time, payload] = queueItem;
475
+ try {
476
+ const timeOffset = Date.now() - time;
477
+ if (timeOffset <= MAX_QUEUE_TIME) {
478
+ payload.time_offset = timeOffset / 1e3;
479
+ await this.makeHubRequest("requests", payload);
480
+ }
481
+ } catch (error) {
482
+ const handled = this.handleHubError(error);
483
+ if (!handled) {
484
+ this.logger.debug("Error while sending requests data to Apitally Hub (will retry)", {
485
+ error
486
+ });
487
+ failedItems.push(queueItem);
488
+ }
489
+ }
490
+ }
491
+ }
492
+ this.requestsDataQueue = failedItems;
493
+ }
494
+ handleHubError(error) {
495
+ if (error instanceof HTTPError) {
496
+ if (error.response.status === 404) {
497
+ this.logger.error(`Invalid Apitally client ID: '${this.clientId}'`);
498
+ this.stopSync();
499
+ return true;
500
+ }
501
+ if (error.response.status === 422) {
502
+ this.logger.error("Received validation error from Apitally Hub");
503
+ return true;
504
+ }
505
+ }
506
+ return false;
507
+ }
508
+ };
509
+ __name(_ApitallyClient, "ApitallyClient");
510
+ __publicField(_ApitallyClient, "instance");
511
+ var ApitallyClient = _ApitallyClient;
512
+
513
+ // src/common/packageVersions.ts
514
+ var import_module = require("module");
515
+ var import_meta = {};
516
+ function getPackageVersion(name) {
517
+ try {
518
+ const _require = (0, import_module.createRequire)(import_meta.url);
519
+ return _require(`${name}/package.json`).version || null;
520
+ } catch (error) {
521
+ return null;
522
+ }
523
+ }
524
+ __name(getPackageVersion, "getPackageVersion");
525
+
526
+ // src/koa/middleware.ts
527
+ var useApitally = /* @__PURE__ */ __name((app, config) => {
528
+ const client = new ApitallyClient(config);
529
+ const middleware = getMiddleware(client);
530
+ app.use(middleware);
531
+ setTimeout(() => {
532
+ client.setAppInfo(getAppInfo(app, config.appVersion));
533
+ }, 1e3);
534
+ }, "useApitally");
535
+ var getMiddleware = /* @__PURE__ */ __name((client) => {
536
+ return async (ctx, next) => {
537
+ let path;
538
+ let statusCode;
539
+ const startTime = performance.now();
540
+ try {
541
+ await next();
542
+ } catch (error) {
543
+ path = getPath(ctx);
544
+ statusCode = error.statusCode || error.status || 500;
545
+ if (path && statusCode === 500 && error instanceof Error) {
546
+ client.serverErrorCounter.addServerError({
547
+ consumer: getConsumer(ctx),
548
+ method: ctx.request.method,
549
+ path,
550
+ type: error.name,
551
+ msg: error.message,
552
+ traceback: error.stack || ""
553
+ });
554
+ }
555
+ throw error;
556
+ } finally {
557
+ if (!path) {
558
+ path = getPath(ctx);
559
+ }
560
+ if (path) {
561
+ try {
562
+ client.requestCounter.addRequest({
563
+ consumer: getConsumer(ctx),
564
+ method: ctx.request.method,
565
+ path,
566
+ statusCode: statusCode || ctx.response.status,
567
+ responseTime: performance.now() - startTime,
568
+ requestSize: ctx.request.length,
569
+ responseSize: ctx.response.length
570
+ });
571
+ } catch (error) {
572
+ client.logger.error("Error while logging request in Apitally middleware.", {
573
+ context: ctx,
574
+ error
575
+ });
576
+ }
577
+ }
578
+ }
579
+ };
580
+ }, "getMiddleware");
581
+ var getPath = /* @__PURE__ */ __name((ctx) => {
582
+ return ctx._matchedRoute || ctx.routePath;
583
+ }, "getPath");
584
+ var getConsumer = /* @__PURE__ */ __name((ctx) => {
585
+ if (ctx.state.apitallyConsumer) {
586
+ return String(ctx.state.apitallyConsumer);
587
+ } else if (ctx.state.consumerIdentifier) {
588
+ return String(ctx.state.consumerIdentifier);
589
+ }
590
+ return null;
591
+ }, "getConsumer");
592
+ var getAppInfo = /* @__PURE__ */ __name((app, appVersion) => {
593
+ const versions = [
594
+ [
595
+ "nodejs",
596
+ process.version.replace(/^v/, "")
597
+ ]
598
+ ];
599
+ const koaVersion = getPackageVersion("koa");
600
+ const apitallyVersion = getPackageVersion("../..");
601
+ if (koaVersion) {
602
+ versions.push([
603
+ "koa",
604
+ koaVersion
605
+ ]);
606
+ }
607
+ if (apitallyVersion) {
608
+ versions.push([
609
+ "apitally",
610
+ apitallyVersion
611
+ ]);
612
+ }
613
+ if (appVersion) {
614
+ versions.push([
615
+ "app",
616
+ appVersion
617
+ ]);
618
+ }
619
+ return {
620
+ paths: listEndpoints(app),
621
+ versions: Object.fromEntries(versions),
622
+ client: "js:koa"
623
+ };
624
+ }, "getAppInfo");
625
+ var isKoaRouterMiddleware = /* @__PURE__ */ __name((middleware) => {
626
+ return typeof middleware === "function" && middleware.router && Array.isArray(middleware.router.stack);
627
+ }, "isKoaRouterMiddleware");
628
+ var listEndpoints = /* @__PURE__ */ __name((app) => {
629
+ const endpoints = [];
630
+ app.middleware.forEach((middleware) => {
631
+ if (isKoaRouterMiddleware(middleware)) {
632
+ middleware.router.stack.forEach((layer) => {
633
+ if (layer.methods && layer.methods.length > 0) {
634
+ layer.methods.forEach((method) => {
635
+ if (![
636
+ "HEAD",
637
+ "OPTIONS"
638
+ ].includes(method.toUpperCase())) {
639
+ endpoints.push({
640
+ method: method.toUpperCase(),
641
+ path: layer.path
642
+ });
643
+ }
644
+ });
645
+ }
646
+ });
647
+ }
648
+ });
649
+ return endpoints;
650
+ }, "listEndpoints");
651
+ // Annotate the CommonJS export names for ESM import in node:
652
+ 0 && (module.exports = {
653
+ useApitally
654
+ });
655
+ //# sourceMappingURL=middleware.cjs.map