apitally 0.21.2 → 0.21.4

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