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