apitally 0.21.3 → 0.21.4

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 (179) hide show
  1. package/dist/adonisjs/configure.cjs +6 -21
  2. package/dist/adonisjs/configure.cjs.map +1 -1
  3. package/dist/adonisjs/configure.js +3 -18
  4. package/dist/adonisjs/configure.js.map +1 -1
  5. package/dist/adonisjs/index.cjs +2 -70
  6. package/dist/adonisjs/index.cjs.map +1 -1
  7. package/dist/adonisjs/index.js +1 -66
  8. package/dist/adonisjs/index.js.map +1 -1
  9. package/dist/adonisjs/middleware.cjs +11 -116
  10. package/dist/adonisjs/middleware.cjs.map +1 -1
  11. package/dist/adonisjs/middleware.js +6 -101
  12. package/dist/adonisjs/middleware.js.map +1 -1
  13. package/dist/adonisjs/provider.cjs +14 -5668
  14. package/dist/adonisjs/provider.cjs.map +1 -1
  15. package/dist/adonisjs/provider.js +6 -5676
  16. package/dist/adonisjs/provider.js.map +1 -1
  17. package/dist/common/client.cjs +26 -792
  18. package/dist/common/client.cjs.map +1 -1
  19. package/dist/common/client.js +19 -785
  20. package/dist/common/client.js.map +1 -1
  21. package/dist/common/consumerRegistry.cjs +3 -5
  22. package/dist/common/consumerRegistry.cjs.map +1 -1
  23. package/dist/common/consumerRegistry.js +3 -5
  24. package/dist/common/consumerRegistry.js.map +1 -1
  25. package/dist/common/headers.cjs +0 -2
  26. package/dist/common/headers.cjs.map +1 -1
  27. package/dist/common/headers.js +0 -2
  28. package/dist/common/headers.js.map +1 -1
  29. package/dist/common/logging.cjs +0 -2
  30. package/dist/common/logging.cjs.map +1 -1
  31. package/dist/common/logging.js +0 -2
  32. package/dist/common/logging.js.map +1 -1
  33. package/dist/common/packageVersions.cjs +2 -4
  34. package/dist/common/packageVersions.cjs.map +1 -1
  35. package/dist/common/packageVersions.js +2 -10
  36. package/dist/common/packageVersions.js.map +1 -1
  37. package/dist/common/paramValidation.cjs +0 -2
  38. package/dist/common/paramValidation.cjs.map +1 -1
  39. package/dist/common/paramValidation.js +0 -2
  40. package/dist/common/paramValidation.js.map +1 -1
  41. package/dist/common/requestCounter.cjs +2 -4
  42. package/dist/common/requestCounter.cjs.map +1 -1
  43. package/dist/common/requestCounter.js +2 -4
  44. package/dist/common/requestCounter.js.map +1 -1
  45. package/dist/common/requestLogger.cjs +39 -162
  46. package/dist/common/requestLogger.cjs.map +1 -1
  47. package/dist/common/requestLogger.js +33 -156
  48. package/dist/common/requestLogger.js.map +1 -1
  49. package/dist/common/response.cjs +0 -2
  50. package/dist/common/response.cjs.map +1 -1
  51. package/dist/common/response.js +0 -2
  52. package/dist/common/response.js.map +1 -1
  53. package/dist/common/sentry.cjs +1 -3
  54. package/dist/common/sentry.cjs.map +1 -1
  55. package/dist/common/sentry.js +1 -3
  56. package/dist/common/sentry.js.map +1 -1
  57. package/dist/common/serverErrorCounter.cjs +7 -36
  58. package/dist/common/serverErrorCounter.cjs.map +1 -1
  59. package/dist/common/serverErrorCounter.js +6 -25
  60. package/dist/common/serverErrorCounter.js.map +1 -1
  61. package/dist/common/tempGzipFile.cjs +9 -11
  62. package/dist/common/tempGzipFile.cjs.map +1 -1
  63. package/dist/common/tempGzipFile.js +9 -11
  64. package/dist/common/tempGzipFile.js.map +1 -1
  65. package/dist/common/types.cjs +0 -2
  66. package/dist/common/types.cjs.map +1 -1
  67. package/dist/common/validationErrorCounter.cjs +3 -5
  68. package/dist/common/validationErrorCounter.cjs.map +1 -1
  69. package/dist/common/validationErrorCounter.js +3 -5
  70. package/dist/common/validationErrorCounter.js.map +1 -1
  71. package/dist/elysia/index.cjs +2 -1573
  72. package/dist/elysia/index.cjs.map +1 -1
  73. package/dist/elysia/index.js +2 -1577
  74. package/dist/elysia/index.js.map +1 -1
  75. package/dist/elysia/plugin.cjs +26 -1432
  76. package/dist/elysia/plugin.cjs.map +1 -1
  77. package/dist/elysia/plugin.js +15 -1416
  78. package/dist/elysia/plugin.js.map +1 -1
  79. package/dist/elysia/utils.cjs +3 -24
  80. package/dist/elysia/utils.cjs.map +1 -1
  81. package/dist/elysia/utils.js +1 -25
  82. package/dist/elysia/utils.js.map +1 -1
  83. package/dist/express/index.cjs +3 -6354
  84. package/dist/express/index.cjs.map +1 -1
  85. package/dist/express/index.js +1 -6367
  86. package/dist/express/index.js.map +1 -1
  87. package/dist/express/middleware.cjs +38 -6070
  88. package/dist/express/middleware.cjs.map +1 -1
  89. package/dist/express/middleware.js +13 -6061
  90. package/dist/express/middleware.js.map +1 -1
  91. package/dist/express/utils.cjs +17 -19
  92. package/dist/express/utils.cjs.map +1 -1
  93. package/dist/express/utils.js +17 -19
  94. package/dist/express/utils.js.map +1 -1
  95. package/dist/fastify/index.cjs +3 -6124
  96. package/dist/fastify/index.cjs.map +1 -1
  97. package/dist/fastify/index.js +2 -6148
  98. package/dist/fastify/index.js.map +1 -1
  99. package/dist/fastify/plugin.cjs +35 -5889
  100. package/dist/fastify/plugin.cjs.map +1 -1
  101. package/dist/fastify/plugin.js +13 -5893
  102. package/dist/fastify/plugin.js.map +1 -1
  103. package/dist/h3/index.cjs +3 -1545
  104. package/dist/h3/index.cjs.map +1 -1
  105. package/dist/h3/index.js +1 -1537
  106. package/dist/h3/index.js.map +1 -1
  107. package/dist/h3/plugin.cjs +27 -1423
  108. package/dist/h3/plugin.cjs.map +1 -1
  109. package/dist/h3/plugin.js +15 -1406
  110. package/dist/h3/plugin.js.map +1 -1
  111. package/dist/h3/utils.cjs +3 -24
  112. package/dist/h3/utils.cjs.map +1 -1
  113. package/dist/h3/utils.js +1 -25
  114. package/dist/h3/utils.js.map +1 -1
  115. package/dist/hapi/index.cjs +3 -5988
  116. package/dist/hapi/index.cjs.map +1 -1
  117. package/dist/hapi/index.js +2 -6012
  118. package/dist/hapi/index.js.map +1 -1
  119. package/dist/hapi/plugin.cjs +27 -5847
  120. package/dist/hapi/plugin.cjs.map +1 -1
  121. package/dist/hapi/plugin.js +15 -5851
  122. package/dist/hapi/plugin.js.map +1 -1
  123. package/dist/hapi/utils.cjs +3 -24
  124. package/dist/hapi/utils.cjs.map +1 -1
  125. package/dist/hapi/utils.js +1 -25
  126. package/dist/hapi/utils.js.map +1 -1
  127. package/dist/hono/index.cjs +3 -1571
  128. package/dist/hono/index.cjs.map +1 -1
  129. package/dist/hono/index.js +1 -1563
  130. package/dist/hono/index.js.map +1 -1
  131. package/dist/hono/middleware.cjs +21 -1460
  132. package/dist/hono/middleware.cjs.map +1 -1
  133. package/dist/hono/middleware.js +9 -1443
  134. package/dist/hono/middleware.js.map +1 -1
  135. package/dist/hono/utils.cjs +3 -24
  136. package/dist/hono/utils.cjs.map +1 -1
  137. package/dist/hono/utils.js +1 -27
  138. package/dist/hono/utils.js.map +1 -1
  139. package/dist/koa/index.cjs +3 -1484
  140. package/dist/koa/index.cjs.map +1 -1
  141. package/dist/koa/index.js +1 -1476
  142. package/dist/koa/index.js.map +1 -1
  143. package/dist/koa/middleware.cjs +19 -1313
  144. package/dist/koa/middleware.cjs.map +1 -1
  145. package/dist/koa/middleware.js +8 -1297
  146. package/dist/koa/middleware.js.map +1 -1
  147. package/dist/loggers/console.cjs +4 -6
  148. package/dist/loggers/console.cjs.map +1 -1
  149. package/dist/loggers/console.js +4 -6
  150. package/dist/loggers/console.js.map +1 -1
  151. package/dist/loggers/hapi.cjs +3 -5
  152. package/dist/loggers/hapi.cjs.map +1 -1
  153. package/dist/loggers/hapi.js +3 -5
  154. package/dist/loggers/hapi.js.map +1 -1
  155. package/dist/loggers/index.cjs +10 -4732
  156. package/dist/loggers/index.cjs.map +1 -1
  157. package/dist/loggers/index.js +5 -4743
  158. package/dist/loggers/index.js.map +1 -1
  159. package/dist/loggers/nestjs.cjs +5 -39
  160. package/dist/loggers/nestjs.cjs.map +1 -1
  161. package/dist/loggers/nestjs.js +4 -36
  162. package/dist/loggers/nestjs.js.map +1 -1
  163. package/dist/loggers/pino.cjs +29 -4448
  164. package/dist/loggers/pino.cjs.map +1 -1
  165. package/dist/loggers/pino.js +7 -4451
  166. package/dist/loggers/pino.js.map +1 -1
  167. package/dist/loggers/utils.cjs +1 -3
  168. package/dist/loggers/utils.cjs.map +1 -1
  169. package/dist/loggers/utils.js +1 -3
  170. package/dist/loggers/utils.js.map +1 -1
  171. package/dist/loggers/winston.cjs +6 -44
  172. package/dist/loggers/winston.cjs.map +1 -1
  173. package/dist/loggers/winston.js +4 -40
  174. package/dist/loggers/winston.js.map +1 -1
  175. package/dist/nestjs/index.cjs +17 -17786
  176. package/dist/nestjs/index.cjs.map +1 -1
  177. package/dist/nestjs/index.js +20 -17814
  178. package/dist/nestjs/index.js.map +1 -1
  179. package/package.json +1 -1
@@ -1,11 +1,8 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  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
6
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
7
  var __export = (target, all) => {
11
8
  for (var name in all)
@@ -19,1464 +16,28 @@ var __copyProps = (to, from, except, desc) => {
19
16
  }
20
17
  return to;
21
18
  };
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
19
  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/hono/middleware.ts
34
20
  var middleware_exports = {};
35
21
  __export(middleware_exports, {
36
22
  setConsumer: () => setConsumer,
37
23
  useApitally: () => useApitally
38
24
  });
39
25
  module.exports = __toCommonJS(middleware_exports);
40
- var import_node_async_hooks = require("async_hooks");
41
- var import_node_perf_hooks = require("perf_hooks");
42
-
43
- // src/common/client.ts
44
- var import_fetch_retry = __toESM(require("fetch-retry"), 1);
45
- var import_node_crypto5 = require("crypto");
46
-
47
- // src/common/consumerRegistry.ts
48
- var consumerFromStringOrObject = /* @__PURE__ */ __name((consumer) => {
49
- var _a2, _b;
50
- if (typeof consumer === "string") {
51
- consumer = String(consumer).trim().substring(0, 128);
52
- return consumer ? {
53
- identifier: consumer
54
- } : null;
55
- } else {
56
- consumer.identifier = String(consumer.identifier).trim().substring(0, 128);
57
- consumer.name = (_a2 = consumer.name) == null ? void 0 : _a2.trim().substring(0, 64);
58
- consumer.group = (_b = consumer.group) == null ? void 0 : _b.trim().substring(0, 64);
59
- return consumer.identifier ? consumer : null;
60
- }
61
- }, "consumerFromStringOrObject");
62
- var _ConsumerRegistry = class _ConsumerRegistry {
63
- consumers;
64
- updated;
65
- constructor() {
66
- this.consumers = /* @__PURE__ */ new Map();
67
- this.updated = /* @__PURE__ */ new Set();
68
- }
69
- addOrUpdateConsumer(consumer) {
70
- if (!consumer || !consumer.name && !consumer.group) {
71
- return;
72
- }
73
- const existing = this.consumers.get(consumer.identifier);
74
- if (!existing) {
75
- this.consumers.set(consumer.identifier, consumer);
76
- this.updated.add(consumer.identifier);
77
- } else {
78
- if (consumer.name && consumer.name !== existing.name) {
79
- existing.name = consumer.name;
80
- this.updated.add(consumer.identifier);
81
- }
82
- if (consumer.group && consumer.group !== existing.group) {
83
- existing.group = consumer.group;
84
- this.updated.add(consumer.identifier);
85
- }
86
- }
87
- }
88
- getAndResetUpdatedConsumers() {
89
- const data = [];
90
- this.updated.forEach((identifier) => {
91
- const consumer = this.consumers.get(identifier);
92
- if (consumer) {
93
- data.push(consumer);
94
- }
95
- });
96
- this.updated.clear();
97
- return data;
98
- }
99
- };
100
- __name(_ConsumerRegistry, "ConsumerRegistry");
101
- var ConsumerRegistry = _ConsumerRegistry;
102
-
103
- // src/common/logging.ts
104
- var import_winston = require("winston");
105
- function getLogger() {
106
- return (0, import_winston.createLogger)({
107
- level: process.env.APITALLY_DEBUG ? "debug" : "warn",
108
- format: import_winston.format.combine(import_winston.format.colorize(), import_winston.format.timestamp(), import_winston.format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`)),
109
- transports: [
110
- new import_winston.transports.Console()
111
- ]
112
- });
113
- }
114
- __name(getLogger, "getLogger");
115
-
116
- // src/common/paramValidation.ts
117
- function isValidClientId(clientId) {
118
- 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;
119
- return regexExp.test(clientId);
120
- }
121
- __name(isValidClientId, "isValidClientId");
122
- function isValidEnv(env) {
123
- const regexExp = /^[\w-]{1,32}$/;
124
- return regexExp.test(env);
125
- }
126
- __name(isValidEnv, "isValidEnv");
127
-
128
- // src/common/requestCounter.ts
129
- var _RequestCounter = class _RequestCounter {
130
- requestCounts;
131
- requestSizeSums;
132
- responseSizeSums;
133
- responseTimes;
134
- requestSizes;
135
- responseSizes;
136
- constructor() {
137
- this.requestCounts = /* @__PURE__ */ new Map();
138
- this.requestSizeSums = /* @__PURE__ */ new Map();
139
- this.responseSizeSums = /* @__PURE__ */ new Map();
140
- this.responseTimes = /* @__PURE__ */ new Map();
141
- this.requestSizes = /* @__PURE__ */ new Map();
142
- this.responseSizes = /* @__PURE__ */ new Map();
143
- }
144
- getKey(requestInfo) {
145
- return [
146
- requestInfo.consumer || "",
147
- requestInfo.method.toUpperCase(),
148
- requestInfo.path,
149
- requestInfo.statusCode
150
- ].join("|");
151
- }
152
- addRequest(requestInfo) {
153
- const key = this.getKey(requestInfo);
154
- this.requestCounts.set(key, (this.requestCounts.get(key) || 0) + 1);
155
- if (!this.responseTimes.has(key)) {
156
- this.responseTimes.set(key, /* @__PURE__ */ new Map());
157
- }
158
- const responseTimeMap = this.responseTimes.get(key);
159
- const responseTimeMsBin = Math.floor(requestInfo.responseTime / 10) * 10;
160
- responseTimeMap.set(responseTimeMsBin, (responseTimeMap.get(responseTimeMsBin) || 0) + 1);
161
- if (requestInfo.requestSize !== void 0) {
162
- requestInfo.requestSize = Number(requestInfo.requestSize);
163
- this.requestSizeSums.set(key, (this.requestSizeSums.get(key) || 0) + requestInfo.requestSize);
164
- if (!this.requestSizes.has(key)) {
165
- this.requestSizes.set(key, /* @__PURE__ */ new Map());
166
- }
167
- const requestSizeMap = this.requestSizes.get(key);
168
- const requestSizeKbBin = Math.floor(requestInfo.requestSize / 1e3);
169
- requestSizeMap.set(requestSizeKbBin, (requestSizeMap.get(requestSizeKbBin) || 0) + 1);
170
- }
171
- if (requestInfo.responseSize !== void 0) {
172
- requestInfo.responseSize = Number(requestInfo.responseSize);
173
- this.responseSizeSums.set(key, (this.responseSizeSums.get(key) || 0) + requestInfo.responseSize);
174
- if (!this.responseSizes.has(key)) {
175
- this.responseSizes.set(key, /* @__PURE__ */ new Map());
176
- }
177
- const responseSizeMap = this.responseSizes.get(key);
178
- const responseSizeKbBin = Math.floor(requestInfo.responseSize / 1e3);
179
- responseSizeMap.set(responseSizeKbBin, (responseSizeMap.get(responseSizeKbBin) || 0) + 1);
180
- }
181
- }
182
- getAndResetRequests() {
183
- const data = [];
184
- this.requestCounts.forEach((count, key) => {
185
- const [consumer, method, path, statusCodeStr] = key.split("|");
186
- const responseTimes = this.responseTimes.get(key) || /* @__PURE__ */ new Map();
187
- const requestSizes = this.requestSizes.get(key) || /* @__PURE__ */ new Map();
188
- const responseSizes = this.responseSizes.get(key) || /* @__PURE__ */ new Map();
189
- data.push({
190
- consumer: consumer || null,
191
- method,
192
- path,
193
- status_code: parseInt(statusCodeStr),
194
- request_count: count,
195
- request_size_sum: this.requestSizeSums.get(key) || 0,
196
- response_size_sum: this.responseSizeSums.get(key) || 0,
197
- response_times: Object.fromEntries(responseTimes),
198
- request_sizes: Object.fromEntries(requestSizes),
199
- response_sizes: Object.fromEntries(responseSizes)
200
- });
201
- });
202
- this.requestCounts.clear();
203
- this.requestSizeSums.clear();
204
- this.responseSizeSums.clear();
205
- this.responseTimes.clear();
206
- this.requestSizes.clear();
207
- this.responseSizes.clear();
208
- return data;
209
- }
210
- };
211
- __name(_RequestCounter, "RequestCounter");
212
- var RequestCounter = _RequestCounter;
213
-
214
- // src/common/requestLogger.ts
215
- var import_async_lock = __toESM(require("async-lock"), 1);
216
- var import_node_buffer2 = require("buffer");
217
- var import_node_crypto3 = require("crypto");
218
- var import_node_fs2 = require("fs");
219
- var import_node_os2 = require("os");
220
- var import_node_path2 = require("path");
221
-
222
- // src/common/sentry.ts
223
- var sentry;
224
- (async () => {
225
- try {
226
- sentry = await import("@sentry/node");
227
- } catch (e) {
228
- }
229
- })();
230
- function getSentryEventId() {
231
- if (sentry && sentry.lastEventId) {
232
- return sentry.lastEventId();
233
- }
234
- return void 0;
235
- }
236
- __name(getSentryEventId, "getSentryEventId");
237
-
238
- // src/common/serverErrorCounter.ts
239
- var import_node_crypto = require("crypto");
240
- var MAX_MSG_LENGTH = 2048;
241
- var MAX_STACKTRACE_LENGTH = 65536;
242
- var _ServerErrorCounter = class _ServerErrorCounter {
243
- errorCounts;
244
- errorDetails;
245
- sentryEventIds;
246
- constructor() {
247
- this.errorCounts = /* @__PURE__ */ new Map();
248
- this.errorDetails = /* @__PURE__ */ new Map();
249
- this.sentryEventIds = /* @__PURE__ */ new Map();
250
- }
251
- addServerError(serverError) {
252
- const key = this.getKey(serverError);
253
- if (!this.errorDetails.has(key)) {
254
- this.errorDetails.set(key, serverError);
255
- }
256
- this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
257
- const sentryEventId = getSentryEventId();
258
- if (sentryEventId) {
259
- this.sentryEventIds.set(key, sentryEventId);
260
- }
261
- }
262
- getAndResetServerErrors() {
263
- const data = [];
264
- this.errorCounts.forEach((count, key) => {
265
- const serverError = this.errorDetails.get(key);
266
- if (serverError) {
267
- data.push({
268
- consumer: serverError.consumer || null,
269
- method: serverError.method,
270
- path: serverError.path,
271
- type: serverError.type,
272
- msg: truncateExceptionMessage(serverError.msg),
273
- traceback: truncateExceptionStackTrace(serverError.traceback),
274
- sentry_event_id: this.sentryEventIds.get(key) || null,
275
- error_count: count
276
- });
277
- }
278
- });
279
- this.errorCounts.clear();
280
- this.errorDetails.clear();
281
- this.sentryEventIds.clear();
282
- return data;
283
- }
284
- getKey(serverError) {
285
- const hashInput = [
286
- serverError.consumer || "",
287
- serverError.method.toUpperCase(),
288
- serverError.path,
289
- serverError.type,
290
- serverError.msg.trim(),
291
- serverError.traceback.trim()
292
- ].join("|");
293
- return (0, import_node_crypto.createHash)("md5").update(hashInput).digest("hex");
294
- }
295
- };
296
- __name(_ServerErrorCounter, "ServerErrorCounter");
297
- var ServerErrorCounter = _ServerErrorCounter;
298
- function truncateExceptionMessage(msg) {
299
- if (msg.length <= MAX_MSG_LENGTH) {
300
- return msg;
301
- }
302
- const suffix = "... (truncated)";
303
- const cutoff = MAX_MSG_LENGTH - suffix.length;
304
- return msg.substring(0, cutoff) + suffix;
305
- }
306
- __name(truncateExceptionMessage, "truncateExceptionMessage");
307
- function truncateExceptionStackTrace(stack) {
308
- const suffix = "... (truncated) ...";
309
- const cutoff = MAX_STACKTRACE_LENGTH - suffix.length;
310
- const lines = stack.trim().split("\n");
311
- const truncatedLines = [];
312
- let length = 0;
313
- for (const line of lines) {
314
- if (length + line.length + 1 > cutoff) {
315
- truncatedLines.push(suffix);
316
- break;
317
- }
318
- truncatedLines.push(line);
319
- length += line.length + 1;
320
- }
321
- return truncatedLines.join("\n");
322
- }
323
- __name(truncateExceptionStackTrace, "truncateExceptionStackTrace");
324
-
325
- // src/common/tempGzipFile.ts
326
- var import_node_buffer = require("buffer");
327
- var import_node_crypto2 = require("crypto");
328
- var import_node_fs = require("fs");
329
- var import_promises = require("fs/promises");
330
- var import_node_os = require("os");
331
- var import_node_path = require("path");
332
- var import_node_zlib = require("zlib");
333
- var _TempGzipFile = class _TempGzipFile {
334
- uuid;
335
- filePath;
336
- gzip;
337
- writeStream;
338
- readyPromise;
339
- closedPromise;
340
- constructor() {
341
- this.uuid = (0, import_node_crypto2.randomUUID)();
342
- this.filePath = (0, import_node_path.join)((0, import_node_os.tmpdir)(), `apitally-${this.uuid}.gz`);
343
- this.writeStream = (0, import_node_fs.createWriteStream)(this.filePath);
344
- this.readyPromise = new Promise((resolve, reject) => {
345
- this.writeStream.once("ready", resolve);
346
- this.writeStream.once("error", reject);
347
- });
348
- this.closedPromise = new Promise((resolve, reject) => {
349
- this.writeStream.once("close", resolve);
350
- this.writeStream.once("error", reject);
351
- });
352
- this.gzip = (0, import_node_zlib.createGzip)();
353
- this.gzip.pipe(this.writeStream);
354
- }
355
- get size() {
356
- return this.writeStream.bytesWritten;
357
- }
358
- async writeLine(data) {
359
- await this.readyPromise;
360
- return new Promise((resolve, reject) => {
361
- this.gzip.write(import_node_buffer.Buffer.concat([
362
- data,
363
- import_node_buffer.Buffer.from("\n")
364
- ]), (error) => {
365
- if (error) {
366
- reject(error);
367
- } else {
368
- resolve();
369
- }
370
- });
371
- });
372
- }
373
- async getContent() {
374
- return new Promise((resolve, reject) => {
375
- (0, import_node_fs.readFile)(this.filePath, (error, data) => {
376
- if (error) {
377
- reject(error);
378
- } else {
379
- resolve(data);
380
- }
381
- });
382
- });
383
- }
384
- async close() {
385
- await new Promise((resolve) => {
386
- this.gzip.end(() => {
387
- resolve();
388
- });
389
- });
390
- await this.closedPromise;
391
- }
392
- async delete() {
393
- await this.close();
394
- await (0, import_promises.unlink)(this.filePath);
395
- }
396
- };
397
- __name(_TempGzipFile, "TempGzipFile");
398
- var TempGzipFile = _TempGzipFile;
399
-
400
- // src/common/requestLogger.ts
401
- var MAX_BODY_SIZE = 5e4;
402
- var MAX_FILE_SIZE = 1e6;
403
- var MAX_FILES = 50;
404
- var MAX_PENDING_WRITES = 100;
405
- var MAX_LOG_MSG_LENGTH = 2048;
406
- var BODY_TOO_LARGE = import_node_buffer2.Buffer.from("<body too large>");
407
- var BODY_MASKED = import_node_buffer2.Buffer.from("<masked>");
408
- var MASKED = "******";
409
- var ALLOWED_CONTENT_TYPES = [
410
- "application/json",
411
- "application/problem+json",
412
- "application/vnd.api+json",
413
- "text/plain",
414
- "text/html"
415
- ];
416
- var EXCLUDE_PATH_PATTERNS = [
417
- /\/_?healthz?$/i,
418
- /\/_?health[_-]?checks?$/i,
419
- /\/_?heart[_-]?beats?$/i,
420
- /\/ping$/i,
421
- /\/ready$/i,
422
- /\/live$/i
423
- ];
424
- var EXCLUDE_USER_AGENT_PATTERNS = [
425
- /health[-_ ]?check/i,
426
- /microsoft-azure-application-lb/i,
427
- /googlehc/i,
428
- /kube-probe/i
429
- ];
430
- var MASK_QUERY_PARAM_PATTERNS = [
431
- /auth/i,
432
- /api-?key/i,
433
- /secret/i,
434
- /token/i,
435
- /password/i,
436
- /pwd/i
437
- ];
438
- var MASK_HEADER_PATTERNS = [
439
- /auth/i,
440
- /api-?key/i,
441
- /secret/i,
442
- /token/i,
443
- /cookie/i
444
- ];
445
- var MASK_BODY_FIELD_PATTERNS = [
446
- /password/i,
447
- /pwd/i,
448
- /token/i,
449
- /secret/i,
450
- /auth/i,
451
- /card[-_ ]?number/i,
452
- /ccv/i,
453
- /ssn/i
454
- ];
455
- var DEFAULT_CONFIG = {
456
- enabled: false,
457
- logQueryParams: true,
458
- logRequestHeaders: false,
459
- logRequestBody: false,
460
- logResponseHeaders: true,
461
- logResponseBody: false,
462
- logException: true,
463
- captureLogs: false,
464
- maskQueryParams: [],
465
- maskHeaders: [],
466
- maskBodyFields: [],
467
- excludePaths: []
468
- };
469
- var _RequestLogger = class _RequestLogger {
470
- config;
471
- enabled;
472
- suspendUntil = null;
473
- pendingWrites = [];
474
- currentFile = null;
475
- files = [];
476
- maintainIntervalId;
477
- lock = new import_async_lock.default();
478
- constructor(config) {
479
- this.config = {
480
- ...DEFAULT_CONFIG,
481
- ...config
482
- };
483
- this.enabled = this.config.enabled && checkWritableFs();
484
- if (this.enabled) {
485
- this.maintainIntervalId = setInterval(() => {
486
- this.maintain();
487
- }, 1e3);
488
- }
489
- }
490
- get maxBodySize() {
491
- return MAX_BODY_SIZE;
492
- }
493
- shouldExcludePath(urlPath) {
494
- const patterns = [
495
- ...this.config.excludePaths,
496
- ...EXCLUDE_PATH_PATTERNS
497
- ];
498
- return matchPatterns(urlPath, patterns);
499
- }
500
- shouldExcludeUserAgent(userAgent) {
501
- return userAgent ? matchPatterns(userAgent, EXCLUDE_USER_AGENT_PATTERNS) : false;
502
- }
503
- shouldMaskQueryParam(name) {
504
- const patterns = [
505
- ...this.config.maskQueryParams,
506
- ...MASK_QUERY_PARAM_PATTERNS
507
- ];
508
- return matchPatterns(name, patterns);
509
- }
510
- shouldMaskHeader(name) {
511
- const patterns = [
512
- ...this.config.maskHeaders,
513
- ...MASK_HEADER_PATTERNS
514
- ];
515
- return matchPatterns(name, patterns);
516
- }
517
- shouldMaskBodyField(name) {
518
- const patterns = [
519
- ...this.config.maskBodyFields,
520
- ...MASK_BODY_FIELD_PATTERNS
521
- ];
522
- return matchPatterns(name, patterns);
523
- }
524
- hasSupportedContentType(headers) {
525
- var _a2;
526
- const contentType = (_a2 = headers.find(([k]) => k.toLowerCase() === "content-type")) == null ? void 0 : _a2[1];
527
- return this.isSupportedContentType(contentType);
528
- }
529
- hasJsonContentType(headers) {
530
- var _a2;
531
- const contentType = (_a2 = headers.find(([k]) => k.toLowerCase() === "content-type")) == null ? void 0 : _a2[1];
532
- return contentType ? /\bjson\b/i.test(contentType) : null;
533
- }
534
- isSupportedContentType(contentType) {
535
- return typeof contentType === "string" && ALLOWED_CONTENT_TYPES.some((t) => contentType.startsWith(t));
536
- }
537
- maskQueryParams(search) {
538
- const params = new URLSearchParams(search);
539
- for (const [key] of params) {
540
- if (this.shouldMaskQueryParam(key)) {
541
- params.set(key, MASKED);
542
- }
543
- }
544
- return params.toString();
545
- }
546
- maskHeaders(headers) {
547
- return headers.map(([k, v]) => [
548
- k,
549
- this.shouldMaskHeader(k) ? MASKED : v
550
- ]);
551
- }
552
- maskBody(data) {
553
- if (typeof data === "object" && data !== null && !Array.isArray(data)) {
554
- const result = {};
555
- for (const [key, value] of Object.entries(data)) {
556
- if (typeof value === "string" && this.shouldMaskBodyField(key)) {
557
- result[key] = MASKED;
558
- } else {
559
- result[key] = this.maskBody(value);
560
- }
561
- }
562
- return result;
563
- }
564
- if (Array.isArray(data)) {
565
- return data.map((item) => this.maskBody(item));
566
- }
567
- return data;
568
- }
569
- applyMasking(item) {
570
- if (this.config.maskRequestBodyCallback && item.request.body && item.request.body !== BODY_TOO_LARGE) {
571
- try {
572
- const maskedBody = this.config.maskRequestBodyCallback(item.request);
573
- item.request.body = maskedBody ?? BODY_MASKED;
574
- } catch {
575
- item.request.body = void 0;
576
- }
577
- }
578
- if (this.config.maskResponseBodyCallback && item.response.body && item.response.body !== BODY_TOO_LARGE) {
579
- try {
580
- const maskedBody = this.config.maskResponseBodyCallback(item.request, item.response);
581
- item.response.body = maskedBody ?? BODY_MASKED;
582
- } catch {
583
- item.response.body = void 0;
584
- }
585
- }
586
- if (item.request.body && item.request.body.length > MAX_BODY_SIZE) {
587
- item.request.body = BODY_TOO_LARGE;
588
- }
589
- if (item.response.body && item.response.body.length > MAX_BODY_SIZE) {
590
- item.response.body = BODY_TOO_LARGE;
591
- }
592
- for (const key of [
593
- "request",
594
- "response"
595
- ]) {
596
- const bodyData = item[key].body;
597
- if (!bodyData || bodyData === BODY_TOO_LARGE || bodyData === BODY_MASKED) {
598
- continue;
599
- }
600
- const headers = item[key].headers;
601
- const hasJsonContent = this.hasJsonContentType(headers);
602
- if (hasJsonContent === null || hasJsonContent) {
603
- try {
604
- const parsedBody = JSON.parse(bodyData.toString());
605
- const maskedBody = this.maskBody(parsedBody);
606
- item[key].body = import_node_buffer2.Buffer.from(JSON.stringify(maskedBody));
607
- } catch {
608
- }
609
- }
610
- }
611
- item.request.headers = this.config.logRequestHeaders ? this.maskHeaders(item.request.headers) : [];
612
- item.response.headers = this.config.logResponseHeaders ? this.maskHeaders(item.response.headers) : [];
613
- const url = new URL(item.request.url);
614
- url.search = this.config.logQueryParams ? this.maskQueryParams(url.search) : "";
615
- item.request.url = url.toString();
616
- return item;
617
- }
618
- logRequest(request, response, error, logs) {
619
- var _a2, _b, _c;
620
- if (!this.enabled || this.suspendUntil !== null) return;
621
- const url = new URL(request.url);
622
- const path = request.path ?? url.pathname;
623
- const userAgent = (_a2 = request.headers.find(([k]) => k.toLowerCase() === "user-agent")) == null ? void 0 : _a2[1];
624
- if (this.shouldExcludePath(path) || this.shouldExcludeUserAgent(userAgent) || (((_c = (_b = this.config).excludeCallback) == null ? void 0 : _c.call(_b, request, response)) ?? false)) {
625
- return;
626
- }
627
- if (!this.config.logRequestBody || !this.hasSupportedContentType(request.headers)) {
628
- request.body = void 0;
629
- }
630
- if (!this.config.logResponseBody || !this.hasSupportedContentType(response.headers)) {
631
- response.body = void 0;
632
- }
633
- if (request.size !== void 0 && request.size < 0) {
634
- request.size = void 0;
635
- }
636
- if (response.size !== void 0 && response.size < 0) {
637
- response.size = void 0;
638
- }
639
- const item = {
640
- uuid: (0, import_node_crypto3.randomUUID)(),
641
- request,
642
- response,
643
- exception: error && this.config.logException ? {
644
- type: error.name,
645
- message: truncateExceptionMessage(error.message),
646
- stacktrace: truncateExceptionStackTrace(error.stack || ""),
647
- sentryEventId: getSentryEventId()
648
- } : void 0
649
- };
650
- if (logs && logs.length > 0) {
651
- item.logs = logs.map((log) => ({
652
- timestamp: log.timestamp,
653
- logger: log.logger,
654
- level: log.level,
655
- message: truncateLogMessage(log.message)
656
- }));
657
- }
658
- this.pendingWrites.push(item);
659
- if (this.pendingWrites.length > MAX_PENDING_WRITES) {
660
- this.pendingWrites.shift();
661
- }
662
- }
663
- async writeToFile() {
664
- if (!this.enabled || this.pendingWrites.length === 0) {
665
- return;
666
- }
667
- return this.lock.acquire("file", async () => {
668
- if (!this.currentFile) {
669
- this.currentFile = new TempGzipFile();
670
- }
671
- while (this.pendingWrites.length > 0) {
672
- let item = this.pendingWrites.shift();
673
- if (item) {
674
- item = this.applyMasking(item);
675
- const finalItem = {
676
- uuid: item.uuid,
677
- request: skipEmptyValues(item.request),
678
- response: skipEmptyValues(item.response),
679
- exception: item.exception,
680
- logs: item.logs
681
- };
682
- [
683
- finalItem.request.body,
684
- finalItem.response.body
685
- ].forEach((body) => {
686
- if (body) {
687
- body.toJSON = function() {
688
- return this.toString("base64");
689
- };
690
- }
691
- });
692
- await this.currentFile.writeLine(import_node_buffer2.Buffer.from(JSON.stringify(finalItem)));
693
- }
694
- }
695
- });
696
- }
697
- getFile() {
698
- return this.files.shift();
699
- }
700
- retryFileLater(file) {
701
- this.files.unshift(file);
702
- }
703
- async rotateFile() {
704
- return this.lock.acquire("file", async () => {
705
- if (this.currentFile) {
706
- await this.currentFile.close();
707
- this.files.push(this.currentFile);
708
- this.currentFile = null;
709
- }
710
- });
711
- }
712
- async maintain() {
713
- await this.writeToFile();
714
- if (this.currentFile && this.currentFile.size > MAX_FILE_SIZE) {
715
- await this.rotateFile();
716
- }
717
- while (this.files.length > MAX_FILES) {
718
- const file = this.files.shift();
719
- file == null ? void 0 : file.delete();
720
- }
721
- if (this.suspendUntil !== null && this.suspendUntil < Date.now()) {
722
- this.suspendUntil = null;
723
- }
724
- }
725
- async clear() {
726
- this.pendingWrites = [];
727
- await this.rotateFile();
728
- this.files.forEach((file) => {
729
- file.delete();
730
- });
731
- this.files = [];
732
- }
733
- async close() {
734
- this.enabled = false;
735
- await this.clear();
736
- if (this.maintainIntervalId) {
737
- clearInterval(this.maintainIntervalId);
738
- }
739
- }
740
- };
741
- __name(_RequestLogger, "RequestLogger");
742
- var RequestLogger = _RequestLogger;
743
- function convertHeaders(headers) {
744
- if (!headers) {
745
- return [];
746
- }
747
- if (headers instanceof Headers) {
748
- return Array.from(headers.entries());
749
- }
750
- return Object.entries(headers).flatMap(([key, value]) => {
751
- if (value === void 0) {
752
- return [];
753
- }
754
- if (Array.isArray(value)) {
755
- return value.map((v) => [
756
- key,
757
- v
758
- ]);
759
- }
760
- return [
761
- [
762
- key,
763
- value.toString()
764
- ]
765
- ];
766
- });
767
- }
768
- __name(convertHeaders, "convertHeaders");
769
- function matchPatterns(value, patterns) {
770
- return patterns.some((pattern) => {
771
- return pattern.test(value);
772
- });
773
- }
774
- __name(matchPatterns, "matchPatterns");
775
- function skipEmptyValues(data) {
776
- return Object.fromEntries(Object.entries(data).filter(([_, v]) => {
777
- if (v == null || Number.isNaN(v)) return false;
778
- if (Array.isArray(v) || import_node_buffer2.Buffer.isBuffer(v) || typeof v === "string") {
779
- return v.length > 0;
780
- }
781
- return true;
782
- }));
783
- }
784
- __name(skipEmptyValues, "skipEmptyValues");
785
- function truncateLogMessage(msg) {
786
- if (msg.length > MAX_LOG_MSG_LENGTH) {
787
- const suffix = "... (truncated)";
788
- return msg.slice(0, MAX_LOG_MSG_LENGTH - suffix.length) + suffix;
789
- }
790
- return msg;
791
- }
792
- __name(truncateLogMessage, "truncateLogMessage");
793
- function checkWritableFs() {
794
- try {
795
- const testPath = (0, import_node_path2.join)((0, import_node_os2.tmpdir)(), `apitally-${(0, import_node_crypto3.randomUUID)()}`);
796
- (0, import_node_fs2.writeFileSync)(testPath, "test");
797
- (0, import_node_fs2.unlinkSync)(testPath);
798
- return true;
799
- } catch (error) {
800
- return false;
801
- }
802
- }
803
- __name(checkWritableFs, "checkWritableFs");
804
-
805
- // src/common/validationErrorCounter.ts
806
- var import_node_crypto4 = require("crypto");
807
- var _ValidationErrorCounter = class _ValidationErrorCounter {
808
- errorCounts;
809
- errorDetails;
810
- constructor() {
811
- this.errorCounts = /* @__PURE__ */ new Map();
812
- this.errorDetails = /* @__PURE__ */ new Map();
813
- }
814
- addValidationError(validationError) {
815
- const key = this.getKey(validationError);
816
- if (!this.errorDetails.has(key)) {
817
- this.errorDetails.set(key, validationError);
818
- }
819
- this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
820
- }
821
- getAndResetValidationErrors() {
822
- const data = [];
823
- this.errorCounts.forEach((count, key) => {
824
- const validationError = this.errorDetails.get(key);
825
- if (validationError) {
826
- data.push({
827
- consumer: validationError.consumer || null,
828
- method: validationError.method,
829
- path: validationError.path,
830
- loc: validationError.loc.split(".").filter(Boolean),
831
- msg: validationError.msg,
832
- type: validationError.type,
833
- error_count: count
834
- });
835
- }
836
- });
837
- this.errorCounts.clear();
838
- this.errorDetails.clear();
839
- return data;
840
- }
841
- getKey(validationError) {
842
- const hashInput = [
843
- validationError.consumer || "",
844
- validationError.method.toUpperCase(),
845
- validationError.path,
846
- validationError.loc.split(".").filter(Boolean),
847
- validationError.msg.trim(),
848
- validationError.type
849
- ].join("|");
850
- return (0, import_node_crypto4.createHash)("md5").update(hashInput).digest("hex");
851
- }
852
- };
853
- __name(_ValidationErrorCounter, "ValidationErrorCounter");
854
- var ValidationErrorCounter = _ValidationErrorCounter;
855
-
856
- // src/common/client.ts
857
- var SYNC_INTERVAL = 6e4;
858
- var INITIAL_SYNC_INTERVAL = 1e4;
859
- var INITIAL_SYNC_INTERVAL_DURATION = 36e5;
860
- var MAX_QUEUE_TIME = 36e5;
861
- var _a;
862
- var HTTPError = (_a = class extends Error {
863
- response;
864
- constructor(response) {
865
- const reason = response.status ? `status code ${response.status}` : "an unknown error";
866
- super(`Request failed with ${reason}`);
867
- this.response = response;
868
- }
869
- }, __name(_a, "HTTPError"), _a);
870
- var _ApitallyClient = class _ApitallyClient {
871
- clientId;
872
- env;
873
- instanceUuid;
874
- syncDataQueue;
875
- syncIntervalId;
876
- startupData;
877
- startupDataSent = false;
878
- enabled = true;
879
- requestCounter;
880
- requestLogger;
881
- validationErrorCounter;
882
- serverErrorCounter;
883
- consumerRegistry;
884
- logger;
885
- constructor({ clientId, env = "dev", requestLogging, requestLoggingConfig, logger }) {
886
- if (_ApitallyClient.instance) {
887
- throw new Error("Apitally client is already initialized");
888
- }
889
- this.logger = logger ?? getLogger();
890
- if (!isValidClientId(clientId)) {
891
- this.logger.error(`Invalid Apitally client ID '${clientId}' (expecting hexadecimal UUID format)`);
892
- this.enabled = false;
893
- }
894
- if (!isValidEnv(env)) {
895
- this.logger.error(`Invalid Apitally env '${env}' (expecting 1-32 alphanumeric characters and hyphens only)`);
896
- this.enabled = false;
897
- }
898
- if (requestLoggingConfig && !requestLogging) {
899
- console.warn("requestLoggingConfig is deprecated, use requestLogging instead.");
900
- }
901
- _ApitallyClient.instance = this;
902
- this.clientId = clientId;
903
- this.env = env;
904
- this.instanceUuid = (0, import_node_crypto5.randomUUID)();
905
- this.syncDataQueue = [];
906
- this.requestCounter = new RequestCounter();
907
- this.requestLogger = new RequestLogger(requestLogging ?? requestLoggingConfig);
908
- this.validationErrorCounter = new ValidationErrorCounter();
909
- this.serverErrorCounter = new ServerErrorCounter();
910
- this.consumerRegistry = new ConsumerRegistry();
911
- this.handleShutdown = this.handleShutdown.bind(this);
912
- }
913
- static getInstance() {
914
- if (!_ApitallyClient.instance) {
915
- throw new Error("Apitally client is not initialized");
916
- }
917
- return _ApitallyClient.instance;
918
- }
919
- isEnabled() {
920
- return this.enabled;
921
- }
922
- static async shutdown() {
923
- if (_ApitallyClient.instance) {
924
- await _ApitallyClient.instance.handleShutdown();
925
- }
926
- }
927
- async handleShutdown() {
928
- this.enabled = false;
929
- this.stopSync();
930
- await this.sendSyncData();
931
- await this.sendLogData();
932
- await this.requestLogger.close();
933
- _ApitallyClient.instance = void 0;
934
- }
935
- getHubUrlPrefix() {
936
- const baseURL = process.env.APITALLY_HUB_BASE_URL || "https://hub.apitally.io";
937
- const version = "v2";
938
- return `${baseURL}/${version}/${this.clientId}/${this.env}/`;
939
- }
940
- async sendData(url, payload) {
941
- const fetchWithRetry = (0, import_fetch_retry.default)(fetch, {
942
- retries: 3,
943
- retryDelay: 1e3,
944
- retryOn: [
945
- 408,
946
- 429,
947
- 500,
948
- 502,
949
- 503,
950
- 504
951
- ]
952
- });
953
- const response = await fetchWithRetry(this.getHubUrlPrefix() + url, {
954
- method: "POST",
955
- body: JSON.stringify(payload),
956
- headers: {
957
- "Content-Type": "application/json"
958
- }
959
- });
960
- if (!response.ok) {
961
- throw new HTTPError(response);
962
- }
963
- }
964
- startSync() {
965
- if (!this.enabled) {
966
- return;
967
- }
968
- this.sync();
969
- this.syncIntervalId = setInterval(() => {
970
- this.sync();
971
- }, INITIAL_SYNC_INTERVAL);
972
- setTimeout(() => {
973
- if (this.syncIntervalId) {
974
- clearInterval(this.syncIntervalId);
975
- this.syncIntervalId = setInterval(() => {
976
- this.sync();
977
- }, SYNC_INTERVAL);
978
- }
979
- }, INITIAL_SYNC_INTERVAL_DURATION);
980
- }
981
- async sync() {
982
- try {
983
- const promises = [
984
- this.sendSyncData(),
985
- this.sendLogData()
986
- ];
987
- if (!this.startupDataSent) {
988
- promises.push(this.sendStartupData());
989
- }
990
- await Promise.all(promises);
991
- } catch (error) {
992
- this.logger.error("Error while syncing with Apitally Hub", {
993
- error
994
- });
995
- }
996
- }
997
- stopSync() {
998
- if (this.syncIntervalId) {
999
- clearInterval(this.syncIntervalId);
1000
- this.syncIntervalId = void 0;
1001
- }
1002
- }
1003
- setStartupData(data) {
1004
- this.startupData = data;
1005
- this.startupDataSent = false;
1006
- }
1007
- async sendStartupData() {
1008
- if (this.startupData) {
1009
- this.logger.debug("Sending startup data to Apitally Hub");
1010
- const payload = {
1011
- instance_uuid: this.instanceUuid,
1012
- message_uuid: (0, import_node_crypto5.randomUUID)(),
1013
- ...this.startupData
1014
- };
1015
- try {
1016
- await this.sendData("startup", payload);
1017
- this.startupDataSent = true;
1018
- } catch (error) {
1019
- const handled = this.handleHubError(error);
1020
- if (!handled) {
1021
- this.logger.error(error.message);
1022
- this.logger.debug("Error while sending startup data to Apitally Hub (will retry)", {
1023
- error
1024
- });
1025
- }
1026
- }
1027
- }
1028
- }
1029
- async sendSyncData() {
1030
- this.logger.debug("Synchronizing data with Apitally Hub");
1031
- const newPayload = {
1032
- timestamp: Date.now() / 1e3,
1033
- instance_uuid: this.instanceUuid,
1034
- message_uuid: (0, import_node_crypto5.randomUUID)(),
1035
- requests: this.requestCounter.getAndResetRequests(),
1036
- validation_errors: this.validationErrorCounter.getAndResetValidationErrors(),
1037
- server_errors: this.serverErrorCounter.getAndResetServerErrors(),
1038
- consumers: this.consumerRegistry.getAndResetUpdatedConsumers()
1039
- };
1040
- this.syncDataQueue.push(newPayload);
1041
- let i = 0;
1042
- while (this.syncDataQueue.length > 0) {
1043
- const payload = this.syncDataQueue.shift();
1044
- if (payload) {
1045
- try {
1046
- if (Date.now() - payload.timestamp * 1e3 <= MAX_QUEUE_TIME) {
1047
- if (i > 0) {
1048
- await this.randomDelay();
1049
- }
1050
- await this.sendData("sync", payload);
1051
- i += 1;
1052
- }
1053
- } catch (error) {
1054
- const handled = this.handleHubError(error);
1055
- if (!handled) {
1056
- this.logger.debug("Error while synchronizing data with Apitally Hub (will retry)", {
1057
- error
1058
- });
1059
- this.syncDataQueue.push(payload);
1060
- break;
1061
- }
1062
- }
1063
- }
1064
- }
1065
- }
1066
- async sendLogData() {
1067
- this.logger.debug("Sending request log data to Apitally Hub");
1068
- await this.requestLogger.rotateFile();
1069
- const fetchWithRetry = (0, import_fetch_retry.default)(fetch, {
1070
- retries: 3,
1071
- retryDelay: 1e3,
1072
- retryOn: [
1073
- 408,
1074
- 429,
1075
- 500,
1076
- 502,
1077
- 503,
1078
- 504
1079
- ]
1080
- });
1081
- let i = 0;
1082
- let logFile;
1083
- while (logFile = this.requestLogger.getFile()) {
1084
- if (i > 0) {
1085
- await this.randomDelay();
1086
- }
1087
- try {
1088
- const response = await fetchWithRetry(`${this.getHubUrlPrefix()}log?uuid=${logFile.uuid}`, {
1089
- method: "POST",
1090
- body: await logFile.getContent()
1091
- });
1092
- if (response.status === 402 && response.headers.has("Retry-After")) {
1093
- const retryAfter = parseInt(response.headers.get("Retry-After") ?? "0");
1094
- if (retryAfter > 0) {
1095
- this.requestLogger.suspendUntil = Date.now() + retryAfter * 1e3;
1096
- this.requestLogger.clear();
1097
- return;
1098
- }
1099
- }
1100
- if (!response.ok) {
1101
- throw new HTTPError(response);
1102
- }
1103
- logFile.delete();
1104
- } catch (error) {
1105
- this.requestLogger.retryFileLater(logFile);
1106
- break;
1107
- }
1108
- i++;
1109
- if (i >= 10) break;
1110
- }
1111
- }
1112
- handleHubError(error) {
1113
- if (error instanceof HTTPError) {
1114
- if (error.response.status === 404) {
1115
- this.logger.error(`Invalid Apitally client ID: '${this.clientId}'`);
1116
- this.enabled = false;
1117
- this.stopSync();
1118
- return true;
1119
- }
1120
- if (error.response.status === 422) {
1121
- this.logger.error("Received validation error from Apitally Hub");
1122
- return true;
1123
- }
1124
- }
1125
- return false;
1126
- }
1127
- async randomDelay() {
1128
- const delay = 100 + Math.random() * 400;
1129
- await new Promise((resolve) => setTimeout(resolve, delay));
1130
- }
1131
- };
1132
- __name(_ApitallyClient, "ApitallyClient");
1133
- __publicField(_ApitallyClient, "instance");
1134
- var ApitallyClient = _ApitallyClient;
1135
-
1136
- // src/common/headers.ts
1137
- function parseContentLength(contentLength) {
1138
- if (contentLength === void 0 || contentLength === null) {
1139
- return void 0;
1140
- }
1141
- if (typeof contentLength === "number") {
1142
- return contentLength;
1143
- }
1144
- if (typeof contentLength === "string") {
1145
- const parsed = parseInt(contentLength);
1146
- return isNaN(parsed) ? void 0 : parsed;
1147
- }
1148
- if (Array.isArray(contentLength)) {
1149
- return parseContentLength(contentLength[0]);
1150
- }
1151
- return void 0;
1152
- }
1153
- __name(parseContentLength, "parseContentLength");
1154
-
1155
- // src/common/response.ts
1156
- async function measureResponseSize(response, tee = true) {
1157
- const [newResponse1, newResponse2] = tee ? teeResponse(response) : [
1158
- response,
1159
- response
1160
- ];
1161
- let size = 0;
1162
- if (newResponse2.body) {
1163
- let done = false;
1164
- const reader = newResponse2.body.getReader();
1165
- while (!done) {
1166
- const result = await reader.read();
1167
- done = result.done;
1168
- if (!done && result.value) {
1169
- size += result.value.byteLength;
1170
- }
1171
- }
1172
- }
1173
- return [
1174
- size,
1175
- newResponse1
1176
- ];
1177
- }
1178
- __name(measureResponseSize, "measureResponseSize");
1179
- async function getResponseBody(response, tee = true) {
1180
- const [newResponse1, newResponse2] = tee ? teeResponse(response) : [
1181
- response,
1182
- response
1183
- ];
1184
- const responseBuffer = Buffer.from(await newResponse2.arrayBuffer());
1185
- return [
1186
- responseBuffer,
1187
- newResponse1
1188
- ];
1189
- }
1190
- __name(getResponseBody, "getResponseBody");
1191
- async function getResponseJson(response) {
1192
- const contentType = response.headers.get("content-type");
1193
- if (contentType == null ? void 0 : contentType.includes("application/json")) {
1194
- const [newResponse1, newResponse2] = teeResponse(response);
1195
- const responseJson = await newResponse2.json();
1196
- return [
1197
- responseJson,
1198
- newResponse1
1199
- ];
1200
- }
1201
- return [
1202
- null,
1203
- response
1204
- ];
1205
- }
1206
- __name(getResponseJson, "getResponseJson");
1207
- function teeResponse(response) {
1208
- if (!response.body) {
1209
- return [
1210
- response,
1211
- response
1212
- ];
1213
- }
1214
- const [stream1, stream2] = response.body.tee();
1215
- const newResponse1 = new Response(stream1, {
1216
- status: response.status,
1217
- statusText: response.statusText,
1218
- headers: response.headers
1219
- });
1220
- const newResponse2 = new Response(stream2, {
1221
- status: response.status,
1222
- statusText: response.statusText,
1223
- headers: response.headers
1224
- });
1225
- return [
1226
- newResponse1,
1227
- newResponse2
1228
- ];
1229
- }
1230
- __name(teeResponse, "teeResponse");
1231
-
1232
- // src/loggers/console.ts
1233
- var import_node_util = require("util");
1234
- var MAX_BUFFER_SIZE = 1e3;
1235
- var isPatched = false;
1236
- var globalLogsContext;
1237
- function patchConsole(logsContext) {
1238
- globalLogsContext = logsContext;
1239
- if (isPatched) {
1240
- return;
1241
- }
1242
- const logMethods = [
1243
- "log",
1244
- "warn",
1245
- "error",
1246
- "info",
1247
- "debug"
1248
- ];
1249
- logMethods.forEach((method) => {
1250
- const originalMethod = console[method];
1251
- console[method] = function(...args) {
1252
- captureLog(method, args);
1253
- return originalMethod.apply(console, args);
1254
- };
1255
- });
1256
- isPatched = true;
1257
- }
1258
- __name(patchConsole, "patchConsole");
1259
- function captureLog(level, args) {
1260
- const logs = globalLogsContext == null ? void 0 : globalLogsContext.getStore();
1261
- if (logs && logs.length < MAX_BUFFER_SIZE) {
1262
- logs.push({
1263
- timestamp: Date.now() / 1e3,
1264
- logger: "console",
1265
- level,
1266
- message: (0, import_node_util.format)(...args)
1267
- });
1268
- }
1269
- }
1270
- __name(captureLog, "captureLog");
1271
-
1272
- // src/loggers/hapi.ts
1273
- var import_node_util2 = require("util");
1274
-
1275
- // src/loggers/utils.ts
1276
- var import_node_util3 = require("util");
1277
- function formatMessage(message, ...args) {
1278
- return [
1279
- message,
1280
- ...args
1281
- ].map(formatArg).filter((arg) => arg !== "").join("\n");
1282
- }
1283
- __name(formatMessage, "formatMessage");
1284
- function removeKeys(obj, keys) {
1285
- return Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key)));
1286
- }
1287
- __name(removeKeys, "removeKeys");
1288
- function formatArg(arg) {
1289
- if (typeof arg === "string") {
1290
- return arg.trim();
1291
- }
1292
- if (arg instanceof Error) {
1293
- return (0, import_node_util3.format)(arg).trim();
1294
- }
1295
- if (arg === void 0 || arg === null || isEmptyObject(arg)) {
1296
- return "";
1297
- }
1298
- try {
1299
- return JSON.stringify(arg);
1300
- } catch {
1301
- return (0, import_node_util3.format)(arg).trim();
1302
- }
1303
- }
1304
- __name(formatArg, "formatArg");
1305
- function isEmptyObject(obj) {
1306
- return obj !== null && typeof obj === "object" && Object.getPrototypeOf(obj) === Object.prototype && Object.keys(obj).length === 0;
1307
- }
1308
- __name(isEmptyObject, "isEmptyObject");
1309
-
1310
- // src/loggers/pino.ts
1311
- var originalStreamSym = Symbol.for("apitally.originalStream");
1312
-
1313
- // src/loggers/winston.ts
1314
- var MAX_BUFFER_SIZE2 = 1e3;
1315
- var isPatched2 = false;
1316
- var globalLogsContext2;
1317
- async function patchWinston(logsContext) {
1318
- var _a2, _b;
1319
- globalLogsContext2 = logsContext;
1320
- if (isPatched2) {
1321
- return;
1322
- }
1323
- try {
1324
- const loggerModule = await import("winston/lib/winston/logger.js");
1325
- if ((_b = (_a2 = loggerModule.default) == null ? void 0 : _a2.prototype) == null ? void 0 : _b.write) {
1326
- const originalWrite = loggerModule.default.prototype.write;
1327
- loggerModule.default.prototype.write = function(info) {
1328
- captureLog2(info);
1329
- return originalWrite.call(this, info);
1330
- };
1331
- }
1332
- } catch {
1333
- }
1334
- isPatched2 = true;
1335
- }
1336
- __name(patchWinston, "patchWinston");
1337
- function captureLog2(info) {
1338
- const logs = globalLogsContext2 == null ? void 0 : globalLogsContext2.getStore();
1339
- if (!logs || !info || logs.length >= MAX_BUFFER_SIZE2) {
1340
- return;
1341
- }
1342
- try {
1343
- const rest = removeKeys(info, [
1344
- "timestamp",
1345
- "level",
1346
- "message",
1347
- "splat"
1348
- ]);
1349
- const formattedMessage = formatMessage(info.message, rest);
1350
- if (formattedMessage) {
1351
- logs.push({
1352
- timestamp: parseTimestamp(info.timestamp),
1353
- level: info.level || "info",
1354
- message: formattedMessage.trim()
1355
- });
1356
- }
1357
- } catch (e) {
1358
- }
1359
- }
1360
- __name(captureLog2, "captureLog");
1361
- function parseTimestamp(timestamp) {
1362
- if (timestamp) {
1363
- const ts = new Date(timestamp).getTime();
1364
- if (!isNaN(ts)) {
1365
- return ts / 1e3;
1366
- }
1367
- }
1368
- return Date.now() / 1e3;
1369
- }
1370
- __name(parseTimestamp, "parseTimestamp");
1371
-
1372
- // src/hono/utils.ts
1373
- var import_handler = require("hono/utils/handler");
1374
-
1375
- // src/common/packageVersions.ts
1376
- var import_node_module = require("module");
1377
- var import_meta = {};
1378
- function getPackageVersion(name) {
1379
- const packageJsonPath = `${name}/package.json`;
1380
- try {
1381
- return require(packageJsonPath).version || null;
1382
- } catch (error) {
1383
- try {
1384
- const _require = (0, import_node_module.createRequire)(import_meta.url);
1385
- return _require(packageJsonPath).version || null;
1386
- } catch (error2) {
1387
- return null;
1388
- }
1389
- }
1390
- }
1391
- __name(getPackageVersion, "getPackageVersion");
1392
-
1393
- // src/hono/utils.ts
1394
- function getAppInfo(app, appVersion) {
1395
- const versions = [];
1396
- if (process.versions.node) {
1397
- versions.push([
1398
- "nodejs",
1399
- process.versions.node
1400
- ]);
1401
- }
1402
- if (process.versions.bun) {
1403
- versions.push([
1404
- "bun",
1405
- process.versions.bun
1406
- ]);
1407
- }
1408
- const honoVersion = getPackageVersion("hono");
1409
- const apitallyVersion = getPackageVersion("../..");
1410
- if (honoVersion) {
1411
- versions.push([
1412
- "hono",
1413
- honoVersion
1414
- ]);
1415
- }
1416
- if (apitallyVersion) {
1417
- versions.push([
1418
- "apitally",
1419
- apitallyVersion
1420
- ]);
1421
- }
1422
- if (appVersion) {
1423
- versions.push([
1424
- "app",
1425
- appVersion
1426
- ]);
1427
- }
1428
- return {
1429
- paths: listEndpoints(app),
1430
- versions: Object.fromEntries(versions),
1431
- client: "js:hono"
1432
- };
1433
- }
1434
- __name(getAppInfo, "getAppInfo");
1435
- function listEndpoints(app) {
1436
- const endpoints = [];
1437
- app.routes.forEach((route) => {
1438
- if (![
1439
- "ALL",
1440
- "HEAD",
1441
- "OPTIONS"
1442
- ].includes(route.method.toUpperCase()) && !(0, import_handler.isMiddleware)(route.handler)) {
1443
- endpoints.push({
1444
- method: route.method.toUpperCase(),
1445
- path: route.path
1446
- });
1447
- }
1448
- });
1449
- return endpoints;
1450
- }
1451
- __name(listEndpoints, "listEndpoints");
1452
- function extractZodErrors(responseJson) {
1453
- var _a2;
1454
- try {
1455
- const errors = [];
1456
- if (responseJson && responseJson.success === false && responseJson.error && responseJson.error.name === "ZodError") {
1457
- const zodError = responseJson.error;
1458
- (_a2 = zodError.issues) == null ? void 0 : _a2.forEach((zodIssue) => {
1459
- errors.push({
1460
- loc: zodIssue.path.join("."),
1461
- msg: zodIssue.message,
1462
- type: zodIssue.code
1463
- });
1464
- });
1465
- }
1466
- return errors;
1467
- } catch (error) {
1468
- return [];
1469
- }
1470
- }
1471
- __name(extractZodErrors, "extractZodErrors");
1472
-
1473
- // src/hono/middleware.ts
26
+ var import_node_async_hooks = require("node:async_hooks");
27
+ var import_node_perf_hooks = require("node:perf_hooks");
28
+ var import_client = require("../common/client.js");
29
+ var import_consumerRegistry = require("../common/consumerRegistry.js");
30
+ var import_headers = require("../common/headers.js");
31
+ var import_requestLogger = require("../common/requestLogger.js");
32
+ var import_response = require("../common/response.js");
33
+ var import_loggers = require("../loggers/index.js");
34
+ var import_utils = require("./utils.js");
1474
35
  function useApitally(app, config) {
1475
- const client = new ApitallyClient(config);
36
+ const client = new import_client.ApitallyClient(config);
1476
37
  const middleware = getMiddleware(client);
1477
38
  app.use(middleware);
1478
39
  const setStartupData = /* @__PURE__ */ __name((attempt = 1) => {
1479
- const appInfo = getAppInfo(app, config.appVersion);
40
+ const appInfo = (0, import_utils.getAppInfo)(app, config.appVersion);
1480
41
  if (appInfo.paths.length > 0 || attempt >= 10) {
1481
42
  client.setStartupData(appInfo);
1482
43
  client.startSync();
@@ -1490,8 +51,8 @@ __name(useApitally, "useApitally");
1490
51
  function getMiddleware(client) {
1491
52
  const logsContext = new import_node_async_hooks.AsyncLocalStorage();
1492
53
  if (client.requestLogger.config.captureLogs) {
1493
- patchConsole(logsContext);
1494
- patchWinston(logsContext);
54
+ (0, import_loggers.patchConsole)(logsContext);
55
+ (0, import_loggers.patchWinston)(logsContext);
1495
56
  }
1496
57
  return async (c, next) => {
1497
58
  if (!client.isEnabled() || c.req.method.toUpperCase() === "OPTIONS") {
@@ -1504,8 +65,8 @@ function getMiddleware(client) {
1504
65
  await next();
1505
66
  let response;
1506
67
  const responseTime = import_node_perf_hooks.performance.now() - startTime;
1507
- const [responseSize, newResponse] = await measureResponseSize(c.res);
1508
- const requestSize = parseContentLength(c.req.header("content-length"));
68
+ const [responseSize, newResponse] = await (0, import_response.measureResponseSize)(c.res);
69
+ const requestSize = (0, import_headers.parseContentLength)(c.req.header("content-length"));
1509
70
  const consumer = getConsumer(c);
1510
71
  client.consumerRegistry.addOrUpdateConsumer(consumer);
1511
72
  client.requestCounter.addRequest({
@@ -1519,8 +80,8 @@ function getMiddleware(client) {
1519
80
  });
1520
81
  response = newResponse;
1521
82
  if (c.res.status === 400) {
1522
- const [responseJson, newResponse2] = await getResponseJson(response);
1523
- const validationErrors = extractZodErrors(responseJson);
83
+ const [responseJson, newResponse2] = await (0, import_response.getResponseJson)(response);
84
+ const validationErrors = (0, import_utils.extractZodErrors)(responseJson);
1524
85
  validationErrors.forEach((error) => {
1525
86
  client.validationErrorCounter.addValidationError({
1526
87
  consumer: consumer == null ? void 0 : consumer.identifier,
@@ -1551,7 +112,7 @@ function getMiddleware(client) {
1551
112
  requestBody = Buffer.from(await c.req.arrayBuffer());
1552
113
  }
1553
114
  if (client.requestLogger.config.logResponseBody && client.requestLogger.isSupportedContentType(responseContentType)) {
1554
- [responseBody, newResponse2] = await getResponseBody(response);
115
+ [responseBody, newResponse2] = await (0, import_response.getResponseBody)(response);
1555
116
  response = newResponse2;
1556
117
  }
1557
118
  const logs = logsContext.getStore();
@@ -1560,14 +121,14 @@ function getMiddleware(client) {
1560
121
  method: c.req.method,
1561
122
  path: c.req.routePath,
1562
123
  url: c.req.url,
1563
- headers: convertHeaders(c.req.header()),
124
+ headers: (0, import_requestLogger.convertHeaders)(c.req.header()),
1564
125
  size: requestSize,
1565
126
  consumer: consumer == null ? void 0 : consumer.identifier,
1566
127
  body: requestBody
1567
128
  }, {
1568
129
  statusCode: c.res.status,
1569
130
  responseTime: responseTime / 1e3,
1570
- headers: convertHeaders(c.res.headers),
131
+ headers: (0, import_requestLogger.convertHeaders)(c.res.headers),
1571
132
  size: responseSize,
1572
133
  body: responseBody
1573
134
  }, c.error, logs);
@@ -1584,7 +145,7 @@ __name(setConsumer, "setConsumer");
1584
145
  function getConsumer(c) {
1585
146
  const consumer = c.get("apitallyConsumer");
1586
147
  if (consumer) {
1587
- return consumerFromStringOrObject(consumer);
148
+ return (0, import_consumerRegistry.consumerFromStringOrObject)(consumer);
1588
149
  }
1589
150
  return null;
1590
151
  }