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