apitally 0.21.3 → 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.
- package/dist/adonisjs/configure.cjs +6 -21
- package/dist/adonisjs/configure.cjs.map +1 -1
- package/dist/adonisjs/configure.js +3 -18
- package/dist/adonisjs/configure.js.map +1 -1
- package/dist/adonisjs/index.cjs +2 -70
- package/dist/adonisjs/index.cjs.map +1 -1
- package/dist/adonisjs/index.js +1 -66
- package/dist/adonisjs/index.js.map +1 -1
- package/dist/adonisjs/middleware.cjs +11 -116
- package/dist/adonisjs/middleware.cjs.map +1 -1
- package/dist/adonisjs/middleware.js +6 -101
- package/dist/adonisjs/middleware.js.map +1 -1
- package/dist/adonisjs/provider.cjs +14 -5668
- package/dist/adonisjs/provider.cjs.map +1 -1
- package/dist/adonisjs/provider.js +6 -5676
- package/dist/adonisjs/provider.js.map +1 -1
- package/dist/common/client.cjs +26 -792
- package/dist/common/client.cjs.map +1 -1
- package/dist/common/client.js +19 -785
- package/dist/common/client.js.map +1 -1
- package/dist/common/consumerRegistry.cjs +3 -5
- package/dist/common/consumerRegistry.cjs.map +1 -1
- package/dist/common/consumerRegistry.js +3 -5
- package/dist/common/consumerRegistry.js.map +1 -1
- package/dist/common/headers.cjs +0 -2
- package/dist/common/headers.cjs.map +1 -1
- package/dist/common/headers.js +0 -2
- package/dist/common/headers.js.map +1 -1
- package/dist/common/logging.cjs +0 -2
- package/dist/common/logging.cjs.map +1 -1
- package/dist/common/logging.js +0 -2
- package/dist/common/logging.js.map +1 -1
- package/dist/common/packageVersions.cjs +2 -4
- package/dist/common/packageVersions.cjs.map +1 -1
- package/dist/common/packageVersions.js +2 -10
- package/dist/common/packageVersions.js.map +1 -1
- package/dist/common/paramValidation.cjs +0 -2
- package/dist/common/paramValidation.cjs.map +1 -1
- package/dist/common/paramValidation.js +0 -2
- package/dist/common/paramValidation.js.map +1 -1
- package/dist/common/requestCounter.cjs +2 -4
- package/dist/common/requestCounter.cjs.map +1 -1
- package/dist/common/requestCounter.js +2 -4
- package/dist/common/requestCounter.js.map +1 -1
- package/dist/common/requestLogger.cjs +39 -162
- package/dist/common/requestLogger.cjs.map +1 -1
- package/dist/common/requestLogger.js +33 -156
- package/dist/common/requestLogger.js.map +1 -1
- package/dist/common/response.cjs +0 -2
- package/dist/common/response.cjs.map +1 -1
- package/dist/common/response.js +0 -2
- package/dist/common/response.js.map +1 -1
- package/dist/common/sentry.cjs +1 -3
- package/dist/common/sentry.cjs.map +1 -1
- package/dist/common/sentry.js +1 -3
- package/dist/common/sentry.js.map +1 -1
- package/dist/common/serverErrorCounter.cjs +7 -36
- package/dist/common/serverErrorCounter.cjs.map +1 -1
- package/dist/common/serverErrorCounter.js +6 -25
- package/dist/common/serverErrorCounter.js.map +1 -1
- package/dist/common/tempGzipFile.cjs +9 -11
- package/dist/common/tempGzipFile.cjs.map +1 -1
- package/dist/common/tempGzipFile.js +9 -11
- package/dist/common/tempGzipFile.js.map +1 -1
- package/dist/common/types.cjs +0 -2
- package/dist/common/types.cjs.map +1 -1
- package/dist/common/validationErrorCounter.cjs +3 -5
- package/dist/common/validationErrorCounter.cjs.map +1 -1
- package/dist/common/validationErrorCounter.js +3 -5
- package/dist/common/validationErrorCounter.js.map +1 -1
- package/dist/elysia/index.cjs +2 -1573
- package/dist/elysia/index.cjs.map +1 -1
- package/dist/elysia/index.js +2 -1577
- package/dist/elysia/index.js.map +1 -1
- package/dist/elysia/plugin.cjs +26 -1432
- package/dist/elysia/plugin.cjs.map +1 -1
- package/dist/elysia/plugin.js +15 -1416
- package/dist/elysia/plugin.js.map +1 -1
- package/dist/elysia/utils.cjs +3 -24
- package/dist/elysia/utils.cjs.map +1 -1
- package/dist/elysia/utils.js +1 -25
- package/dist/elysia/utils.js.map +1 -1
- package/dist/express/index.cjs +3 -6354
- package/dist/express/index.cjs.map +1 -1
- package/dist/express/index.js +1 -6367
- package/dist/express/index.js.map +1 -1
- package/dist/express/middleware.cjs +38 -6070
- package/dist/express/middleware.cjs.map +1 -1
- package/dist/express/middleware.js +13 -6061
- package/dist/express/middleware.js.map +1 -1
- package/dist/express/utils.cjs +17 -19
- package/dist/express/utils.cjs.map +1 -1
- package/dist/express/utils.js +17 -19
- package/dist/express/utils.js.map +1 -1
- package/dist/fastify/index.cjs +3 -6124
- package/dist/fastify/index.cjs.map +1 -1
- package/dist/fastify/index.js +2 -6148
- package/dist/fastify/index.js.map +1 -1
- package/dist/fastify/plugin.cjs +35 -5889
- package/dist/fastify/plugin.cjs.map +1 -1
- package/dist/fastify/plugin.js +13 -5893
- package/dist/fastify/plugin.js.map +1 -1
- package/dist/h3/index.cjs +3 -1545
- package/dist/h3/index.cjs.map +1 -1
- package/dist/h3/index.js +1 -1537
- package/dist/h3/index.js.map +1 -1
- package/dist/h3/plugin.cjs +27 -1423
- package/dist/h3/plugin.cjs.map +1 -1
- package/dist/h3/plugin.js +15 -1406
- package/dist/h3/plugin.js.map +1 -1
- package/dist/h3/utils.cjs +3 -24
- package/dist/h3/utils.cjs.map +1 -1
- package/dist/h3/utils.js +1 -25
- package/dist/h3/utils.js.map +1 -1
- package/dist/hapi/index.cjs +3 -5988
- package/dist/hapi/index.cjs.map +1 -1
- package/dist/hapi/index.js +2 -6012
- package/dist/hapi/index.js.map +1 -1
- package/dist/hapi/plugin.cjs +27 -5847
- package/dist/hapi/plugin.cjs.map +1 -1
- package/dist/hapi/plugin.js +15 -5851
- package/dist/hapi/plugin.js.map +1 -1
- package/dist/hapi/utils.cjs +3 -24
- package/dist/hapi/utils.cjs.map +1 -1
- package/dist/hapi/utils.js +1 -25
- package/dist/hapi/utils.js.map +1 -1
- package/dist/hono/index.cjs +3 -1571
- package/dist/hono/index.cjs.map +1 -1
- package/dist/hono/index.js +1 -1563
- package/dist/hono/index.js.map +1 -1
- package/dist/hono/middleware.cjs +21 -1460
- package/dist/hono/middleware.cjs.map +1 -1
- package/dist/hono/middleware.js +9 -1443
- package/dist/hono/middleware.js.map +1 -1
- package/dist/hono/utils.cjs +3 -24
- package/dist/hono/utils.cjs.map +1 -1
- package/dist/hono/utils.js +1 -27
- package/dist/hono/utils.js.map +1 -1
- package/dist/koa/index.cjs +3 -1484
- package/dist/koa/index.cjs.map +1 -1
- package/dist/koa/index.js +1 -1476
- package/dist/koa/index.js.map +1 -1
- package/dist/koa/middleware.cjs +19 -1313
- package/dist/koa/middleware.cjs.map +1 -1
- package/dist/koa/middleware.js +8 -1297
- package/dist/koa/middleware.js.map +1 -1
- package/dist/loggers/console.cjs +4 -6
- package/dist/loggers/console.cjs.map +1 -1
- package/dist/loggers/console.js +4 -6
- package/dist/loggers/console.js.map +1 -1
- package/dist/loggers/hapi.cjs +3 -5
- package/dist/loggers/hapi.cjs.map +1 -1
- package/dist/loggers/hapi.js +3 -5
- package/dist/loggers/hapi.js.map +1 -1
- package/dist/loggers/index.cjs +10 -4732
- package/dist/loggers/index.cjs.map +1 -1
- package/dist/loggers/index.js +5 -4743
- package/dist/loggers/index.js.map +1 -1
- package/dist/loggers/nestjs.cjs +5 -39
- package/dist/loggers/nestjs.cjs.map +1 -1
- package/dist/loggers/nestjs.js +4 -36
- package/dist/loggers/nestjs.js.map +1 -1
- package/dist/loggers/pino.cjs +29 -4448
- package/dist/loggers/pino.cjs.map +1 -1
- package/dist/loggers/pino.js +7 -4451
- package/dist/loggers/pino.js.map +1 -1
- package/dist/loggers/utils.cjs +1 -3
- package/dist/loggers/utils.cjs.map +1 -1
- package/dist/loggers/utils.js +1 -3
- package/dist/loggers/utils.js.map +1 -1
- package/dist/loggers/winston.cjs +6 -44
- package/dist/loggers/winston.cjs.map +1 -1
- package/dist/loggers/winston.js +4 -40
- package/dist/loggers/winston.js.map +1 -1
- package/dist/nestjs/index.cjs +17 -17786
- package/dist/nestjs/index.cjs.map +1 -1
- package/dist/nestjs/index.js +20 -17814
- package/dist/nestjs/index.js.map +1 -1
- 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,1552 +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
|
-
this.logger = logger ?? getLogger();
|
|
893
|
-
if (!isValidClientId(clientId)) {
|
|
894
|
-
this.logger.error(`Invalid Apitally client ID '${clientId}' (expecting hexadecimal UUID format)`);
|
|
895
|
-
this.enabled = false;
|
|
896
|
-
}
|
|
897
|
-
if (!isValidEnv(env)) {
|
|
898
|
-
this.logger.error(`Invalid Apitally env '${env}' (expecting 1-32 alphanumeric characters and hyphens only)`);
|
|
899
|
-
this.enabled = false;
|
|
900
|
-
}
|
|
901
|
-
if (requestLoggingConfig && !requestLogging) {
|
|
902
|
-
console.warn("requestLoggingConfig is deprecated, use requestLogging instead.");
|
|
903
|
-
}
|
|
904
|
-
_ApitallyClient.instance = this;
|
|
905
|
-
this.clientId = clientId;
|
|
906
|
-
this.env = env;
|
|
907
|
-
this.instanceUuid = (0, import_node_crypto5.randomUUID)();
|
|
908
|
-
this.syncDataQueue = [];
|
|
909
|
-
this.requestCounter = new RequestCounter();
|
|
910
|
-
this.requestLogger = new RequestLogger(requestLogging ?? requestLoggingConfig);
|
|
911
|
-
this.validationErrorCounter = new ValidationErrorCounter();
|
|
912
|
-
this.serverErrorCounter = new ServerErrorCounter();
|
|
913
|
-
this.consumerRegistry = new ConsumerRegistry();
|
|
914
|
-
this.handleShutdown = this.handleShutdown.bind(this);
|
|
915
|
-
}
|
|
916
|
-
static getInstance() {
|
|
917
|
-
if (!_ApitallyClient.instance) {
|
|
918
|
-
throw new Error("Apitally client is not initialized");
|
|
919
|
-
}
|
|
920
|
-
return _ApitallyClient.instance;
|
|
921
|
-
}
|
|
922
|
-
isEnabled() {
|
|
923
|
-
return this.enabled;
|
|
924
|
-
}
|
|
925
|
-
static async shutdown() {
|
|
926
|
-
if (_ApitallyClient.instance) {
|
|
927
|
-
await _ApitallyClient.instance.handleShutdown();
|
|
928
|
-
}
|
|
929
|
-
}
|
|
930
|
-
async handleShutdown() {
|
|
931
|
-
this.enabled = false;
|
|
932
|
-
this.stopSync();
|
|
933
|
-
await this.sendSyncData();
|
|
934
|
-
await this.sendLogData();
|
|
935
|
-
await this.requestLogger.close();
|
|
936
|
-
_ApitallyClient.instance = void 0;
|
|
937
|
-
}
|
|
938
|
-
getHubUrlPrefix() {
|
|
939
|
-
const baseURL = process.env.APITALLY_HUB_BASE_URL || "https://hub.apitally.io";
|
|
940
|
-
const version = "v2";
|
|
941
|
-
return `${baseURL}/${version}/${this.clientId}/${this.env}/`;
|
|
942
|
-
}
|
|
943
|
-
async sendData(url, payload) {
|
|
944
|
-
const fetchWithRetry = (0, import_fetch_retry.default)(fetch, {
|
|
945
|
-
retries: 3,
|
|
946
|
-
retryDelay: 1e3,
|
|
947
|
-
retryOn: [
|
|
948
|
-
408,
|
|
949
|
-
429,
|
|
950
|
-
500,
|
|
951
|
-
502,
|
|
952
|
-
503,
|
|
953
|
-
504
|
|
954
|
-
]
|
|
955
|
-
});
|
|
956
|
-
const response = await fetchWithRetry(this.getHubUrlPrefix() + url, {
|
|
957
|
-
method: "POST",
|
|
958
|
-
body: JSON.stringify(payload),
|
|
959
|
-
headers: {
|
|
960
|
-
"Content-Type": "application/json"
|
|
961
|
-
}
|
|
962
|
-
});
|
|
963
|
-
if (!response.ok) {
|
|
964
|
-
throw new HTTPError(response);
|
|
965
|
-
}
|
|
966
|
-
}
|
|
967
|
-
startSync() {
|
|
968
|
-
if (!this.enabled) {
|
|
969
|
-
return;
|
|
970
|
-
}
|
|
971
|
-
this.sync();
|
|
972
|
-
this.syncIntervalId = setInterval(() => {
|
|
973
|
-
this.sync();
|
|
974
|
-
}, INITIAL_SYNC_INTERVAL);
|
|
975
|
-
setTimeout(() => {
|
|
976
|
-
if (this.syncIntervalId) {
|
|
977
|
-
clearInterval(this.syncIntervalId);
|
|
978
|
-
this.syncIntervalId = setInterval(() => {
|
|
979
|
-
this.sync();
|
|
980
|
-
}, SYNC_INTERVAL);
|
|
981
|
-
}
|
|
982
|
-
}, INITIAL_SYNC_INTERVAL_DURATION);
|
|
983
|
-
}
|
|
984
|
-
async sync() {
|
|
985
|
-
try {
|
|
986
|
-
const promises = [
|
|
987
|
-
this.sendSyncData(),
|
|
988
|
-
this.sendLogData()
|
|
989
|
-
];
|
|
990
|
-
if (!this.startupDataSent) {
|
|
991
|
-
promises.push(this.sendStartupData());
|
|
992
|
-
}
|
|
993
|
-
await Promise.all(promises);
|
|
994
|
-
} catch (error) {
|
|
995
|
-
this.logger.error("Error while syncing with Apitally Hub", {
|
|
996
|
-
error
|
|
997
|
-
});
|
|
998
|
-
}
|
|
999
|
-
}
|
|
1000
|
-
stopSync() {
|
|
1001
|
-
if (this.syncIntervalId) {
|
|
1002
|
-
clearInterval(this.syncIntervalId);
|
|
1003
|
-
this.syncIntervalId = void 0;
|
|
1004
|
-
}
|
|
1005
|
-
}
|
|
1006
|
-
setStartupData(data) {
|
|
1007
|
-
this.startupData = data;
|
|
1008
|
-
this.startupDataSent = false;
|
|
1009
|
-
}
|
|
1010
|
-
async sendStartupData() {
|
|
1011
|
-
if (this.startupData) {
|
|
1012
|
-
this.logger.debug("Sending startup data to Apitally Hub");
|
|
1013
|
-
const payload = {
|
|
1014
|
-
instance_uuid: this.instanceUuid,
|
|
1015
|
-
message_uuid: (0, import_node_crypto5.randomUUID)(),
|
|
1016
|
-
...this.startupData
|
|
1017
|
-
};
|
|
1018
|
-
try {
|
|
1019
|
-
await this.sendData("startup", payload);
|
|
1020
|
-
this.startupDataSent = true;
|
|
1021
|
-
} catch (error) {
|
|
1022
|
-
const handled = this.handleHubError(error);
|
|
1023
|
-
if (!handled) {
|
|
1024
|
-
this.logger.error(error.message);
|
|
1025
|
-
this.logger.debug("Error while sending startup data to Apitally Hub (will retry)", {
|
|
1026
|
-
error
|
|
1027
|
-
});
|
|
1028
|
-
}
|
|
1029
|
-
}
|
|
1030
|
-
}
|
|
1031
|
-
}
|
|
1032
|
-
async sendSyncData() {
|
|
1033
|
-
this.logger.debug("Synchronizing data with Apitally Hub");
|
|
1034
|
-
const newPayload = {
|
|
1035
|
-
timestamp: Date.now() / 1e3,
|
|
1036
|
-
instance_uuid: this.instanceUuid,
|
|
1037
|
-
message_uuid: (0, import_node_crypto5.randomUUID)(),
|
|
1038
|
-
requests: this.requestCounter.getAndResetRequests(),
|
|
1039
|
-
validation_errors: this.validationErrorCounter.getAndResetValidationErrors(),
|
|
1040
|
-
server_errors: this.serverErrorCounter.getAndResetServerErrors(),
|
|
1041
|
-
consumers: this.consumerRegistry.getAndResetUpdatedConsumers()
|
|
1042
|
-
};
|
|
1043
|
-
this.syncDataQueue.push(newPayload);
|
|
1044
|
-
let i = 0;
|
|
1045
|
-
while (this.syncDataQueue.length > 0) {
|
|
1046
|
-
const payload = this.syncDataQueue.shift();
|
|
1047
|
-
if (payload) {
|
|
1048
|
-
try {
|
|
1049
|
-
if (Date.now() - payload.timestamp * 1e3 <= MAX_QUEUE_TIME) {
|
|
1050
|
-
if (i > 0) {
|
|
1051
|
-
await this.randomDelay();
|
|
1052
|
-
}
|
|
1053
|
-
await this.sendData("sync", payload);
|
|
1054
|
-
i += 1;
|
|
1055
|
-
}
|
|
1056
|
-
} catch (error) {
|
|
1057
|
-
const handled = this.handleHubError(error);
|
|
1058
|
-
if (!handled) {
|
|
1059
|
-
this.logger.debug("Error while synchronizing data with Apitally Hub (will retry)", {
|
|
1060
|
-
error
|
|
1061
|
-
});
|
|
1062
|
-
this.syncDataQueue.push(payload);
|
|
1063
|
-
break;
|
|
1064
|
-
}
|
|
1065
|
-
}
|
|
1066
|
-
}
|
|
1067
|
-
}
|
|
1068
|
-
}
|
|
1069
|
-
async sendLogData() {
|
|
1070
|
-
this.logger.debug("Sending request log data to Apitally Hub");
|
|
1071
|
-
await this.requestLogger.rotateFile();
|
|
1072
|
-
const fetchWithRetry = (0, import_fetch_retry.default)(fetch, {
|
|
1073
|
-
retries: 3,
|
|
1074
|
-
retryDelay: 1e3,
|
|
1075
|
-
retryOn: [
|
|
1076
|
-
408,
|
|
1077
|
-
429,
|
|
1078
|
-
500,
|
|
1079
|
-
502,
|
|
1080
|
-
503,
|
|
1081
|
-
504
|
|
1082
|
-
]
|
|
1083
|
-
});
|
|
1084
|
-
let i = 0;
|
|
1085
|
-
let logFile;
|
|
1086
|
-
while (logFile = this.requestLogger.getFile()) {
|
|
1087
|
-
if (i > 0) {
|
|
1088
|
-
await this.randomDelay();
|
|
1089
|
-
}
|
|
1090
|
-
try {
|
|
1091
|
-
const response = await fetchWithRetry(`${this.getHubUrlPrefix()}log?uuid=${logFile.uuid}`, {
|
|
1092
|
-
method: "POST",
|
|
1093
|
-
body: await logFile.getContent()
|
|
1094
|
-
});
|
|
1095
|
-
if (response.status === 402 && response.headers.has("Retry-After")) {
|
|
1096
|
-
const retryAfter = parseInt(response.headers.get("Retry-After") ?? "0");
|
|
1097
|
-
if (retryAfter > 0) {
|
|
1098
|
-
this.requestLogger.suspendUntil = Date.now() + retryAfter * 1e3;
|
|
1099
|
-
this.requestLogger.clear();
|
|
1100
|
-
return;
|
|
1101
|
-
}
|
|
1102
|
-
}
|
|
1103
|
-
if (!response.ok) {
|
|
1104
|
-
throw new HTTPError(response);
|
|
1105
|
-
}
|
|
1106
|
-
logFile.delete();
|
|
1107
|
-
} catch (error) {
|
|
1108
|
-
this.requestLogger.retryFileLater(logFile);
|
|
1109
|
-
break;
|
|
1110
|
-
}
|
|
1111
|
-
i++;
|
|
1112
|
-
if (i >= 10) break;
|
|
1113
|
-
}
|
|
1114
|
-
}
|
|
1115
|
-
handleHubError(error) {
|
|
1116
|
-
if (error instanceof HTTPError) {
|
|
1117
|
-
if (error.response.status === 404) {
|
|
1118
|
-
this.logger.error(`Invalid Apitally client ID: '${this.clientId}'`);
|
|
1119
|
-
this.enabled = false;
|
|
1120
|
-
this.stopSync();
|
|
1121
|
-
return true;
|
|
1122
|
-
}
|
|
1123
|
-
if (error.response.status === 422) {
|
|
1124
|
-
this.logger.error("Received validation error from Apitally Hub");
|
|
1125
|
-
return true;
|
|
1126
|
-
}
|
|
1127
|
-
}
|
|
1128
|
-
return false;
|
|
1129
|
-
}
|
|
1130
|
-
async randomDelay() {
|
|
1131
|
-
const delay = 100 + Math.random() * 400;
|
|
1132
|
-
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
1133
|
-
}
|
|
1134
|
-
};
|
|
1135
|
-
__name(_ApitallyClient, "ApitallyClient");
|
|
1136
|
-
__publicField(_ApitallyClient, "instance");
|
|
1137
|
-
var ApitallyClient = _ApitallyClient;
|
|
1138
|
-
|
|
1139
|
-
// src/common/headers.ts
|
|
1140
|
-
function parseContentLength(contentLength) {
|
|
1141
|
-
if (contentLength === void 0 || contentLength === null) {
|
|
1142
|
-
return void 0;
|
|
1143
|
-
}
|
|
1144
|
-
if (typeof contentLength === "number") {
|
|
1145
|
-
return contentLength;
|
|
1146
|
-
}
|
|
1147
|
-
if (typeof contentLength === "string") {
|
|
1148
|
-
const parsed = parseInt(contentLength);
|
|
1149
|
-
return isNaN(parsed) ? void 0 : parsed;
|
|
1150
|
-
}
|
|
1151
|
-
if (Array.isArray(contentLength)) {
|
|
1152
|
-
return parseContentLength(contentLength[0]);
|
|
1153
|
-
}
|
|
1154
|
-
return void 0;
|
|
1155
|
-
}
|
|
1156
|
-
__name(parseContentLength, "parseContentLength");
|
|
1157
|
-
function mergeHeaders(base, merge) {
|
|
1158
|
-
const mergedHeaders = new Headers(base);
|
|
1159
|
-
for (const [name, value] of merge) if (name === "set-cookie") mergedHeaders.append(name, value);
|
|
1160
|
-
else mergedHeaders.set(name, value);
|
|
1161
|
-
return mergedHeaders;
|
|
1162
|
-
}
|
|
1163
|
-
__name(mergeHeaders, "mergeHeaders");
|
|
1164
|
-
|
|
1165
|
-
// src/common/response.ts
|
|
1166
|
-
async function measureResponseSize(response, tee = true) {
|
|
1167
|
-
const [newResponse1, newResponse2] = tee ? teeResponse(response) : [
|
|
1168
|
-
response,
|
|
1169
|
-
response
|
|
1170
|
-
];
|
|
1171
|
-
let size = 0;
|
|
1172
|
-
if (newResponse2.body) {
|
|
1173
|
-
let done = false;
|
|
1174
|
-
const reader = newResponse2.body.getReader();
|
|
1175
|
-
while (!done) {
|
|
1176
|
-
const result = await reader.read();
|
|
1177
|
-
done = result.done;
|
|
1178
|
-
if (!done && result.value) {
|
|
1179
|
-
size += result.value.byteLength;
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
|
-
}
|
|
1183
|
-
return [
|
|
1184
|
-
size,
|
|
1185
|
-
newResponse1
|
|
1186
|
-
];
|
|
1187
|
-
}
|
|
1188
|
-
__name(measureResponseSize, "measureResponseSize");
|
|
1189
|
-
async function getResponseBody(response, tee = true) {
|
|
1190
|
-
const [newResponse1, newResponse2] = tee ? teeResponse(response) : [
|
|
1191
|
-
response,
|
|
1192
|
-
response
|
|
1193
|
-
];
|
|
1194
|
-
const responseBuffer = Buffer.from(await newResponse2.arrayBuffer());
|
|
1195
|
-
return [
|
|
1196
|
-
responseBuffer,
|
|
1197
|
-
newResponse1
|
|
1198
|
-
];
|
|
1199
|
-
}
|
|
1200
|
-
__name(getResponseBody, "getResponseBody");
|
|
1201
|
-
function teeResponse(response) {
|
|
1202
|
-
if (!response.body) {
|
|
1203
|
-
return [
|
|
1204
|
-
response,
|
|
1205
|
-
response
|
|
1206
|
-
];
|
|
1207
|
-
}
|
|
1208
|
-
const [stream1, stream2] = response.body.tee();
|
|
1209
|
-
const newResponse1 = new Response(stream1, {
|
|
1210
|
-
status: response.status,
|
|
1211
|
-
statusText: response.statusText,
|
|
1212
|
-
headers: response.headers
|
|
1213
|
-
});
|
|
1214
|
-
const newResponse2 = new Response(stream2, {
|
|
1215
|
-
status: response.status,
|
|
1216
|
-
statusText: response.statusText,
|
|
1217
|
-
headers: response.headers
|
|
1218
|
-
});
|
|
1219
|
-
return [
|
|
1220
|
-
newResponse1,
|
|
1221
|
-
newResponse2
|
|
1222
|
-
];
|
|
1223
|
-
}
|
|
1224
|
-
__name(teeResponse, "teeResponse");
|
|
1225
|
-
|
|
1226
|
-
// src/loggers/console.ts
|
|
1227
|
-
var import_node_util = require("util");
|
|
1228
|
-
var MAX_BUFFER_SIZE = 1e3;
|
|
1229
|
-
var isPatched = false;
|
|
1230
|
-
var globalLogsContext;
|
|
1231
|
-
function patchConsole(logsContext) {
|
|
1232
|
-
globalLogsContext = logsContext;
|
|
1233
|
-
if (isPatched) {
|
|
1234
|
-
return;
|
|
1235
|
-
}
|
|
1236
|
-
const logMethods = [
|
|
1237
|
-
"log",
|
|
1238
|
-
"warn",
|
|
1239
|
-
"error",
|
|
1240
|
-
"info",
|
|
1241
|
-
"debug"
|
|
1242
|
-
];
|
|
1243
|
-
logMethods.forEach((method) => {
|
|
1244
|
-
const originalMethod = console[method];
|
|
1245
|
-
console[method] = function(...args) {
|
|
1246
|
-
captureLog(method, args);
|
|
1247
|
-
return originalMethod.apply(console, args);
|
|
1248
|
-
};
|
|
1249
|
-
});
|
|
1250
|
-
isPatched = true;
|
|
1251
|
-
}
|
|
1252
|
-
__name(patchConsole, "patchConsole");
|
|
1253
|
-
function captureLog(level, args) {
|
|
1254
|
-
const logs = globalLogsContext == null ? void 0 : globalLogsContext.getStore();
|
|
1255
|
-
if (logs && logs.length < MAX_BUFFER_SIZE) {
|
|
1256
|
-
logs.push({
|
|
1257
|
-
timestamp: Date.now() / 1e3,
|
|
1258
|
-
logger: "console",
|
|
1259
|
-
level,
|
|
1260
|
-
message: (0, import_node_util.format)(...args)
|
|
1261
|
-
});
|
|
1262
|
-
}
|
|
1263
|
-
}
|
|
1264
|
-
__name(captureLog, "captureLog");
|
|
1265
|
-
|
|
1266
|
-
// src/loggers/hapi.ts
|
|
1267
|
-
var import_node_util2 = require("util");
|
|
1268
|
-
|
|
1269
|
-
// src/loggers/utils.ts
|
|
1270
|
-
var import_node_util3 = require("util");
|
|
1271
|
-
function formatMessage(message, ...args) {
|
|
1272
|
-
return [
|
|
1273
|
-
message,
|
|
1274
|
-
...args
|
|
1275
|
-
].map(formatArg).filter((arg) => arg !== "").join("\n");
|
|
1276
|
-
}
|
|
1277
|
-
__name(formatMessage, "formatMessage");
|
|
1278
|
-
function removeKeys(obj, keys) {
|
|
1279
|
-
return Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key)));
|
|
1280
|
-
}
|
|
1281
|
-
__name(removeKeys, "removeKeys");
|
|
1282
|
-
function formatArg(arg) {
|
|
1283
|
-
if (typeof arg === "string") {
|
|
1284
|
-
return arg.trim();
|
|
1285
|
-
}
|
|
1286
|
-
if (arg instanceof Error) {
|
|
1287
|
-
return (0, import_node_util3.format)(arg).trim();
|
|
1288
|
-
}
|
|
1289
|
-
if (arg === void 0 || arg === null || isEmptyObject(arg)) {
|
|
1290
|
-
return "";
|
|
1291
|
-
}
|
|
1292
|
-
try {
|
|
1293
|
-
return JSON.stringify(arg);
|
|
1294
|
-
} catch {
|
|
1295
|
-
return (0, import_node_util3.format)(arg).trim();
|
|
1296
|
-
}
|
|
1297
|
-
}
|
|
1298
|
-
__name(formatArg, "formatArg");
|
|
1299
|
-
function isEmptyObject(obj) {
|
|
1300
|
-
return obj !== null && typeof obj === "object" && Object.getPrototypeOf(obj) === Object.prototype && Object.keys(obj).length === 0;
|
|
1301
|
-
}
|
|
1302
|
-
__name(isEmptyObject, "isEmptyObject");
|
|
1303
|
-
|
|
1304
|
-
// src/loggers/pino.ts
|
|
1305
|
-
var originalStreamSym = Symbol.for("apitally.originalStream");
|
|
1306
|
-
|
|
1307
|
-
// src/loggers/winston.ts
|
|
1308
|
-
var MAX_BUFFER_SIZE2 = 1e3;
|
|
1309
|
-
var isPatched2 = false;
|
|
1310
|
-
var globalLogsContext2;
|
|
1311
|
-
async function patchWinston(logsContext) {
|
|
1312
|
-
var _a2, _b;
|
|
1313
|
-
globalLogsContext2 = logsContext;
|
|
1314
|
-
if (isPatched2) {
|
|
1315
|
-
return;
|
|
1316
|
-
}
|
|
1317
|
-
try {
|
|
1318
|
-
const loggerModule = await import("winston/lib/winston/logger.js");
|
|
1319
|
-
if ((_b = (_a2 = loggerModule.default) == null ? void 0 : _a2.prototype) == null ? void 0 : _b.write) {
|
|
1320
|
-
const originalWrite = loggerModule.default.prototype.write;
|
|
1321
|
-
loggerModule.default.prototype.write = function(info) {
|
|
1322
|
-
captureLog2(info);
|
|
1323
|
-
return originalWrite.call(this, info);
|
|
1324
|
-
};
|
|
1325
|
-
}
|
|
1326
|
-
} catch {
|
|
1327
|
-
}
|
|
1328
|
-
isPatched2 = true;
|
|
1329
|
-
}
|
|
1330
|
-
__name(patchWinston, "patchWinston");
|
|
1331
|
-
function captureLog2(info) {
|
|
1332
|
-
const logs = globalLogsContext2 == null ? void 0 : globalLogsContext2.getStore();
|
|
1333
|
-
if (!logs || !info || logs.length >= MAX_BUFFER_SIZE2) {
|
|
1334
|
-
return;
|
|
1335
|
-
}
|
|
1336
|
-
try {
|
|
1337
|
-
const rest = removeKeys(info, [
|
|
1338
|
-
"timestamp",
|
|
1339
|
-
"level",
|
|
1340
|
-
"message",
|
|
1341
|
-
"splat"
|
|
1342
|
-
]);
|
|
1343
|
-
const formattedMessage = formatMessage(info.message, rest);
|
|
1344
|
-
if (formattedMessage) {
|
|
1345
|
-
logs.push({
|
|
1346
|
-
timestamp: parseTimestamp(info.timestamp),
|
|
1347
|
-
level: info.level || "info",
|
|
1348
|
-
message: formattedMessage.trim()
|
|
1349
|
-
});
|
|
1350
|
-
}
|
|
1351
|
-
} catch (e) {
|
|
1352
|
-
}
|
|
1353
|
-
}
|
|
1354
|
-
__name(captureLog2, "captureLog");
|
|
1355
|
-
function parseTimestamp(timestamp) {
|
|
1356
|
-
if (timestamp) {
|
|
1357
|
-
const ts = new Date(timestamp).getTime();
|
|
1358
|
-
if (!isNaN(ts)) {
|
|
1359
|
-
return ts / 1e3;
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1362
|
-
return Date.now() / 1e3;
|
|
1363
|
-
}
|
|
1364
|
-
__name(parseTimestamp, "parseTimestamp");
|
|
1365
|
-
|
|
1366
|
-
// src/common/packageVersions.ts
|
|
1367
|
-
var import_node_module = require("module");
|
|
1368
|
-
var import_meta = {};
|
|
1369
|
-
function getPackageVersion(name) {
|
|
1370
|
-
const packageJsonPath = `${name}/package.json`;
|
|
1371
|
-
try {
|
|
1372
|
-
return require(packageJsonPath).version || null;
|
|
1373
|
-
} catch (error) {
|
|
1374
|
-
try {
|
|
1375
|
-
const _require = (0, import_node_module.createRequire)(import_meta.url);
|
|
1376
|
-
return _require(packageJsonPath).version || null;
|
|
1377
|
-
} catch (error2) {
|
|
1378
|
-
return null;
|
|
1379
|
-
}
|
|
1380
|
-
}
|
|
1381
|
-
}
|
|
1382
|
-
__name(getPackageVersion, "getPackageVersion");
|
|
1383
|
-
|
|
1384
|
-
// src/h3/utils.ts
|
|
1385
|
-
function getAppInfo(h3, appVersion) {
|
|
1386
|
-
const versions = [];
|
|
1387
|
-
if (process.versions.node) {
|
|
1388
|
-
versions.push([
|
|
1389
|
-
"nodejs",
|
|
1390
|
-
process.versions.node
|
|
1391
|
-
]);
|
|
1392
|
-
}
|
|
1393
|
-
if (process.versions.bun) {
|
|
1394
|
-
versions.push([
|
|
1395
|
-
"bun",
|
|
1396
|
-
process.versions.bun
|
|
1397
|
-
]);
|
|
1398
|
-
}
|
|
1399
|
-
const h3Version = getPackageVersion("h3");
|
|
1400
|
-
const apitallyVersion = getPackageVersion("../..");
|
|
1401
|
-
if (h3Version) {
|
|
1402
|
-
versions.push([
|
|
1403
|
-
"h3",
|
|
1404
|
-
h3Version
|
|
1405
|
-
]);
|
|
1406
|
-
}
|
|
1407
|
-
if (apitallyVersion) {
|
|
1408
|
-
versions.push([
|
|
1409
|
-
"apitally",
|
|
1410
|
-
apitallyVersion
|
|
1411
|
-
]);
|
|
1412
|
-
}
|
|
1413
|
-
if (appVersion) {
|
|
1414
|
-
versions.push([
|
|
1415
|
-
"app",
|
|
1416
|
-
appVersion
|
|
1417
|
-
]);
|
|
1418
|
-
}
|
|
1419
|
-
return {
|
|
1420
|
-
paths: h3._routes.map((route) => ({
|
|
1421
|
-
method: route.method || "",
|
|
1422
|
-
path: route.route || ""
|
|
1423
|
-
})).filter((route) => route.method && route.path && ![
|
|
1424
|
-
"HEAD",
|
|
1425
|
-
"OPTIONS"
|
|
1426
|
-
].includes(route.method.toUpperCase())),
|
|
1427
|
-
versions: Object.fromEntries(versions),
|
|
1428
|
-
client: "js:h3"
|
|
1429
|
-
};
|
|
1430
|
-
}
|
|
1431
|
-
__name(getAppInfo, "getAppInfo");
|
|
1432
|
-
|
|
1433
|
-
// src/h3/plugin.ts
|
|
1434
|
-
var REQUEST_TIMESTAMP_SYMBOL = Symbol("apitally.requestTimestamp");
|
|
1435
|
-
var REQUEST_BODY_SYMBOL = Symbol("apitally.requestBody");
|
|
1436
|
-
var jsonHeaders = new Headers({
|
|
1437
|
-
"content-type": "application/json;charset=UTF-8"
|
|
1438
|
-
});
|
|
1439
|
-
var apitallyPlugin = (0, import_h3.definePlugin)((app, config) => {
|
|
1440
|
-
const client = new ApitallyClient(config);
|
|
1441
|
-
const logsContext = new import_node_async_hooks.AsyncLocalStorage();
|
|
1442
|
-
const setStartupData = /* @__PURE__ */ __name((attempt = 1) => {
|
|
1443
|
-
const appInfo = getAppInfo(app, config.appVersion);
|
|
1444
|
-
if (appInfo.paths.length > 0 || attempt >= 10) {
|
|
1445
|
-
client.setStartupData(appInfo);
|
|
1446
|
-
client.startSync();
|
|
1447
|
-
} else {
|
|
1448
|
-
setTimeout(() => setStartupData(attempt + 1), 500);
|
|
1449
|
-
}
|
|
1450
|
-
}, "setStartupData");
|
|
1451
|
-
setTimeout(() => setStartupData(), 500);
|
|
1452
|
-
if (client.requestLogger.config.captureLogs) {
|
|
1453
|
-
patchConsole(logsContext);
|
|
1454
|
-
patchWinston(logsContext);
|
|
1455
|
-
}
|
|
1456
|
-
const handleResponse = /* @__PURE__ */ __name(async (event, response, error) => {
|
|
1457
|
-
var _a2, _b;
|
|
1458
|
-
if (event.req.method.toUpperCase() === "OPTIONS") {
|
|
1459
|
-
return response;
|
|
1460
|
-
}
|
|
1461
|
-
const startTime = event.context[REQUEST_TIMESTAMP_SYMBOL];
|
|
1462
|
-
const responseTime = startTime ? import_node_perf_hooks.performance.now() - startTime : 0;
|
|
1463
|
-
const path = (_a2 = event.context.matchedRoute) == null ? void 0 : _a2.route;
|
|
1464
|
-
const statusCode = (response == null ? void 0 : response.status) || (error == null ? void 0 : error.status) || 500;
|
|
1465
|
-
const requestSize = parseContentLength(event.req.headers.get("content-length"));
|
|
1466
|
-
let responseSize = 0;
|
|
1467
|
-
let newResponse = response;
|
|
1468
|
-
if (response) {
|
|
1469
|
-
[responseSize, newResponse] = await measureResponseSize(response);
|
|
1470
|
-
}
|
|
1471
|
-
const consumer = getConsumer(event);
|
|
1472
|
-
client.consumerRegistry.addOrUpdateConsumer(consumer);
|
|
1473
|
-
if (path) {
|
|
1474
|
-
client.requestCounter.addRequest({
|
|
1475
|
-
consumer: consumer == null ? void 0 : consumer.identifier,
|
|
1476
|
-
method: event.req.method,
|
|
1477
|
-
path,
|
|
1478
|
-
statusCode,
|
|
1479
|
-
responseTime,
|
|
1480
|
-
requestSize,
|
|
1481
|
-
responseSize
|
|
1482
|
-
});
|
|
1483
|
-
if ((error == null ? void 0 : error.status) === 400 && error.data.name === "ZodError") {
|
|
1484
|
-
const zodError = error.data;
|
|
1485
|
-
(_b = zodError.issues) == null ? void 0 : _b.forEach((issue) => {
|
|
1486
|
-
client.validationErrorCounter.addValidationError({
|
|
1487
|
-
consumer: consumer == null ? void 0 : consumer.identifier,
|
|
1488
|
-
method: event.req.method,
|
|
1489
|
-
path,
|
|
1490
|
-
loc: issue.path.join("."),
|
|
1491
|
-
msg: issue.message,
|
|
1492
|
-
type: issue.code
|
|
1493
|
-
});
|
|
1494
|
-
});
|
|
1495
|
-
}
|
|
1496
|
-
if ((error == null ? void 0 : error.status) === 500 && error.cause instanceof Error) {
|
|
1497
|
-
client.serverErrorCounter.addServerError({
|
|
1498
|
-
consumer: consumer == null ? void 0 : consumer.identifier,
|
|
1499
|
-
method: event.req.method,
|
|
1500
|
-
path,
|
|
1501
|
-
type: error.cause.name,
|
|
1502
|
-
msg: error.cause.message,
|
|
1503
|
-
traceback: error.cause.stack || ""
|
|
1504
|
-
});
|
|
1505
|
-
}
|
|
1506
|
-
}
|
|
1507
|
-
if (client.requestLogger.enabled) {
|
|
1508
|
-
const responseHeaders = response ? response.headers : (error == null ? void 0 : error.headers) ? mergeHeaders(jsonHeaders, error.headers) : jsonHeaders;
|
|
1509
|
-
const responseContentType = responseHeaders.get("content-type");
|
|
1510
|
-
let responseBody;
|
|
1511
|
-
if (newResponse && client.requestLogger.config.logResponseBody && client.requestLogger.isSupportedContentType(responseContentType)) {
|
|
1512
|
-
[responseBody, newResponse] = await getResponseBody(newResponse);
|
|
1513
|
-
} else if (error && client.requestLogger.config.logResponseBody) {
|
|
1514
|
-
responseBody = Buffer.from(JSON.stringify(error.toJSON()));
|
|
1515
|
-
}
|
|
1516
|
-
const logs = logsContext.getStore();
|
|
1517
|
-
client.requestLogger.logRequest({
|
|
1518
|
-
timestamp: (Date.now() - responseTime) / 1e3,
|
|
1519
|
-
method: event.req.method,
|
|
1520
|
-
path,
|
|
1521
|
-
url: event.req.url,
|
|
1522
|
-
headers: convertHeaders(Object.fromEntries(event.req.headers.entries())),
|
|
1523
|
-
size: requestSize,
|
|
1524
|
-
consumer: consumer == null ? void 0 : consumer.identifier,
|
|
1525
|
-
body: event.context[REQUEST_BODY_SYMBOL]
|
|
1526
|
-
}, {
|
|
1527
|
-
statusCode,
|
|
1528
|
-
responseTime: responseTime / 1e3,
|
|
1529
|
-
headers: convertHeaders(Object.fromEntries(responseHeaders.entries())),
|
|
1530
|
-
size: responseSize,
|
|
1531
|
-
body: responseBody
|
|
1532
|
-
}, (error == null ? void 0 : error.cause) instanceof Error ? error.cause : void 0, logs);
|
|
1533
|
-
}
|
|
1534
|
-
return newResponse;
|
|
1535
|
-
}, "handleResponse");
|
|
1536
|
-
app.use((0, import_h3.onRequest)(async (event) => {
|
|
1537
|
-
logsContext.enterWith([]);
|
|
1538
|
-
event.context[REQUEST_TIMESTAMP_SYMBOL] = import_node_perf_hooks.performance.now();
|
|
1539
|
-
const requestContentType = event.req.headers.get("content-type");
|
|
1540
|
-
const requestSize = parseContentLength(event.req.headers.get("content-length")) ?? 0;
|
|
1541
|
-
if (client.requestLogger.enabled && client.requestLogger.config.logRequestBody && client.requestLogger.isSupportedContentType(requestContentType) && requestSize <= client.requestLogger.maxBodySize) {
|
|
1542
|
-
const clonedRequest = event.req.clone();
|
|
1543
|
-
const requestBody = Buffer.from(await clonedRequest.arrayBuffer());
|
|
1544
|
-
event.context[REQUEST_BODY_SYMBOL] = requestBody;
|
|
1545
|
-
}
|
|
1546
|
-
})).use((0, import_h3.onResponse)((response, event) => {
|
|
1547
|
-
if (client.isEnabled()) {
|
|
1548
|
-
return handleResponse(event, response, void 0);
|
|
1549
|
-
}
|
|
1550
|
-
})).use((0, import_h3.onError)((error, event) => {
|
|
1551
|
-
if (client.isEnabled()) {
|
|
1552
|
-
return handleResponse(event, void 0, error);
|
|
1553
|
-
}
|
|
1554
|
-
}));
|
|
1555
|
-
});
|
|
1556
|
-
function setConsumer(event, consumer) {
|
|
1557
|
-
event.context.apitallyConsumer = consumer || void 0;
|
|
1558
|
-
}
|
|
1559
|
-
__name(setConsumer, "setConsumer");
|
|
1560
|
-
function getConsumer(event) {
|
|
1561
|
-
const consumer = event.context.apitallyConsumer;
|
|
1562
|
-
if (consumer) {
|
|
1563
|
-
return consumerFromStringOrObject(consumer);
|
|
1564
|
-
}
|
|
1565
|
-
return null;
|
|
1566
|
-
}
|
|
1567
|
-
__name(getConsumer, "getConsumer");
|
|
25
|
+
var import_plugin = require("./plugin.js");
|
|
1568
26
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1569
27
|
0 && (module.exports = {
|
|
1570
28
|
apitallyPlugin,
|