apitally 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +47 -10
  2. package/dist/adonisjs/index.cjs +41 -0
  3. package/dist/adonisjs/index.cjs.map +1 -0
  4. package/dist/adonisjs/index.d.cts +14 -0
  5. package/dist/adonisjs/index.d.ts +14 -0
  6. package/dist/adonisjs/index.js +17 -0
  7. package/dist/adonisjs/index.js.map +1 -0
  8. package/dist/adonisjs/middleware.cjs +214 -0
  9. package/dist/adonisjs/middleware.cjs.map +1 -0
  10. package/dist/adonisjs/middleware.d.cts +21 -0
  11. package/dist/adonisjs/middleware.d.ts +21 -0
  12. package/dist/adonisjs/middleware.js +185 -0
  13. package/dist/adonisjs/middleware.js.map +1 -0
  14. package/dist/adonisjs/provider.cjs +1083 -0
  15. package/dist/adonisjs/provider.cjs.map +1 -0
  16. package/dist/adonisjs/provider.d.cts +28 -0
  17. package/dist/adonisjs/provider.d.ts +28 -0
  18. package/dist/adonisjs/provider.js +1057 -0
  19. package/dist/adonisjs/provider.js.map +1 -0
  20. package/dist/common/client.cjs +1 -1
  21. package/dist/common/client.cjs.map +1 -1
  22. package/dist/common/client.js +1 -1
  23. package/dist/common/client.js.map +1 -1
  24. package/dist/common/consumerRegistry.cjs.map +1 -1
  25. package/dist/common/consumerRegistry.js.map +1 -1
  26. package/dist/common/logging.cjs.map +1 -1
  27. package/dist/common/logging.js.map +1 -1
  28. package/dist/common/packageVersions.cjs.map +1 -1
  29. package/dist/common/packageVersions.js.map +1 -1
  30. package/dist/common/paramValidation.cjs.map +1 -1
  31. package/dist/common/paramValidation.js.map +1 -1
  32. package/dist/common/requestCounter.cjs.map +1 -1
  33. package/dist/common/requestCounter.js.map +1 -1
  34. package/dist/common/requestLogger.cjs.map +1 -1
  35. package/dist/common/requestLogger.js.map +1 -1
  36. package/dist/common/sentry.cjs.map +1 -1
  37. package/dist/common/sentry.js.map +1 -1
  38. package/dist/common/serverErrorCounter.cjs.map +1 -1
  39. package/dist/common/serverErrorCounter.js.map +1 -1
  40. package/dist/common/tempGzipFile.cjs.map +1 -1
  41. package/dist/common/tempGzipFile.js.map +1 -1
  42. package/dist/common/types.cjs.map +1 -1
  43. package/dist/common/types.d.cts +0 -1
  44. package/dist/common/types.d.ts +0 -1
  45. package/dist/common/utils.cjs +48 -0
  46. package/dist/common/utils.cjs.map +1 -0
  47. package/dist/common/utils.d.cts +5 -0
  48. package/dist/common/utils.d.ts +5 -0
  49. package/dist/common/utils.js +25 -0
  50. package/dist/common/utils.js.map +1 -0
  51. package/dist/common/validationErrorCounter.cjs.map +1 -1
  52. package/dist/common/validationErrorCounter.js.map +1 -1
  53. package/dist/express/index.cjs +91 -25
  54. package/dist/express/index.cjs.map +1 -1
  55. package/dist/express/index.js +91 -25
  56. package/dist/express/index.js.map +1 -1
  57. package/dist/express/middleware.cjs +91 -25
  58. package/dist/express/middleware.cjs.map +1 -1
  59. package/dist/express/middleware.js +91 -25
  60. package/dist/express/middleware.js.map +1 -1
  61. package/dist/express/utils.cjs +59 -16
  62. package/dist/express/utils.cjs.map +1 -1
  63. package/dist/express/utils.d.cts +11 -2
  64. package/dist/express/utils.d.ts +11 -2
  65. package/dist/express/utils.js +56 -15
  66. package/dist/express/utils.js.map +1 -1
  67. package/dist/fastify/index.cjs +22 -6
  68. package/dist/fastify/index.cjs.map +1 -1
  69. package/dist/fastify/index.js +22 -6
  70. package/dist/fastify/index.js.map +1 -1
  71. package/dist/fastify/plugin.cjs +22 -6
  72. package/dist/fastify/plugin.cjs.map +1 -1
  73. package/dist/fastify/plugin.js +22 -6
  74. package/dist/fastify/plugin.js.map +1 -1
  75. package/dist/hono/index.cjs +21 -2
  76. package/dist/hono/index.cjs.map +1 -1
  77. package/dist/hono/index.js +21 -2
  78. package/dist/hono/index.js.map +1 -1
  79. package/dist/hono/middleware.cjs +21 -2
  80. package/dist/hono/middleware.cjs.map +1 -1
  81. package/dist/hono/middleware.js +21 -2
  82. package/dist/hono/middleware.js.map +1 -1
  83. package/dist/koa/index.cjs +3 -3
  84. package/dist/koa/index.cjs.map +1 -1
  85. package/dist/koa/index.js +3 -3
  86. package/dist/koa/index.js.map +1 -1
  87. package/dist/koa/middleware.cjs +3 -3
  88. package/dist/koa/middleware.cjs.map +1 -1
  89. package/dist/koa/middleware.js +3 -3
  90. package/dist/koa/middleware.js.map +1 -1
  91. package/dist/nestjs/index.cjs +91 -25
  92. package/dist/nestjs/index.cjs.map +1 -1
  93. package/dist/nestjs/index.js +91 -25
  94. package/dist/nestjs/index.js.map +1 -1
  95. package/package.json +71 -52
@@ -0,0 +1,1083 @@
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/adonisjs/provider.ts
34
+ var provider_exports = {};
35
+ __export(provider_exports, {
36
+ default: () => ApitallyProvider
37
+ });
38
+ module.exports = __toCommonJS(provider_exports);
39
+
40
+ // src/common/client.ts
41
+ var import_crypto5 = require("crypto");
42
+ var import_fetch_retry = __toESM(require("fetch-retry"), 1);
43
+
44
+ // src/common/consumerRegistry.ts
45
+ var _ConsumerRegistry = class _ConsumerRegistry {
46
+ consumers;
47
+ updated;
48
+ constructor() {
49
+ this.consumers = /* @__PURE__ */ new Map();
50
+ this.updated = /* @__PURE__ */ new Set();
51
+ }
52
+ addOrUpdateConsumer(consumer) {
53
+ if (!consumer || !consumer.name && !consumer.group) {
54
+ return;
55
+ }
56
+ const existing = this.consumers.get(consumer.identifier);
57
+ if (!existing) {
58
+ this.consumers.set(consumer.identifier, consumer);
59
+ this.updated.add(consumer.identifier);
60
+ } else {
61
+ if (consumer.name && consumer.name !== existing.name) {
62
+ existing.name = consumer.name;
63
+ this.updated.add(consumer.identifier);
64
+ }
65
+ if (consumer.group && consumer.group !== existing.group) {
66
+ existing.group = consumer.group;
67
+ this.updated.add(consumer.identifier);
68
+ }
69
+ }
70
+ }
71
+ getAndResetUpdatedConsumers() {
72
+ const data = [];
73
+ this.updated.forEach((identifier) => {
74
+ const consumer = this.consumers.get(identifier);
75
+ if (consumer) {
76
+ data.push(consumer);
77
+ }
78
+ });
79
+ this.updated.clear();
80
+ return data;
81
+ }
82
+ };
83
+ __name(_ConsumerRegistry, "ConsumerRegistry");
84
+ var ConsumerRegistry = _ConsumerRegistry;
85
+
86
+ // src/common/logging.ts
87
+ var import_winston = require("winston");
88
+ var getLogger = /* @__PURE__ */ __name(() => {
89
+ return (0, import_winston.createLogger)({
90
+ level: process.env.APITALLY_DEBUG ? "debug" : "warn",
91
+ format: import_winston.format.combine(import_winston.format.colorize(), import_winston.format.timestamp(), import_winston.format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`)),
92
+ transports: [
93
+ new import_winston.transports.Console()
94
+ ]
95
+ });
96
+ }, "getLogger");
97
+
98
+ // src/common/paramValidation.ts
99
+ function isValidClientId(clientId) {
100
+ 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;
101
+ return regexExp.test(clientId);
102
+ }
103
+ __name(isValidClientId, "isValidClientId");
104
+ function isValidEnv(env) {
105
+ const regexExp = /^[\w-]{1,32}$/;
106
+ return regexExp.test(env);
107
+ }
108
+ __name(isValidEnv, "isValidEnv");
109
+
110
+ // src/common/requestCounter.ts
111
+ var _RequestCounter = class _RequestCounter {
112
+ requestCounts;
113
+ requestSizeSums;
114
+ responseSizeSums;
115
+ responseTimes;
116
+ requestSizes;
117
+ responseSizes;
118
+ constructor() {
119
+ this.requestCounts = /* @__PURE__ */ new Map();
120
+ this.requestSizeSums = /* @__PURE__ */ new Map();
121
+ this.responseSizeSums = /* @__PURE__ */ new Map();
122
+ this.responseTimes = /* @__PURE__ */ new Map();
123
+ this.requestSizes = /* @__PURE__ */ new Map();
124
+ this.responseSizes = /* @__PURE__ */ new Map();
125
+ }
126
+ getKey(requestInfo) {
127
+ return [
128
+ requestInfo.consumer || "",
129
+ requestInfo.method.toUpperCase(),
130
+ requestInfo.path,
131
+ requestInfo.statusCode
132
+ ].join("|");
133
+ }
134
+ addRequest(requestInfo) {
135
+ const key = this.getKey(requestInfo);
136
+ this.requestCounts.set(key, (this.requestCounts.get(key) || 0) + 1);
137
+ if (!this.responseTimes.has(key)) {
138
+ this.responseTimes.set(key, /* @__PURE__ */ new Map());
139
+ }
140
+ const responseTimeMap = this.responseTimes.get(key);
141
+ const responseTimeMsBin = Math.floor(requestInfo.responseTime / 10) * 10;
142
+ responseTimeMap.set(responseTimeMsBin, (responseTimeMap.get(responseTimeMsBin) || 0) + 1);
143
+ if (requestInfo.requestSize !== void 0) {
144
+ requestInfo.requestSize = Number(requestInfo.requestSize);
145
+ this.requestSizeSums.set(key, (this.requestSizeSums.get(key) || 0) + requestInfo.requestSize);
146
+ if (!this.requestSizes.has(key)) {
147
+ this.requestSizes.set(key, /* @__PURE__ */ new Map());
148
+ }
149
+ const requestSizeMap = this.requestSizes.get(key);
150
+ const requestSizeKbBin = Math.floor(requestInfo.requestSize / 1e3);
151
+ requestSizeMap.set(requestSizeKbBin, (requestSizeMap.get(requestSizeKbBin) || 0) + 1);
152
+ }
153
+ if (requestInfo.responseSize !== void 0) {
154
+ requestInfo.responseSize = Number(requestInfo.responseSize);
155
+ this.responseSizeSums.set(key, (this.responseSizeSums.get(key) || 0) + requestInfo.responseSize);
156
+ if (!this.responseSizes.has(key)) {
157
+ this.responseSizes.set(key, /* @__PURE__ */ new Map());
158
+ }
159
+ const responseSizeMap = this.responseSizes.get(key);
160
+ const responseSizeKbBin = Math.floor(requestInfo.responseSize / 1e3);
161
+ responseSizeMap.set(responseSizeKbBin, (responseSizeMap.get(responseSizeKbBin) || 0) + 1);
162
+ }
163
+ }
164
+ getAndResetRequests() {
165
+ const data = [];
166
+ this.requestCounts.forEach((count, key) => {
167
+ const [consumer, method, path, statusCodeStr] = key.split("|");
168
+ const responseTimes = this.responseTimes.get(key) || /* @__PURE__ */ new Map();
169
+ const requestSizes = this.requestSizes.get(key) || /* @__PURE__ */ new Map();
170
+ const responseSizes = this.responseSizes.get(key) || /* @__PURE__ */ new Map();
171
+ data.push({
172
+ consumer: consumer || null,
173
+ method,
174
+ path,
175
+ status_code: parseInt(statusCodeStr),
176
+ request_count: count,
177
+ request_size_sum: this.requestSizeSums.get(key) || 0,
178
+ response_size_sum: this.responseSizeSums.get(key) || 0,
179
+ response_times: Object.fromEntries(responseTimes),
180
+ request_sizes: Object.fromEntries(requestSizes),
181
+ response_sizes: Object.fromEntries(responseSizes)
182
+ });
183
+ });
184
+ this.requestCounts.clear();
185
+ this.requestSizeSums.clear();
186
+ this.responseSizeSums.clear();
187
+ this.responseTimes.clear();
188
+ this.requestSizes.clear();
189
+ this.responseSizes.clear();
190
+ return data;
191
+ }
192
+ };
193
+ __name(_RequestCounter, "RequestCounter");
194
+ var RequestCounter = _RequestCounter;
195
+
196
+ // src/common/requestLogger.ts
197
+ var import_async_lock = __toESM(require("async-lock"), 1);
198
+ var import_buffer2 = require("buffer");
199
+ var import_crypto3 = require("crypto");
200
+ var import_fs2 = require("fs");
201
+ var import_os2 = require("os");
202
+ var import_path2 = require("path");
203
+
204
+ // src/common/sentry.ts
205
+ var sentry;
206
+ (async () => {
207
+ try {
208
+ sentry = await import("@sentry/node");
209
+ } catch (e) {
210
+ }
211
+ })();
212
+ function getSentryEventId() {
213
+ if (sentry && sentry.lastEventId) {
214
+ return sentry.lastEventId();
215
+ }
216
+ return void 0;
217
+ }
218
+ __name(getSentryEventId, "getSentryEventId");
219
+
220
+ // src/common/serverErrorCounter.ts
221
+ var import_crypto = require("crypto");
222
+ var MAX_MSG_LENGTH = 2048;
223
+ var MAX_STACKTRACE_LENGTH = 65536;
224
+ var _ServerErrorCounter = class _ServerErrorCounter {
225
+ errorCounts;
226
+ errorDetails;
227
+ sentryEventIds;
228
+ constructor() {
229
+ this.errorCounts = /* @__PURE__ */ new Map();
230
+ this.errorDetails = /* @__PURE__ */ new Map();
231
+ this.sentryEventIds = /* @__PURE__ */ new Map();
232
+ }
233
+ addServerError(serverError) {
234
+ const key = this.getKey(serverError);
235
+ if (!this.errorDetails.has(key)) {
236
+ this.errorDetails.set(key, serverError);
237
+ }
238
+ this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
239
+ const sentryEventId = getSentryEventId();
240
+ if (sentryEventId) {
241
+ this.sentryEventIds.set(key, sentryEventId);
242
+ }
243
+ }
244
+ getAndResetServerErrors() {
245
+ const data = [];
246
+ this.errorCounts.forEach((count, key) => {
247
+ const serverError = this.errorDetails.get(key);
248
+ if (serverError) {
249
+ data.push({
250
+ consumer: serverError.consumer || null,
251
+ method: serverError.method,
252
+ path: serverError.path,
253
+ type: serverError.type,
254
+ msg: truncateExceptionMessage(serverError.msg),
255
+ traceback: truncateExceptionStackTrace(serverError.traceback),
256
+ sentry_event_id: this.sentryEventIds.get(key) || null,
257
+ error_count: count
258
+ });
259
+ }
260
+ });
261
+ this.errorCounts.clear();
262
+ this.errorDetails.clear();
263
+ return data;
264
+ }
265
+ getKey(serverError) {
266
+ const hashInput = [
267
+ serverError.consumer || "",
268
+ serverError.method.toUpperCase(),
269
+ serverError.path,
270
+ serverError.type,
271
+ serverError.msg.trim(),
272
+ serverError.traceback.trim()
273
+ ].join("|");
274
+ return (0, import_crypto.createHash)("md5").update(hashInput).digest("hex");
275
+ }
276
+ };
277
+ __name(_ServerErrorCounter, "ServerErrorCounter");
278
+ var ServerErrorCounter = _ServerErrorCounter;
279
+ function truncateExceptionMessage(msg) {
280
+ if (msg.length <= MAX_MSG_LENGTH) {
281
+ return msg;
282
+ }
283
+ const suffix = "... (truncated)";
284
+ const cutoff = MAX_MSG_LENGTH - suffix.length;
285
+ return msg.substring(0, cutoff) + suffix;
286
+ }
287
+ __name(truncateExceptionMessage, "truncateExceptionMessage");
288
+ function truncateExceptionStackTrace(stack) {
289
+ const suffix = "... (truncated) ...";
290
+ const cutoff = MAX_STACKTRACE_LENGTH - suffix.length;
291
+ const lines = stack.trim().split("\n");
292
+ const truncatedLines = [];
293
+ let length = 0;
294
+ for (const line of lines) {
295
+ if (length + line.length + 1 > cutoff) {
296
+ truncatedLines.push(suffix);
297
+ break;
298
+ }
299
+ truncatedLines.push(line);
300
+ length += line.length + 1;
301
+ }
302
+ return truncatedLines.join("\n");
303
+ }
304
+ __name(truncateExceptionStackTrace, "truncateExceptionStackTrace");
305
+
306
+ // src/common/tempGzipFile.ts
307
+ var import_buffer = require("buffer");
308
+ var import_crypto2 = require("crypto");
309
+ var import_fs = require("fs");
310
+ var import_os = require("os");
311
+ var import_path = require("path");
312
+ var import_zlib = require("zlib");
313
+ var _TempGzipFile = class _TempGzipFile {
314
+ uuid;
315
+ filePath;
316
+ gzip;
317
+ writeStream;
318
+ readyPromise;
319
+ closedPromise;
320
+ constructor() {
321
+ this.uuid = (0, import_crypto2.randomUUID)();
322
+ this.filePath = (0, import_path.join)((0, import_os.tmpdir)(), `apitally-${this.uuid}.gz`);
323
+ this.writeStream = (0, import_fs.createWriteStream)(this.filePath);
324
+ this.readyPromise = new Promise((resolve, reject) => {
325
+ this.writeStream.once("ready", resolve);
326
+ this.writeStream.once("error", reject);
327
+ });
328
+ this.closedPromise = new Promise((resolve, reject) => {
329
+ this.writeStream.once("close", resolve);
330
+ this.writeStream.once("error", reject);
331
+ });
332
+ this.gzip = (0, import_zlib.createGzip)();
333
+ this.gzip.pipe(this.writeStream);
334
+ }
335
+ get size() {
336
+ return this.writeStream.bytesWritten;
337
+ }
338
+ async writeLine(data) {
339
+ await this.readyPromise;
340
+ return new Promise((resolve, reject) => {
341
+ this.gzip.write(import_buffer.Buffer.concat([
342
+ data,
343
+ import_buffer.Buffer.from("\n")
344
+ ]), (error) => {
345
+ if (error) {
346
+ reject(error);
347
+ } else {
348
+ resolve();
349
+ }
350
+ });
351
+ });
352
+ }
353
+ async getContent() {
354
+ return new Promise((resolve, reject) => {
355
+ (0, import_fs.readFile)(this.filePath, (error, data) => {
356
+ if (error) {
357
+ reject(error);
358
+ } else {
359
+ resolve(data);
360
+ }
361
+ });
362
+ });
363
+ }
364
+ async close() {
365
+ await new Promise((resolve) => {
366
+ this.gzip.end(() => {
367
+ resolve();
368
+ });
369
+ });
370
+ await this.closedPromise;
371
+ }
372
+ async delete() {
373
+ await this.close();
374
+ (0, import_fs.unlinkSync)(this.filePath);
375
+ }
376
+ };
377
+ __name(_TempGzipFile, "TempGzipFile");
378
+ var TempGzipFile = _TempGzipFile;
379
+
380
+ // src/common/requestLogger.ts
381
+ var MAX_BODY_SIZE = 5e4;
382
+ var MAX_FILE_SIZE = 1e6;
383
+ var MAX_FILES = 50;
384
+ var MAX_PENDING_WRITES = 100;
385
+ var BODY_TOO_LARGE = import_buffer2.Buffer.from("<body too large>");
386
+ var BODY_MASKED = import_buffer2.Buffer.from("<masked>");
387
+ var MASKED = "******";
388
+ var ALLOWED_CONTENT_TYPES = [
389
+ "application/json",
390
+ "text/plain"
391
+ ];
392
+ var EXCLUDE_PATH_PATTERNS = [
393
+ /\/_?healthz?$/i,
394
+ /\/_?health[_-]?checks?$/i,
395
+ /\/_?heart[_-]?beats?$/i,
396
+ /\/ping$/i,
397
+ /\/ready$/i,
398
+ /\/live$/i
399
+ ];
400
+ var EXCLUDE_USER_AGENT_PATTERNS = [
401
+ /health[-_ ]?check/i,
402
+ /microsoft-azure-application-lb/i,
403
+ /googlehc/i,
404
+ /kube-probe/i
405
+ ];
406
+ var MASK_QUERY_PARAM_PATTERNS = [
407
+ /auth/i,
408
+ /api-?key/i,
409
+ /secret/i,
410
+ /token/i,
411
+ /password/i,
412
+ /pwd/i
413
+ ];
414
+ var MASK_HEADER_PATTERNS = [
415
+ /auth/i,
416
+ /api-?key/i,
417
+ /secret/i,
418
+ /token/i,
419
+ /cookie/i
420
+ ];
421
+ var DEFAULT_CONFIG = {
422
+ enabled: false,
423
+ logQueryParams: true,
424
+ logRequestHeaders: false,
425
+ logRequestBody: false,
426
+ logResponseHeaders: true,
427
+ logResponseBody: false,
428
+ logException: true,
429
+ maskQueryParams: [],
430
+ maskHeaders: [],
431
+ excludePaths: []
432
+ };
433
+ var _RequestLogger = class _RequestLogger {
434
+ config;
435
+ enabled;
436
+ suspendUntil = null;
437
+ pendingWrites = [];
438
+ currentFile = null;
439
+ files = [];
440
+ maintainIntervalId;
441
+ lock = new import_async_lock.default();
442
+ constructor(config) {
443
+ this.config = {
444
+ ...DEFAULT_CONFIG,
445
+ ...config
446
+ };
447
+ this.enabled = this.config.enabled && checkWritableFs();
448
+ if (this.enabled) {
449
+ this.maintainIntervalId = setInterval(() => {
450
+ this.maintain();
451
+ }, 1e3);
452
+ }
453
+ }
454
+ shouldExcludePath(urlPath) {
455
+ const patterns = [
456
+ ...this.config.excludePaths,
457
+ ...EXCLUDE_PATH_PATTERNS
458
+ ];
459
+ return matchPatterns(urlPath, patterns);
460
+ }
461
+ shouldExcludeUserAgent(userAgent) {
462
+ return userAgent ? matchPatterns(userAgent, EXCLUDE_USER_AGENT_PATTERNS) : false;
463
+ }
464
+ shouldMaskQueryParam(name) {
465
+ const patterns = [
466
+ ...this.config.maskQueryParams,
467
+ ...MASK_QUERY_PARAM_PATTERNS
468
+ ];
469
+ return matchPatterns(name, patterns);
470
+ }
471
+ shouldMaskHeader(name) {
472
+ const patterns = [
473
+ ...this.config.maskHeaders,
474
+ ...MASK_HEADER_PATTERNS
475
+ ];
476
+ return matchPatterns(name, patterns);
477
+ }
478
+ hasSupportedContentType(headers) {
479
+ var _a2;
480
+ const contentType = (_a2 = headers.find(([k]) => k.toLowerCase() === "content-type")) == null ? void 0 : _a2[1];
481
+ return this.isSupportedContentType(contentType);
482
+ }
483
+ isSupportedContentType(contentType) {
484
+ return typeof contentType === "string" && ALLOWED_CONTENT_TYPES.some((t) => contentType.startsWith(t));
485
+ }
486
+ maskQueryParams(search) {
487
+ const params = new URLSearchParams(search);
488
+ for (const [key] of params) {
489
+ if (this.shouldMaskQueryParam(key)) {
490
+ params.set(key, MASKED);
491
+ }
492
+ }
493
+ return params.toString();
494
+ }
495
+ maskHeaders(headers) {
496
+ return headers.map(([k, v]) => [
497
+ k,
498
+ this.shouldMaskHeader(k) ? MASKED : v
499
+ ]);
500
+ }
501
+ logRequest(request, response, error) {
502
+ var _a2, _b, _c;
503
+ if (!this.enabled || this.suspendUntil !== null) return;
504
+ const url = new URL(request.url);
505
+ const path = request.path ?? url.pathname;
506
+ const userAgent = (_a2 = request.headers.find(([k]) => k.toLowerCase() === "user-agent")) == null ? void 0 : _a2[1];
507
+ if (this.shouldExcludePath(path) || this.shouldExcludeUserAgent(userAgent) || (((_c = (_b = this.config).excludeCallback) == null ? void 0 : _c.call(_b, request, response)) ?? false)) {
508
+ return;
509
+ }
510
+ url.search = this.config.logQueryParams ? this.maskQueryParams(url.search) : "";
511
+ request.url = url.toString();
512
+ if (!this.config.logRequestBody || !this.hasSupportedContentType(request.headers)) {
513
+ request.body = void 0;
514
+ } else if (request.body) {
515
+ if (request.body.length > MAX_BODY_SIZE) {
516
+ request.body = BODY_TOO_LARGE;
517
+ } else if (this.config.maskRequestBodyCallback) {
518
+ try {
519
+ request.body = this.config.maskRequestBodyCallback(request) ?? BODY_MASKED;
520
+ if (request.body.length > MAX_BODY_SIZE) {
521
+ request.body = BODY_TOO_LARGE;
522
+ }
523
+ } catch {
524
+ request.body = void 0;
525
+ }
526
+ }
527
+ }
528
+ if (!this.config.logResponseBody || !this.hasSupportedContentType(response.headers)) {
529
+ response.body = void 0;
530
+ } else if (response.body) {
531
+ if (response.body.length > MAX_BODY_SIZE) {
532
+ response.body = BODY_TOO_LARGE;
533
+ } else if (this.config.maskResponseBodyCallback) {
534
+ try {
535
+ response.body = this.config.maskResponseBodyCallback(request, response) ?? BODY_MASKED;
536
+ if (response.body.length > MAX_BODY_SIZE) {
537
+ response.body = BODY_TOO_LARGE;
538
+ }
539
+ } catch {
540
+ response.body = void 0;
541
+ }
542
+ }
543
+ }
544
+ request.headers = this.config.logRequestHeaders ? this.maskHeaders(request.headers) : [];
545
+ response.headers = this.config.logResponseHeaders ? this.maskHeaders(response.headers) : [];
546
+ const item = {
547
+ uuid: (0, import_crypto3.randomUUID)(),
548
+ request: skipEmptyValues(request),
549
+ response: skipEmptyValues(response),
550
+ exception: error && this.config.logException ? {
551
+ type: error.name,
552
+ message: truncateExceptionMessage(error.message),
553
+ stacktrace: truncateExceptionStackTrace(error.stack || ""),
554
+ sentryEventId: getSentryEventId()
555
+ } : null
556
+ };
557
+ [
558
+ item.request.body,
559
+ item.response.body
560
+ ].forEach((body) => {
561
+ if (body) {
562
+ body.toJSON = function() {
563
+ return this.toString("base64");
564
+ };
565
+ }
566
+ });
567
+ this.pendingWrites.push(JSON.stringify(item));
568
+ if (this.pendingWrites.length > MAX_PENDING_WRITES) {
569
+ this.pendingWrites.shift();
570
+ }
571
+ }
572
+ async writeToFile() {
573
+ if (!this.enabled || this.pendingWrites.length === 0) {
574
+ return;
575
+ }
576
+ return this.lock.acquire("file", async () => {
577
+ if (!this.currentFile) {
578
+ this.currentFile = new TempGzipFile();
579
+ }
580
+ while (this.pendingWrites.length > 0) {
581
+ const item = this.pendingWrites.shift();
582
+ if (item) {
583
+ await this.currentFile.writeLine(import_buffer2.Buffer.from(item));
584
+ }
585
+ }
586
+ });
587
+ }
588
+ getFile() {
589
+ return this.files.shift();
590
+ }
591
+ retryFileLater(file) {
592
+ this.files.unshift(file);
593
+ }
594
+ async rotateFile() {
595
+ return this.lock.acquire("file", async () => {
596
+ if (this.currentFile) {
597
+ await this.currentFile.close();
598
+ this.files.push(this.currentFile);
599
+ this.currentFile = null;
600
+ }
601
+ });
602
+ }
603
+ async maintain() {
604
+ await this.writeToFile();
605
+ if (this.currentFile && this.currentFile.size > MAX_FILE_SIZE) {
606
+ await this.rotateFile();
607
+ }
608
+ while (this.files.length > MAX_FILES) {
609
+ const file = this.files.shift();
610
+ file == null ? void 0 : file.delete();
611
+ }
612
+ if (this.suspendUntil !== null && this.suspendUntil < Date.now()) {
613
+ this.suspendUntil = null;
614
+ }
615
+ }
616
+ async clear() {
617
+ this.pendingWrites = [];
618
+ await this.rotateFile();
619
+ this.files.forEach((file) => {
620
+ file.delete();
621
+ });
622
+ this.files = [];
623
+ }
624
+ async close() {
625
+ this.enabled = false;
626
+ await this.clear();
627
+ if (this.maintainIntervalId) {
628
+ clearInterval(this.maintainIntervalId);
629
+ }
630
+ }
631
+ };
632
+ __name(_RequestLogger, "RequestLogger");
633
+ var RequestLogger = _RequestLogger;
634
+ function matchPatterns(value, patterns) {
635
+ return patterns.some((pattern) => {
636
+ return pattern.test(value);
637
+ });
638
+ }
639
+ __name(matchPatterns, "matchPatterns");
640
+ function skipEmptyValues(data) {
641
+ return Object.fromEntries(Object.entries(data).filter(([_, v]) => {
642
+ if (v == null || Number.isNaN(v)) return false;
643
+ if (Array.isArray(v) || import_buffer2.Buffer.isBuffer(v) || typeof v === "string") {
644
+ return v.length > 0;
645
+ }
646
+ return true;
647
+ }));
648
+ }
649
+ __name(skipEmptyValues, "skipEmptyValues");
650
+ function checkWritableFs() {
651
+ try {
652
+ const testPath = (0, import_path2.join)((0, import_os2.tmpdir)(), `apitally-${(0, import_crypto3.randomUUID)()}`);
653
+ (0, import_fs2.writeFileSync)(testPath, "test");
654
+ (0, import_fs2.unlinkSync)(testPath);
655
+ return true;
656
+ } catch (error) {
657
+ return false;
658
+ }
659
+ }
660
+ __name(checkWritableFs, "checkWritableFs");
661
+
662
+ // src/common/validationErrorCounter.ts
663
+ var import_crypto4 = require("crypto");
664
+ var _ValidationErrorCounter = class _ValidationErrorCounter {
665
+ errorCounts;
666
+ errorDetails;
667
+ constructor() {
668
+ this.errorCounts = /* @__PURE__ */ new Map();
669
+ this.errorDetails = /* @__PURE__ */ new Map();
670
+ }
671
+ addValidationError(validationError) {
672
+ const key = this.getKey(validationError);
673
+ if (!this.errorDetails.has(key)) {
674
+ this.errorDetails.set(key, validationError);
675
+ }
676
+ this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
677
+ }
678
+ getAndResetValidationErrors() {
679
+ const data = [];
680
+ this.errorCounts.forEach((count, key) => {
681
+ const validationError = this.errorDetails.get(key);
682
+ if (validationError) {
683
+ data.push({
684
+ consumer: validationError.consumer || null,
685
+ method: validationError.method,
686
+ path: validationError.path,
687
+ loc: validationError.loc.split("."),
688
+ msg: validationError.msg,
689
+ type: validationError.type,
690
+ error_count: count
691
+ });
692
+ }
693
+ });
694
+ this.errorCounts.clear();
695
+ this.errorDetails.clear();
696
+ return data;
697
+ }
698
+ getKey(validationError) {
699
+ const hashInput = [
700
+ validationError.consumer || "",
701
+ validationError.method.toUpperCase(),
702
+ validationError.path,
703
+ validationError.loc,
704
+ validationError.msg.trim(),
705
+ validationError.type
706
+ ].join("|");
707
+ return (0, import_crypto4.createHash)("md5").update(hashInput).digest("hex");
708
+ }
709
+ };
710
+ __name(_ValidationErrorCounter, "ValidationErrorCounter");
711
+ var ValidationErrorCounter = _ValidationErrorCounter;
712
+
713
+ // src/common/client.ts
714
+ var SYNC_INTERVAL = 6e4;
715
+ var INITIAL_SYNC_INTERVAL = 1e4;
716
+ var INITIAL_SYNC_INTERVAL_DURATION = 36e5;
717
+ var MAX_QUEUE_TIME = 36e5;
718
+ var _a;
719
+ var HTTPError = (_a = class extends Error {
720
+ response;
721
+ constructor(response) {
722
+ const reason = response.status ? `status code ${response.status}` : "an unknown error";
723
+ super(`Request failed with ${reason}`);
724
+ this.response = response;
725
+ }
726
+ }, __name(_a, "HTTPError"), _a);
727
+ var _ApitallyClient = class _ApitallyClient {
728
+ clientId;
729
+ env;
730
+ instanceUuid;
731
+ syncDataQueue;
732
+ syncIntervalId;
733
+ startupData;
734
+ startupDataSent = false;
735
+ enabled = true;
736
+ requestCounter;
737
+ requestLogger;
738
+ validationErrorCounter;
739
+ serverErrorCounter;
740
+ consumerRegistry;
741
+ logger;
742
+ constructor({ clientId, env = "dev", requestLoggingConfig, logger }) {
743
+ if (_ApitallyClient.instance) {
744
+ throw new Error("Apitally client is already initialized");
745
+ }
746
+ if (!isValidClientId(clientId)) {
747
+ throw new Error(`Invalid Apitally client ID '${clientId}' (expecting hexadecimal UUID format)`);
748
+ }
749
+ if (!isValidEnv(env)) {
750
+ throw new Error(`Invalid env '${env}' (expecting 1-32 alphanumeric lowercase characters and hyphens only)`);
751
+ }
752
+ _ApitallyClient.instance = this;
753
+ this.clientId = clientId;
754
+ this.env = env;
755
+ this.instanceUuid = (0, import_crypto5.randomUUID)();
756
+ this.syncDataQueue = [];
757
+ this.requestCounter = new RequestCounter();
758
+ this.requestLogger = new RequestLogger(requestLoggingConfig);
759
+ this.validationErrorCounter = new ValidationErrorCounter();
760
+ this.serverErrorCounter = new ServerErrorCounter();
761
+ this.consumerRegistry = new ConsumerRegistry();
762
+ this.logger = logger || getLogger();
763
+ this.startSync();
764
+ this.handleShutdown = this.handleShutdown.bind(this);
765
+ }
766
+ static getInstance() {
767
+ if (!_ApitallyClient.instance) {
768
+ throw new Error("Apitally client is not initialized");
769
+ }
770
+ return _ApitallyClient.instance;
771
+ }
772
+ isEnabled() {
773
+ return this.enabled;
774
+ }
775
+ static async shutdown() {
776
+ if (_ApitallyClient.instance) {
777
+ await _ApitallyClient.instance.handleShutdown();
778
+ }
779
+ }
780
+ async handleShutdown() {
781
+ this.enabled = false;
782
+ this.stopSync();
783
+ await this.sendSyncData();
784
+ await this.sendLogData();
785
+ await this.requestLogger.close();
786
+ _ApitallyClient.instance = void 0;
787
+ }
788
+ getHubUrlPrefix() {
789
+ const baseURL = process.env.APITALLY_HUB_BASE_URL || "https://hub.apitally.io";
790
+ const version = "v2";
791
+ return `${baseURL}/${version}/${this.clientId}/${this.env}/`;
792
+ }
793
+ async sendData(url, payload) {
794
+ const fetchWithRetry = (0, import_fetch_retry.default)(fetch, {
795
+ retries: 3,
796
+ retryDelay: 1e3,
797
+ retryOn: [
798
+ 408,
799
+ 429,
800
+ 500,
801
+ 502,
802
+ 503,
803
+ 504
804
+ ]
805
+ });
806
+ const response = await fetchWithRetry(this.getHubUrlPrefix() + url, {
807
+ method: "POST",
808
+ body: JSON.stringify(payload),
809
+ headers: {
810
+ "Content-Type": "application/json"
811
+ }
812
+ });
813
+ if (!response.ok) {
814
+ throw new HTTPError(response);
815
+ }
816
+ }
817
+ startSync() {
818
+ this.sync();
819
+ this.syncIntervalId = setInterval(() => {
820
+ this.sync();
821
+ }, INITIAL_SYNC_INTERVAL);
822
+ setTimeout(() => {
823
+ clearInterval(this.syncIntervalId);
824
+ this.syncIntervalId = setInterval(() => {
825
+ this.sync();
826
+ }, SYNC_INTERVAL);
827
+ }, INITIAL_SYNC_INTERVAL_DURATION);
828
+ }
829
+ async sync() {
830
+ try {
831
+ const promises = [
832
+ this.sendSyncData(),
833
+ this.sendLogData()
834
+ ];
835
+ if (!this.startupDataSent) {
836
+ promises.push(this.sendStartupData());
837
+ }
838
+ await Promise.all(promises);
839
+ } catch (error) {
840
+ this.logger.error("Error while syncing with Apitally Hub", {
841
+ error
842
+ });
843
+ }
844
+ }
845
+ stopSync() {
846
+ if (this.syncIntervalId) {
847
+ clearInterval(this.syncIntervalId);
848
+ this.syncIntervalId = void 0;
849
+ }
850
+ }
851
+ setStartupData(data) {
852
+ this.startupData = data;
853
+ this.startupDataSent = false;
854
+ this.sendStartupData();
855
+ }
856
+ async sendStartupData() {
857
+ if (this.startupData) {
858
+ this.logger.debug("Sending startup data to Apitally Hub");
859
+ const payload = {
860
+ instance_uuid: this.instanceUuid,
861
+ message_uuid: (0, import_crypto5.randomUUID)(),
862
+ ...this.startupData
863
+ };
864
+ try {
865
+ await this.sendData("startup", payload);
866
+ this.startupDataSent = true;
867
+ } catch (error) {
868
+ const handled = this.handleHubError(error);
869
+ if (!handled) {
870
+ this.logger.error(error.message);
871
+ this.logger.debug("Error while sending startup data to Apitally Hub (will retry)", {
872
+ error
873
+ });
874
+ }
875
+ }
876
+ }
877
+ }
878
+ async sendSyncData() {
879
+ this.logger.debug("Synchronizing data with Apitally Hub");
880
+ const newPayload = {
881
+ timestamp: Date.now() / 1e3,
882
+ instance_uuid: this.instanceUuid,
883
+ message_uuid: (0, import_crypto5.randomUUID)(),
884
+ requests: this.requestCounter.getAndResetRequests(),
885
+ validation_errors: this.validationErrorCounter.getAndResetValidationErrors(),
886
+ server_errors: this.serverErrorCounter.getAndResetServerErrors(),
887
+ consumers: this.consumerRegistry.getAndResetUpdatedConsumers()
888
+ };
889
+ this.syncDataQueue.push(newPayload);
890
+ let i = 0;
891
+ while (this.syncDataQueue.length > 0) {
892
+ const payload = this.syncDataQueue.shift();
893
+ if (payload) {
894
+ try {
895
+ if (Date.now() - payload.timestamp * 1e3 <= MAX_QUEUE_TIME) {
896
+ if (i > 0) {
897
+ await this.randomDelay();
898
+ }
899
+ await this.sendData("sync", payload);
900
+ i += 1;
901
+ }
902
+ } catch (error) {
903
+ const handled = this.handleHubError(error);
904
+ if (!handled) {
905
+ this.logger.debug("Error while synchronizing data with Apitally Hub (will retry)", {
906
+ error
907
+ });
908
+ this.syncDataQueue.push(payload);
909
+ break;
910
+ }
911
+ }
912
+ }
913
+ }
914
+ }
915
+ async sendLogData() {
916
+ this.logger.debug("Sending request log data to Apitally Hub");
917
+ await this.requestLogger.rotateFile();
918
+ const fetchWithRetry = (0, import_fetch_retry.default)(fetch, {
919
+ retries: 3,
920
+ retryDelay: 1e3,
921
+ retryOn: [
922
+ 408,
923
+ 429,
924
+ 500,
925
+ 502,
926
+ 503,
927
+ 504
928
+ ]
929
+ });
930
+ let i = 0;
931
+ let logFile;
932
+ while (logFile = this.requestLogger.getFile()) {
933
+ if (i > 0) {
934
+ await this.randomDelay();
935
+ }
936
+ try {
937
+ const response = await fetchWithRetry(`${this.getHubUrlPrefix()}log?uuid=${logFile.uuid}`, {
938
+ method: "POST",
939
+ body: await logFile.getContent()
940
+ });
941
+ if (response.status === 402 && response.headers.has("Retry-After")) {
942
+ const retryAfter = parseInt(response.headers.get("Retry-After") ?? "0");
943
+ if (retryAfter > 0) {
944
+ this.requestLogger.suspendUntil = Date.now() + retryAfter * 1e3;
945
+ this.requestLogger.clear();
946
+ return;
947
+ }
948
+ }
949
+ if (!response.ok) {
950
+ throw new HTTPError(response);
951
+ }
952
+ logFile.delete();
953
+ } catch (error) {
954
+ this.requestLogger.retryFileLater(logFile);
955
+ break;
956
+ }
957
+ i++;
958
+ if (i >= 10) break;
959
+ }
960
+ }
961
+ handleHubError(error) {
962
+ if (error instanceof HTTPError) {
963
+ if (error.response.status === 404) {
964
+ this.logger.error(`Invalid Apitally client ID: '${this.clientId}'`);
965
+ this.enabled = false;
966
+ this.stopSync();
967
+ return true;
968
+ }
969
+ if (error.response.status === 422) {
970
+ this.logger.error("Received validation error from Apitally Hub");
971
+ return true;
972
+ }
973
+ }
974
+ return false;
975
+ }
976
+ async randomDelay() {
977
+ const delay = 100 + Math.random() * 400;
978
+ await new Promise((resolve) => setTimeout(resolve, delay));
979
+ }
980
+ };
981
+ __name(_ApitallyClient, "ApitallyClient");
982
+ __publicField(_ApitallyClient, "instance");
983
+ var ApitallyClient = _ApitallyClient;
984
+
985
+ // src/common/packageVersions.ts
986
+ var import_module = require("module");
987
+ var import_meta = {};
988
+ function getPackageVersion(name) {
989
+ const packageJsonPath = `${name}/package.json`;
990
+ try {
991
+ return require(packageJsonPath).version || null;
992
+ } catch (error) {
993
+ try {
994
+ const _require = (0, import_module.createRequire)(import_meta.url);
995
+ return _require(packageJsonPath).version || null;
996
+ } catch (error2) {
997
+ return null;
998
+ }
999
+ }
1000
+ }
1001
+ __name(getPackageVersion, "getPackageVersion");
1002
+
1003
+ // src/adonisjs/provider.ts
1004
+ var _ApitallyProvider = class _ApitallyProvider {
1005
+ app;
1006
+ constructor(app) {
1007
+ this.app = app;
1008
+ }
1009
+ register() {
1010
+ this.app.container.singleton("apitallyClient", () => {
1011
+ const config = this.app.config.get("apitally");
1012
+ return new ApitallyClient(config);
1013
+ });
1014
+ }
1015
+ async ready() {
1016
+ const client = await this.app.container.make("apitallyClient");
1017
+ const router = await this.app.container.make("router");
1018
+ const paths = listRoutes(router);
1019
+ const versions = getVersions(this.app.config.get("apitally.appVersion"));
1020
+ const startupData = {
1021
+ paths,
1022
+ versions,
1023
+ client: "js:adonisjs"
1024
+ };
1025
+ client.setStartupData(startupData);
1026
+ }
1027
+ async shutdown() {
1028
+ const client = await this.app.container.make("apitallyClient");
1029
+ await client.handleShutdown();
1030
+ }
1031
+ };
1032
+ __name(_ApitallyProvider, "ApitallyProvider");
1033
+ var ApitallyProvider = _ApitallyProvider;
1034
+ var listRoutes = /* @__PURE__ */ __name((router) => {
1035
+ const routes = router.toJSON();
1036
+ const paths = [];
1037
+ for (const domain in routes) {
1038
+ for (const route of routes[domain]) {
1039
+ for (const method of route.methods) {
1040
+ if (![
1041
+ "HEAD",
1042
+ "OPTIONS"
1043
+ ].includes(method.toUpperCase())) {
1044
+ paths.push({
1045
+ method: method.toUpperCase(),
1046
+ path: route.pattern
1047
+ });
1048
+ }
1049
+ }
1050
+ }
1051
+ }
1052
+ return paths;
1053
+ }, "listRoutes");
1054
+ var getVersions = /* @__PURE__ */ __name((appVersion) => {
1055
+ const versions = [
1056
+ [
1057
+ "nodejs",
1058
+ process.version.replace(/^v/, "")
1059
+ ]
1060
+ ];
1061
+ const adonisJsVersion = getPackageVersion("@adonisjs/core");
1062
+ const apitallyVersion = getPackageVersion("../..");
1063
+ if (adonisJsVersion) {
1064
+ versions.push([
1065
+ "adonisjs",
1066
+ adonisJsVersion
1067
+ ]);
1068
+ }
1069
+ if (apitallyVersion) {
1070
+ versions.push([
1071
+ "apitally",
1072
+ apitallyVersion
1073
+ ]);
1074
+ }
1075
+ if (appVersion) {
1076
+ versions.push([
1077
+ "app",
1078
+ appVersion
1079
+ ]);
1080
+ }
1081
+ return Object.fromEntries(versions);
1082
+ }, "getVersions");
1083
+ //# sourceMappingURL=provider.cjs.map