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