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