@zharp/node 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +123 -3
- package/dist/index.d.mts +191 -0
- package/dist/index.d.ts +191 -0
- package/dist/index.js +1403 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1389 -0
- package/dist/index.mjs.map +1 -0
- package/init.d.ts +2 -0
- package/init.js +4 -0
- package/init.mjs +5 -0
- package/package.json +83 -3
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1389 @@
|
|
|
1
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
2
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
3
|
+
}) : x)(function(x) {
|
|
4
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
5
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
// src/zharp.ts
|
|
9
|
+
import { register as registerLoader } from "module";
|
|
10
|
+
import {
|
|
11
|
+
DiagLogLevel,
|
|
12
|
+
diag,
|
|
13
|
+
INVALID_SPAN_CONTEXT,
|
|
14
|
+
logs,
|
|
15
|
+
SpanStatusCode,
|
|
16
|
+
trace as trace2
|
|
17
|
+
} from "@opentelemetry/api";
|
|
18
|
+
import { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from "@opentelemetry/core";
|
|
19
|
+
import { envDetector, hostDetector, resourceFromAttributes } from "@opentelemetry/resources";
|
|
20
|
+
import { NodeSDK } from "@opentelemetry/sdk-node";
|
|
21
|
+
import {
|
|
22
|
+
BatchSpanProcessor,
|
|
23
|
+
ParentBasedSampler,
|
|
24
|
+
SamplingDecision,
|
|
25
|
+
TraceIdRatioBasedSampler
|
|
26
|
+
} from "@opentelemetry/sdk-trace";
|
|
27
|
+
import { BatchLogRecordProcessor } from "@opentelemetry/sdk-logs";
|
|
28
|
+
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
|
|
29
|
+
import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
|
|
30
|
+
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
|
|
31
|
+
|
|
32
|
+
// ../../internal/src/builtins.ts
|
|
33
|
+
function loadBuiltin(name) {
|
|
34
|
+
try {
|
|
35
|
+
const proc = typeof process !== "undefined" ? process : void 0;
|
|
36
|
+
if (proc && typeof proc.getBuiltinModule === "function") {
|
|
37
|
+
return proc.getBuiltinModule(`node:${name}`) ?? null;
|
|
38
|
+
}
|
|
39
|
+
const req = typeof module !== "undefined" && typeof __require === "function" ? __require : null;
|
|
40
|
+
return req ? req(name) : null;
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// ../../internal/src/env.ts
|
|
47
|
+
function nodeEnv(name) {
|
|
48
|
+
if (typeof window !== "undefined" || typeof process === "undefined" || !process.env) return void 0;
|
|
49
|
+
const value = process.env[name];
|
|
50
|
+
return value && value.trim() ? value.trim() : void 0;
|
|
51
|
+
}
|
|
52
|
+
function packageName() {
|
|
53
|
+
if (typeof window !== "undefined" || typeof process === "undefined") return void 0;
|
|
54
|
+
const fs = loadBuiltin("fs");
|
|
55
|
+
const path = loadBuiltin("path");
|
|
56
|
+
if (!fs || !path) return void 0;
|
|
57
|
+
const starts = [process.argv?.[1] ? path.dirname(path.resolve(process.argv[1])) : "", process.cwd?.() ?? ""];
|
|
58
|
+
for (const start of starts.filter(Boolean)) {
|
|
59
|
+
let dir = start;
|
|
60
|
+
for (let i = 0; i < 12; i++) {
|
|
61
|
+
if (path.basename(dir) !== "node_modules") {
|
|
62
|
+
try {
|
|
63
|
+
const name = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"))?.name;
|
|
64
|
+
if (typeof name === "string" && name.trim()) return name.trim().replace(/^@[^/]+\//, "");
|
|
65
|
+
} catch {
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const parent = path.dirname(dir);
|
|
69
|
+
if (parent === dir) break;
|
|
70
|
+
dir = parent;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return void 0;
|
|
74
|
+
}
|
|
75
|
+
function disabledByEnv() {
|
|
76
|
+
const value = nodeEnv("ZHARP_DISABLED");
|
|
77
|
+
return !!value && /^(true|1|yes|on)$/i.test(value);
|
|
78
|
+
}
|
|
79
|
+
function pick(...values) {
|
|
80
|
+
for (const value of values) {
|
|
81
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
82
|
+
}
|
|
83
|
+
return void 0;
|
|
84
|
+
}
|
|
85
|
+
function describeTarget(service, environment) {
|
|
86
|
+
return `service "${service}", ${environment ? `environment "${environment}"` : "no environment set"}`;
|
|
87
|
+
}
|
|
88
|
+
function announce(message) {
|
|
89
|
+
console.info(`[Zharp] ${message}`);
|
|
90
|
+
}
|
|
91
|
+
function warn(message) {
|
|
92
|
+
console.warn(`[Zharp] ${message}`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ../../internal/src/bodies.ts
|
|
96
|
+
var DEFAULT_MAX_BODY = 32 * 1024;
|
|
97
|
+
var MAX_BODY = 128 * 1024;
|
|
98
|
+
var FILTERED = "[Filtered]";
|
|
99
|
+
function rawLimit(settings) {
|
|
100
|
+
return Math.max(64 * 1024, settings.maxSize * 2);
|
|
101
|
+
}
|
|
102
|
+
var BODY_ATTRIBUTES = {
|
|
103
|
+
request: "http.request.body",
|
|
104
|
+
requestTruncated: "http.request.body.truncated",
|
|
105
|
+
requestType: "http.request.header.content-type",
|
|
106
|
+
response: "http.response.body",
|
|
107
|
+
responseTruncated: "http.response.body.truncated",
|
|
108
|
+
responseType: "http.response.header.content-type"
|
|
109
|
+
};
|
|
110
|
+
function bodySettings(option, env) {
|
|
111
|
+
let value = option;
|
|
112
|
+
if (value === void 0 && env) {
|
|
113
|
+
const e = env.trim().toLowerCase();
|
|
114
|
+
if (e === "errors" || e === "all") value = e;
|
|
115
|
+
else if (/^(true|1|yes|on)$/.test(e)) value = true;
|
|
116
|
+
}
|
|
117
|
+
if (!value) return null;
|
|
118
|
+
const o = value === true ? {} : typeof value === "string" ? { mode: value } : value;
|
|
119
|
+
const size = typeof o.maxSize === "number" && o.maxSize > 0 ? Math.min(Math.floor(o.maxSize), MAX_BODY) : DEFAULT_MAX_BODY;
|
|
120
|
+
return { mode: o.mode === "all" ? "all" : "errors", maxSize: size, extraKeys: o.redactKeys ?? [], urls: o.urls };
|
|
121
|
+
}
|
|
122
|
+
function wanted(settings, status) {
|
|
123
|
+
return settings.mode === "all" || !status || status >= 400;
|
|
124
|
+
}
|
|
125
|
+
var mime = (contentType) => (contentType ?? "").split(";")[0].trim().toLowerCase();
|
|
126
|
+
function isEventStream(contentType) {
|
|
127
|
+
return mime(contentType) === "text/event-stream";
|
|
128
|
+
}
|
|
129
|
+
function isMultipart(contentType) {
|
|
130
|
+
return mime(contentType) === "multipart/form-data";
|
|
131
|
+
}
|
|
132
|
+
function isTextual(contentType) {
|
|
133
|
+
const type = mime(contentType);
|
|
134
|
+
if (!type) return true;
|
|
135
|
+
if (type === "text/event-stream") return false;
|
|
136
|
+
return type.startsWith("text/") || type.endsWith("+json") || type.endsWith("+xml") || /^application\/(json|xml|x-www-form-urlencoded|graphql|javascript|x-ndjson|ld\+json)$/.test(type);
|
|
137
|
+
}
|
|
138
|
+
function isForm(contentType) {
|
|
139
|
+
return mime(contentType) === "application/x-www-form-urlencoded";
|
|
140
|
+
}
|
|
141
|
+
function formatSize(bytes) {
|
|
142
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
143
|
+
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
|
|
144
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
145
|
+
}
|
|
146
|
+
function fileLabel(name, type, size, partial = false) {
|
|
147
|
+
const parts = [`file ${name || "blob"}`];
|
|
148
|
+
if (type) parts.push(type);
|
|
149
|
+
if (size !== void 0) parts.push(formatSize(size) + (partial ? "+" : ""));
|
|
150
|
+
return `[${parts.join(" \xB7 ")}]`;
|
|
151
|
+
}
|
|
152
|
+
function describeBody(contentType, size, partial = false) {
|
|
153
|
+
if (isEventStream(contentType)) return "[event stream]";
|
|
154
|
+
const parts = ["binary"];
|
|
155
|
+
const type = mime(contentType);
|
|
156
|
+
if (type) parts.push(type);
|
|
157
|
+
if (size !== void 0 && size > 0) parts.push(formatSize(size) + (partial ? "+" : ""));
|
|
158
|
+
return `[${parts.join(" \xB7 ")}]`;
|
|
159
|
+
}
|
|
160
|
+
var CONTAINS = [
|
|
161
|
+
"password",
|
|
162
|
+
"passwd",
|
|
163
|
+
"passphrase",
|
|
164
|
+
"secret",
|
|
165
|
+
"token",
|
|
166
|
+
"apikey",
|
|
167
|
+
"accesskey",
|
|
168
|
+
"privatekey",
|
|
169
|
+
"authorization",
|
|
170
|
+
"cookie",
|
|
171
|
+
"creditcard",
|
|
172
|
+
"cardnumber",
|
|
173
|
+
"cvv",
|
|
174
|
+
"cvc",
|
|
175
|
+
"ssn",
|
|
176
|
+
"iban",
|
|
177
|
+
"sessionid",
|
|
178
|
+
"signature",
|
|
179
|
+
"credential"
|
|
180
|
+
];
|
|
181
|
+
var EXACT = ["auth", "pin", "pwd", "otp", "card", "pan", "jwt", "sid", "codeverifier"];
|
|
182
|
+
var URL_EXACT = ["key", "sig", "code", "state", "session"];
|
|
183
|
+
var normalize = (key) => key.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
184
|
+
function isSecretKey(key, extra = []) {
|
|
185
|
+
const k = normalize(key);
|
|
186
|
+
if (!k) return false;
|
|
187
|
+
if (EXACT.includes(k) || CONTAINS.some((c) => k.includes(c))) return true;
|
|
188
|
+
return extra.some((p) => p instanceof RegExp ? p.test(key) : normalize(p) === k);
|
|
189
|
+
}
|
|
190
|
+
var DATA_URI = /^data:([\w.+-]+\/[\w.+-]+)?(?:;[\w=.+-]+)*;base64,([A-Za-z0-9+/=\s]*)$/;
|
|
191
|
+
var BASE64 = /^[A-Za-z0-9+/_-]{256,}={0,2}$/;
|
|
192
|
+
function shorten(value) {
|
|
193
|
+
if (value.length < 256) return value;
|
|
194
|
+
const uri = DATA_URI.exec(value);
|
|
195
|
+
if (uri) return `[${uri[1] || "data"} \xB7 ${formatSize(Math.floor(uri[2].length * 3 / 4))}]`;
|
|
196
|
+
if (BASE64.test(value) && /[0-9+/]/.test(value)) return `[base64 \xB7 ${formatSize(Math.floor(value.length * 3 / 4))}]`;
|
|
197
|
+
return value;
|
|
198
|
+
}
|
|
199
|
+
function filterAll(value, depth) {
|
|
200
|
+
if (depth > 20) return FILTERED;
|
|
201
|
+
if (value === null || value === "") return value;
|
|
202
|
+
if (Array.isArray(value)) return value.map((v) => filterAll(v, depth + 1));
|
|
203
|
+
if (typeof value === "object") {
|
|
204
|
+
const out = {};
|
|
205
|
+
for (const [k, v] of Object.entries(value)) out[k] = filterAll(v, depth + 1);
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
return FILTERED;
|
|
209
|
+
}
|
|
210
|
+
function redactValue(value, extra, depth = 0) {
|
|
211
|
+
if (typeof value === "string") return shorten(value);
|
|
212
|
+
if (depth > 20 || value === null || typeof value !== "object") return value;
|
|
213
|
+
if (Array.isArray(value)) return value.map((v) => redactValue(v, extra, depth + 1));
|
|
214
|
+
const out = {};
|
|
215
|
+
for (const [k, v] of Object.entries(value)) {
|
|
216
|
+
out[k] = isSecretKey(k, extra) ? filterAll(v, depth + 1) : redactValue(v, extra, depth + 1);
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
function redactLoose(text, extra) {
|
|
221
|
+
const runs = /"((?:data:[\w.+-]+\/[\w.+-]+(?:;[\w=.+-]+)*;base64,)?[A-Za-z0-9+/_=-]{256,})("?)/g;
|
|
222
|
+
return text.replace(runs, (match, run, close) => {
|
|
223
|
+
const short = shorten(run);
|
|
224
|
+
if (short === run) return match;
|
|
225
|
+
return close ? `"${short}"` : `"${short.slice(0, -1)}+]"`;
|
|
226
|
+
}).replace(
|
|
227
|
+
/("([^"\\]{1,100})"\s*:\s*)("(?:[^"\\]|\\.)*"?|-?\d[\d.eE+-]*|true|false)/g,
|
|
228
|
+
(match, prefix, key) => isSecretKey(key, extra) ? `${prefix}"${FILTERED}"` : match
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
function redactForm(text, extra) {
|
|
232
|
+
return text.split("&").map((pair) => {
|
|
233
|
+
const eq = pair.indexOf("=");
|
|
234
|
+
if (eq < 0) return pair;
|
|
235
|
+
let key = pair.slice(0, eq);
|
|
236
|
+
try {
|
|
237
|
+
key = decodeURIComponent(key.replace(/\+/g, " "));
|
|
238
|
+
} catch {
|
|
239
|
+
}
|
|
240
|
+
if (isSecretKey(key, extra)) return `${pair.slice(0, eq)}=${FILTERED}`;
|
|
241
|
+
const value = pair.slice(eq + 1);
|
|
242
|
+
return value.length >= 256 ? `${pair.slice(0, eq)}=${shortenEncoded(value)}` : pair;
|
|
243
|
+
}).join("&");
|
|
244
|
+
}
|
|
245
|
+
function shortenEncoded(value) {
|
|
246
|
+
try {
|
|
247
|
+
const decoded = decodeURIComponent(value.replace(/\+/g, " "));
|
|
248
|
+
const short = shorten(decoded);
|
|
249
|
+
return short === decoded ? value : short;
|
|
250
|
+
} catch {
|
|
251
|
+
return value;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
function formatBody(text, contentType, settings, cut = false) {
|
|
255
|
+
if (text == null) return null;
|
|
256
|
+
let body = String(text);
|
|
257
|
+
if (!body.trim()) return null;
|
|
258
|
+
if (isForm(contentType)) body = redactForm(body, settings.extraKeys);
|
|
259
|
+
else {
|
|
260
|
+
let parsed2;
|
|
261
|
+
let ok = false;
|
|
262
|
+
const trimmed = body.trim();
|
|
263
|
+
if (!cut && (trimmed[0] === "{" || trimmed[0] === "[")) {
|
|
264
|
+
try {
|
|
265
|
+
parsed2 = JSON.parse(trimmed);
|
|
266
|
+
ok = true;
|
|
267
|
+
} catch {
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
body = ok ? JSON.stringify(redactValue(parsed2, settings.extraKeys)) : redactLoose(body, settings.extraKeys);
|
|
271
|
+
}
|
|
272
|
+
const truncated = cut || body.length > settings.maxSize;
|
|
273
|
+
return { value: body.length > settings.maxSize ? body.slice(0, settings.maxSize) : body, truncated };
|
|
274
|
+
}
|
|
275
|
+
function typeKey(side) {
|
|
276
|
+
return side === "request" ? BODY_ATTRIBUTES.requestType : BODY_ATTRIBUTES.responseType;
|
|
277
|
+
}
|
|
278
|
+
function bodyAttributes(side, text, contentType, settings, cut = false) {
|
|
279
|
+
if (!isTextual(contentType) && !isMultipart(contentType)) return {};
|
|
280
|
+
const formatted = formatBody(text, contentType, settings, cut);
|
|
281
|
+
if (!formatted) return {};
|
|
282
|
+
const attributes = { [BODY_ATTRIBUTES[side]]: formatted.value };
|
|
283
|
+
if (formatted.truncated) attributes[side === "request" ? BODY_ATTRIBUTES.requestTruncated : BODY_ATTRIBUTES.responseTruncated] = true;
|
|
284
|
+
if (contentType) attributes[typeKey(side)] = contentType;
|
|
285
|
+
return attributes;
|
|
286
|
+
}
|
|
287
|
+
function describedAttributes(side, contentType, size, partial = false) {
|
|
288
|
+
const attributes = { [BODY_ATTRIBUTES[side]]: describeBody(contentType, size, partial) };
|
|
289
|
+
if (contentType) attributes[typeKey(side)] = contentType;
|
|
290
|
+
return attributes;
|
|
291
|
+
}
|
|
292
|
+
function redactUrl(url, extra = []) {
|
|
293
|
+
if (!url) return url;
|
|
294
|
+
let out = url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, "$1");
|
|
295
|
+
const q = out.indexOf("?");
|
|
296
|
+
if (q < 0) return out;
|
|
297
|
+
const hash = out.indexOf("#", q);
|
|
298
|
+
const query = out.slice(q + 1, hash < 0 ? void 0 : hash);
|
|
299
|
+
const redacted = redactQuery(query, extra);
|
|
300
|
+
if (redacted !== query) out = out.slice(0, q + 1) + redacted + (hash < 0 ? "" : out.slice(hash));
|
|
301
|
+
return out;
|
|
302
|
+
}
|
|
303
|
+
function redactQuery(query, extra = []) {
|
|
304
|
+
if (!query) return query;
|
|
305
|
+
return query.split("&").map((pair) => {
|
|
306
|
+
const eq = pair.indexOf("=");
|
|
307
|
+
if (eq < 0) return pair;
|
|
308
|
+
let key = pair.slice(0, eq);
|
|
309
|
+
try {
|
|
310
|
+
key = decodeURIComponent(key.replace(/\+/g, " "));
|
|
311
|
+
} catch {
|
|
312
|
+
}
|
|
313
|
+
const secret = isSecretKey(key, extra) || URL_EXACT.includes(normalize(key));
|
|
314
|
+
return secret && eq < pair.length - 1 ? `${pair.slice(0, eq)}=${FILTERED}` : pair;
|
|
315
|
+
}).join("&");
|
|
316
|
+
}
|
|
317
|
+
function urlMatches(url, patterns) {
|
|
318
|
+
let host = "";
|
|
319
|
+
let hostname = "";
|
|
320
|
+
try {
|
|
321
|
+
const parsed2 = new URL(url);
|
|
322
|
+
host = parsed2.host;
|
|
323
|
+
hostname = parsed2.hostname;
|
|
324
|
+
} catch {
|
|
325
|
+
}
|
|
326
|
+
return patterns.some((p) => {
|
|
327
|
+
if (p instanceof RegExp) return p.test(url);
|
|
328
|
+
if (!p) return false;
|
|
329
|
+
if (p.includes("://")) return url.startsWith(p);
|
|
330
|
+
return host === p || hostname === p;
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// src/bodies.ts
|
|
335
|
+
import { ClientRequest, IncomingMessage, ServerResponse } from "http";
|
|
336
|
+
import { brotliDecompressSync, constants, gunzipSync, inflateSync } from "zlib";
|
|
337
|
+
var TAP = /* @__PURE__ */ Symbol.for("zharp.body");
|
|
338
|
+
var MAX_FIELDS = 200;
|
|
339
|
+
var Multipart = class {
|
|
340
|
+
constructor(boundary, maxText) {
|
|
341
|
+
this.maxText = maxText;
|
|
342
|
+
this.first = Buffer.from(`--${boundary}`);
|
|
343
|
+
this.delimiter = Buffer.from(`\r
|
|
344
|
+
--${boundary}`);
|
|
345
|
+
}
|
|
346
|
+
maxText;
|
|
347
|
+
buf = Buffer.alloc(0);
|
|
348
|
+
state = "start";
|
|
349
|
+
first;
|
|
350
|
+
delimiter;
|
|
351
|
+
part = null;
|
|
352
|
+
count = 0;
|
|
353
|
+
fields = {};
|
|
354
|
+
cut = false;
|
|
355
|
+
push(chunk) {
|
|
356
|
+
if (this.state === "done") return;
|
|
357
|
+
this.buf = this.buf.length ? Buffer.concat([this.buf, chunk]) : chunk;
|
|
358
|
+
for (; ; ) {
|
|
359
|
+
if (this.state === "start") {
|
|
360
|
+
const i = this.buf.indexOf(this.first);
|
|
361
|
+
if (i < 0) {
|
|
362
|
+
if (this.buf.length > 64 * 1024) this.state = "done";
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
this.buf = this.buf.subarray(i + this.first.length);
|
|
366
|
+
this.state = "after";
|
|
367
|
+
}
|
|
368
|
+
if (this.state === "after") {
|
|
369
|
+
if (this.buf.length < 2) return;
|
|
370
|
+
if (this.buf[0] === 45 && this.buf[1] === 45) {
|
|
371
|
+
this.state = "done";
|
|
372
|
+
this.buf = Buffer.alloc(0);
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
if (this.buf[0] === 13 && this.buf[1] === 10) this.buf = this.buf.subarray(2);
|
|
376
|
+
this.state = "headers";
|
|
377
|
+
}
|
|
378
|
+
if (this.state === "headers") {
|
|
379
|
+
const i = this.buf.indexOf("\r\n\r\n");
|
|
380
|
+
if (i < 0) {
|
|
381
|
+
if (this.buf.length > 16 * 1024) this.state = "done";
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
this.part = parsePartHeaders(this.buf.subarray(0, i).toString("utf8"));
|
|
385
|
+
this.buf = this.buf.subarray(i + 4);
|
|
386
|
+
this.state = "body";
|
|
387
|
+
}
|
|
388
|
+
if (this.state === "body") {
|
|
389
|
+
const i = this.buf.indexOf(this.delimiter);
|
|
390
|
+
if (i >= 0) {
|
|
391
|
+
this.consume(this.buf.subarray(0, i));
|
|
392
|
+
this.finish(false);
|
|
393
|
+
this.buf = this.buf.subarray(i + this.delimiter.length);
|
|
394
|
+
this.state = "after";
|
|
395
|
+
if (this.count >= MAX_FIELDS) {
|
|
396
|
+
this.state = "done";
|
|
397
|
+
this.cut = true;
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
const keep = this.delimiter.length - 1;
|
|
403
|
+
if (this.buf.length > keep) {
|
|
404
|
+
this.consume(this.buf.subarray(0, this.buf.length - keep));
|
|
405
|
+
this.buf = Buffer.from(this.buf.subarray(this.buf.length - keep));
|
|
406
|
+
}
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
consume(bytes) {
|
|
413
|
+
const part = this.part;
|
|
414
|
+
if (!part || !bytes.length) return;
|
|
415
|
+
part.size += bytes.length;
|
|
416
|
+
if (part.filename !== void 0) return;
|
|
417
|
+
const room = this.maxText - part.kept;
|
|
418
|
+
if (room > 0) {
|
|
419
|
+
const slice = bytes.subarray(0, room);
|
|
420
|
+
part.text.push(Buffer.from(slice));
|
|
421
|
+
part.kept += slice.length;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
finish(partial) {
|
|
425
|
+
const part = this.part;
|
|
426
|
+
this.part = null;
|
|
427
|
+
if (!part) return;
|
|
428
|
+
let value;
|
|
429
|
+
if (part.filename !== void 0) value = fileLabel(part.filename, part.type, part.size, partial);
|
|
430
|
+
else {
|
|
431
|
+
value = Buffer.concat(part.text).toString("utf8").replace(/�$/, "");
|
|
432
|
+
if (part.size > part.kept || partial) this.cut = true;
|
|
433
|
+
}
|
|
434
|
+
const existing = this.fields[part.name];
|
|
435
|
+
this.fields[part.name] = existing === void 0 ? value : Array.isArray(existing) ? [...existing, value] : [existing, value];
|
|
436
|
+
this.count++;
|
|
437
|
+
}
|
|
438
|
+
/** The fields so far, including a part the stream stopped inside. */
|
|
439
|
+
result() {
|
|
440
|
+
if (this.part) {
|
|
441
|
+
this.consume(this.state === "body" ? this.buf : Buffer.alloc(0));
|
|
442
|
+
this.buf = Buffer.alloc(0);
|
|
443
|
+
this.finish(true);
|
|
444
|
+
this.cut = true;
|
|
445
|
+
}
|
|
446
|
+
return { json: JSON.stringify(this.fields), cut: this.cut };
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
function parsePartHeaders(head) {
|
|
450
|
+
const disposition = /^content-disposition:(.*)$/im.exec(head)?.[1] ?? "";
|
|
451
|
+
const name = /\bname="([^"]*)"/i.exec(disposition)?.[1] ?? /\bname=([^;\s]+)/i.exec(disposition)?.[1] ?? "";
|
|
452
|
+
const filenameStar = /\bfilename\*=(?:UTF-8'')?([^;\s]+)/i.exec(disposition)?.[1];
|
|
453
|
+
let filename = /\bfilename="([^"]*)"/i.exec(disposition)?.[1];
|
|
454
|
+
if (filenameStar) {
|
|
455
|
+
try {
|
|
456
|
+
filename = decodeURIComponent(filenameStar);
|
|
457
|
+
} catch {
|
|
458
|
+
filename = filenameStar;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
const type = /^content-type:\s*(.*)$/im.exec(head)?.[1]?.trim();
|
|
462
|
+
return { name, filename, type: filename !== void 0 ? type : void 0, size: 0, text: [], kept: 0 };
|
|
463
|
+
}
|
|
464
|
+
function boundaryOf(contentType) {
|
|
465
|
+
const m = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType ?? "");
|
|
466
|
+
return m ? m[1] ?? m[2] : void 0;
|
|
467
|
+
}
|
|
468
|
+
var Tap = class {
|
|
469
|
+
/** `typeOf` is asked once, at the first byte, when the content type is surely set. */
|
|
470
|
+
constructor(settings, typeOf2) {
|
|
471
|
+
this.settings = settings;
|
|
472
|
+
this.typeOf = typeOf2;
|
|
473
|
+
}
|
|
474
|
+
settings;
|
|
475
|
+
typeOf;
|
|
476
|
+
chunks = [];
|
|
477
|
+
kept = 0;
|
|
478
|
+
/** Every byte seen, kept or not. */
|
|
479
|
+
total = 0;
|
|
480
|
+
cut = false;
|
|
481
|
+
mode;
|
|
482
|
+
multipart;
|
|
483
|
+
add(chunk, encoding) {
|
|
484
|
+
if (chunk == null || typeof chunk === "function") return;
|
|
485
|
+
let buf;
|
|
486
|
+
if (typeof chunk === "string") buf = Buffer.from(chunk, typeof encoding === "string" && Buffer.isEncoding(encoding) ? encoding : "utf8");
|
|
487
|
+
else if (chunk instanceof Uint8Array) buf = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
|
|
488
|
+
else return;
|
|
489
|
+
if (!buf.length) return;
|
|
490
|
+
this.total += buf.length;
|
|
491
|
+
if (this.mode === void 0) {
|
|
492
|
+
const type = this.typeOf();
|
|
493
|
+
const boundary = isMultipart(type) ? boundaryOf(type) : void 0;
|
|
494
|
+
if (boundary) {
|
|
495
|
+
this.mode = "multipart";
|
|
496
|
+
this.multipart = new Multipart(boundary, this.settings.maxSize);
|
|
497
|
+
} else this.mode = isTextual(type) ? "text" : "count";
|
|
498
|
+
}
|
|
499
|
+
if (this.mode === "multipart") return this.multipart.push(Buffer.from(buf));
|
|
500
|
+
if (this.mode === "count" || this.cut) return;
|
|
501
|
+
const room = rawLimit(this.settings) - this.kept;
|
|
502
|
+
if (buf.length > room) {
|
|
503
|
+
this.cut = true;
|
|
504
|
+
buf = buf.subarray(0, Math.max(0, room));
|
|
505
|
+
}
|
|
506
|
+
if (buf.length) {
|
|
507
|
+
this.chunks.push(Buffer.from(buf));
|
|
508
|
+
this.kept += buf.length;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
/** The text, inflated if it was compressed; null when it cannot be read as text. */
|
|
512
|
+
text(encoding) {
|
|
513
|
+
let raw = Buffer.concat(this.chunks);
|
|
514
|
+
const enc = (encoding ?? "").toLowerCase().trim();
|
|
515
|
+
try {
|
|
516
|
+
const flush = { finishFlush: constants.Z_SYNC_FLUSH };
|
|
517
|
+
if (enc === "gzip" || enc === "x-gzip") raw = gunzipSync(raw, flush);
|
|
518
|
+
else if (enc === "deflate") raw = inflateSync(raw, flush);
|
|
519
|
+
else if (enc === "br") raw = brotliDecompressSync(raw, { finishFlush: constants.BROTLI_OPERATION_FLUSH });
|
|
520
|
+
else if (enc && enc !== "identity") return null;
|
|
521
|
+
} catch {
|
|
522
|
+
return null;
|
|
523
|
+
}
|
|
524
|
+
return raw.toString("utf8").replace(/�$/, "");
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
function sideAttributes(side, tap, type, encoding, settings) {
|
|
528
|
+
if (!tap || !tap.total) return {};
|
|
529
|
+
if (tap.multipart) {
|
|
530
|
+
const { json, cut } = tap.multipart.result();
|
|
531
|
+
return bodyAttributes(side, json, type, settings, cut);
|
|
532
|
+
}
|
|
533
|
+
if (!isTextual(type)) return describedAttributes(side, type, tap.total);
|
|
534
|
+
const text = tap.text(encoding);
|
|
535
|
+
if (text == null) return describedAttributes(side, type, tap.total);
|
|
536
|
+
return bodyAttributes(side, text, type, settings, tap.cut);
|
|
537
|
+
}
|
|
538
|
+
function tapReadable(stream, tap) {
|
|
539
|
+
const emit = stream.emit;
|
|
540
|
+
stream.emit = function(event, ...args) {
|
|
541
|
+
if (event === "data") {
|
|
542
|
+
try {
|
|
543
|
+
tap.add(args[0]);
|
|
544
|
+
} catch {
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
return emit.call(this, event, ...args);
|
|
548
|
+
};
|
|
549
|
+
stream[TAP] = tap;
|
|
550
|
+
}
|
|
551
|
+
function tapWritable(stream, tap) {
|
|
552
|
+
const target = stream;
|
|
553
|
+
const write = target.write;
|
|
554
|
+
const end = target.end;
|
|
555
|
+
target.write = function(...args) {
|
|
556
|
+
try {
|
|
557
|
+
tap.add(args[0], args[1]);
|
|
558
|
+
} catch {
|
|
559
|
+
}
|
|
560
|
+
return write.apply(this, args);
|
|
561
|
+
};
|
|
562
|
+
target.end = function(...args) {
|
|
563
|
+
try {
|
|
564
|
+
tap.add(args[0], args[1]);
|
|
565
|
+
} catch {
|
|
566
|
+
}
|
|
567
|
+
return end.apply(this, args);
|
|
568
|
+
};
|
|
569
|
+
stream[TAP] = tap;
|
|
570
|
+
}
|
|
571
|
+
var tapOf = (stream) => stream?.[TAP];
|
|
572
|
+
function header(value) {
|
|
573
|
+
if (value == null) return void 0;
|
|
574
|
+
return Array.isArray(value) ? String(value[0]) : String(value);
|
|
575
|
+
}
|
|
576
|
+
function incomingUrl(req) {
|
|
577
|
+
const proto = req.socket?.encrypted ? "https" : "http";
|
|
578
|
+
return `${proto}://${req.headers.host ?? "localhost"}${req.url ?? "/"}`;
|
|
579
|
+
}
|
|
580
|
+
function sentHeader(res, name) {
|
|
581
|
+
const set = header(res.getHeader(name));
|
|
582
|
+
if (set) return set;
|
|
583
|
+
const head = res._header;
|
|
584
|
+
if (typeof head !== "string") return void 0;
|
|
585
|
+
const match = head.match(new RegExp(`^${name}:[ \\t]*(.*)$`, "im"));
|
|
586
|
+
return match ? match[1].trim() : void 0;
|
|
587
|
+
}
|
|
588
|
+
function outgoingUrl(req) {
|
|
589
|
+
const r = req;
|
|
590
|
+
return `${r.protocol ?? "http:"}//${r.host ?? "localhost"}${r.path ?? "/"}`;
|
|
591
|
+
}
|
|
592
|
+
function withBodyCapture(settings, config = {}) {
|
|
593
|
+
const allowed = (url) => !settings.urls || urlMatches(url, settings.urls);
|
|
594
|
+
return {
|
|
595
|
+
...config,
|
|
596
|
+
requestHook(span, request) {
|
|
597
|
+
config.requestHook?.(span, request);
|
|
598
|
+
try {
|
|
599
|
+
if (request instanceof IncomingMessage) {
|
|
600
|
+
if (allowed(incomingUrl(request))) tapReadable(request, new Tap(settings, () => header(request.headers["content-type"])));
|
|
601
|
+
} else if (request instanceof ClientRequest) {
|
|
602
|
+
if (allowed(outgoingUrl(request))) tapWritable(request, new Tap(settings, () => header(request.getHeader("content-type"))));
|
|
603
|
+
}
|
|
604
|
+
} catch {
|
|
605
|
+
}
|
|
606
|
+
},
|
|
607
|
+
responseHook(span, response) {
|
|
608
|
+
config.responseHook?.(span, response);
|
|
609
|
+
try {
|
|
610
|
+
if (response instanceof ServerResponse) {
|
|
611
|
+
if (tapOf(response.req) || allowed(incomingUrl(response.req))) tapWritable(response, new Tap(settings, () => sentHeader(response, "content-type")));
|
|
612
|
+
} else if (response instanceof IncomingMessage) {
|
|
613
|
+
const req = response.req;
|
|
614
|
+
if (!req || tapOf(req) || allowed(outgoingUrl(req))) tapReadable(response, new Tap(settings, () => header(response.headers["content-type"])));
|
|
615
|
+
}
|
|
616
|
+
} catch {
|
|
617
|
+
}
|
|
618
|
+
},
|
|
619
|
+
applyCustomAttributesOnSpan(span, request, response) {
|
|
620
|
+
config.applyCustomAttributesOnSpan?.(span, request, response);
|
|
621
|
+
try {
|
|
622
|
+
const status = Number(response?.statusCode) || 0;
|
|
623
|
+
if (!wanted(settings, status)) return;
|
|
624
|
+
const attributes = {};
|
|
625
|
+
if (request instanceof ClientRequest) {
|
|
626
|
+
Object.assign(
|
|
627
|
+
attributes,
|
|
628
|
+
sideAttributes("request", tapOf(request), header(request.getHeader("content-type")), header(request.getHeader("content-encoding")), settings)
|
|
629
|
+
);
|
|
630
|
+
const res = response;
|
|
631
|
+
Object.assign(
|
|
632
|
+
attributes,
|
|
633
|
+
sideAttributes("response", tapOf(res), header(res?.headers?.["content-type"]), header(res?.headers?.["content-encoding"]), settings)
|
|
634
|
+
);
|
|
635
|
+
} else if (request instanceof IncomingMessage) {
|
|
636
|
+
const sentType = header(request.headers["content-type"]);
|
|
637
|
+
const sent = tapOf(request);
|
|
638
|
+
if (sent && sent.total) {
|
|
639
|
+
Object.assign(attributes, sideAttributes("request", sent, sentType, header(request.headers["content-encoding"]), settings));
|
|
640
|
+
} else {
|
|
641
|
+
const parsed2 = request.body;
|
|
642
|
+
if (parsed2 != null && (typeof parsed2 === "string" || typeof parsed2 === "object" && !Buffer.isBuffer(parsed2))) {
|
|
643
|
+
const text = typeof parsed2 === "string" ? parsed2 : JSON.stringify(parsed2);
|
|
644
|
+
Object.assign(attributes, bodyAttributes("request", text, isTextual(sentType) ? sentType : "application/json", settings));
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
const res = response;
|
|
648
|
+
Object.assign(attributes, sideAttributes("response", tapOf(res), sentHeader(res, "content-type"), sentHeader(res, "content-encoding"), settings));
|
|
649
|
+
}
|
|
650
|
+
if (Object.keys(attributes).length) span.setAttributes(attributes);
|
|
651
|
+
} catch {
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// src/urls.ts
|
|
658
|
+
var URL_KEYS = ["url.full", "http.url", "http.target"];
|
|
659
|
+
var UrlRedactionSpanProcessor = class {
|
|
660
|
+
onStart() {
|
|
661
|
+
}
|
|
662
|
+
onEnding(span) {
|
|
663
|
+
try {
|
|
664
|
+
const attributes = span.attributes ?? {};
|
|
665
|
+
for (const key of URL_KEYS) {
|
|
666
|
+
const value = attributes[key];
|
|
667
|
+
if (typeof value === "string") {
|
|
668
|
+
const redacted = redactUrl(value);
|
|
669
|
+
if (redacted !== value) span.setAttribute(key, redacted);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
const query = attributes["url.query"];
|
|
673
|
+
if (typeof query === "string") {
|
|
674
|
+
const bare = query.startsWith("?") ? query.slice(1) : query;
|
|
675
|
+
const redacted = redactQuery(bare);
|
|
676
|
+
if (redacted !== bare) span.setAttribute("url.query", (query.startsWith("?") ? "?" : "") + redacted);
|
|
677
|
+
}
|
|
678
|
+
} catch {
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
onEnd(_span) {
|
|
682
|
+
}
|
|
683
|
+
forceFlush() {
|
|
684
|
+
return Promise.resolve();
|
|
685
|
+
}
|
|
686
|
+
shutdown() {
|
|
687
|
+
return Promise.resolve();
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
|
|
691
|
+
// src/context.ts
|
|
692
|
+
import { context as otelContext, propagation, trace } from "@opentelemetry/api";
|
|
693
|
+
var BAGGAGE_KEYS = ["enduser.id", "session.id"];
|
|
694
|
+
function userAttributes(user) {
|
|
695
|
+
const out = { "enduser.id": String(user.id) };
|
|
696
|
+
if (user.email) out["enduser.email"] = String(user.email);
|
|
697
|
+
if (user.name) out["enduser.name"] = String(user.name);
|
|
698
|
+
return out;
|
|
699
|
+
}
|
|
700
|
+
var ContextStore = class {
|
|
701
|
+
/** Set outside any request: a script or worker that is one user's work throughout. */
|
|
702
|
+
globalUser = null;
|
|
703
|
+
tags = {};
|
|
704
|
+
byTrace = /* @__PURE__ */ new Map();
|
|
705
|
+
/** The first span of each trace in this process, which the user is also written onto. */
|
|
706
|
+
localRoots = /* @__PURE__ */ new Map();
|
|
707
|
+
/** Set the user for the request in progress, or for the whole process outside one. */
|
|
708
|
+
setUser(user) {
|
|
709
|
+
const span = trace.getActiveSpan();
|
|
710
|
+
const traceId = span?.spanContext().traceId;
|
|
711
|
+
if (!span || !traceId) {
|
|
712
|
+
this.globalUser = user;
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
if (user) {
|
|
716
|
+
this.byTrace.set(traceId, user);
|
|
717
|
+
span.setAttributes(user);
|
|
718
|
+
this.localRoots.get(traceId)?.span.setAttributes(user);
|
|
719
|
+
} else {
|
|
720
|
+
this.byTrace.delete(traceId);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
/** What every span and log in `traceId` should carry, before baggage. */
|
|
724
|
+
attributesFor(traceId) {
|
|
725
|
+
const user = traceId && this.byTrace.get(traceId) || this.globalUser;
|
|
726
|
+
return user ? { ...this.tags, ...user } : { ...this.tags };
|
|
727
|
+
}
|
|
728
|
+
noteStart(span, parent) {
|
|
729
|
+
const parentSpan = trace.getSpanContext(parent);
|
|
730
|
+
if (!parentSpan || parentSpan.isRemote) {
|
|
731
|
+
const { traceId, spanId } = span.spanContext();
|
|
732
|
+
if (!this.localRoots.has(traceId)) this.localRoots.set(traceId, { spanId, span });
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
noteEnd(span) {
|
|
736
|
+
const { traceId, spanId } = span.spanContext();
|
|
737
|
+
if (this.localRoots.get(traceId)?.spanId !== spanId) return;
|
|
738
|
+
this.localRoots.delete(traceId);
|
|
739
|
+
this.byTrace.delete(traceId);
|
|
740
|
+
}
|
|
741
|
+
};
|
|
742
|
+
function fromBaggage(ctx) {
|
|
743
|
+
const out = {};
|
|
744
|
+
const baggage = propagation.getBaggage(ctx);
|
|
745
|
+
if (!baggage) return out;
|
|
746
|
+
for (const key of BAGGAGE_KEYS) {
|
|
747
|
+
const value = baggage.getEntry(key)?.value;
|
|
748
|
+
if (value) out[key] = value;
|
|
749
|
+
}
|
|
750
|
+
return out;
|
|
751
|
+
}
|
|
752
|
+
var ContextSpanProcessor = class {
|
|
753
|
+
constructor(store) {
|
|
754
|
+
this.store = store;
|
|
755
|
+
}
|
|
756
|
+
store;
|
|
757
|
+
onStart(span, parentContext) {
|
|
758
|
+
try {
|
|
759
|
+
this.store.noteStart(span, parentContext);
|
|
760
|
+
span.setAttributes({ ...this.store.attributesFor(span.spanContext().traceId), ...fromBaggage(parentContext) });
|
|
761
|
+
} catch {
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
onEnd(span) {
|
|
765
|
+
this.store.noteEnd(span);
|
|
766
|
+
}
|
|
767
|
+
forceFlush() {
|
|
768
|
+
return Promise.resolve();
|
|
769
|
+
}
|
|
770
|
+
shutdown() {
|
|
771
|
+
return Promise.resolve();
|
|
772
|
+
}
|
|
773
|
+
};
|
|
774
|
+
var ContextLogProcessor = class {
|
|
775
|
+
constructor(store) {
|
|
776
|
+
this.store = store;
|
|
777
|
+
}
|
|
778
|
+
store;
|
|
779
|
+
onEmit(record, ctx) {
|
|
780
|
+
try {
|
|
781
|
+
const active = ctx ?? otelContext.active();
|
|
782
|
+
const traceId = record.spanContext?.traceId ?? trace.getSpanContext(active)?.traceId;
|
|
783
|
+
const add = { ...this.store.attributesFor(traceId), ...fromBaggage(active) };
|
|
784
|
+
for (const [key, value] of Object.entries(add)) {
|
|
785
|
+
if (record.attributes[key] === void 0) record.setAttribute(key, value);
|
|
786
|
+
}
|
|
787
|
+
} catch {
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
forceFlush() {
|
|
791
|
+
return Promise.resolve();
|
|
792
|
+
}
|
|
793
|
+
shutdown() {
|
|
794
|
+
return Promise.resolve();
|
|
795
|
+
}
|
|
796
|
+
};
|
|
797
|
+
|
|
798
|
+
// src/console.ts
|
|
799
|
+
import { format } from "util";
|
|
800
|
+
import { SeverityNumber } from "@opentelemetry/api";
|
|
801
|
+
var LEVELS = [
|
|
802
|
+
["debug", SeverityNumber.DEBUG, "DEBUG"],
|
|
803
|
+
["trace", SeverityNumber.TRACE, "TRACE"],
|
|
804
|
+
["log", SeverityNumber.INFO, "INFO"],
|
|
805
|
+
["info", SeverityNumber.INFO, "INFO"],
|
|
806
|
+
["warn", SeverityNumber.WARN, "WARN"],
|
|
807
|
+
["error", SeverityNumber.ERROR, "ERROR"]
|
|
808
|
+
];
|
|
809
|
+
var emitting = false;
|
|
810
|
+
function captureConsole(logger) {
|
|
811
|
+
const originals = /* @__PURE__ */ new Map();
|
|
812
|
+
for (const [method, severityNumber, severityText] of LEVELS) {
|
|
813
|
+
const original = console[method];
|
|
814
|
+
if (typeof original !== "function" || original.__zharp) continue;
|
|
815
|
+
originals.set(method, original);
|
|
816
|
+
const patched = function(...args) {
|
|
817
|
+
original.apply(this ?? console, args);
|
|
818
|
+
if (emitting) return;
|
|
819
|
+
emitting = true;
|
|
820
|
+
try {
|
|
821
|
+
const body = format(...args);
|
|
822
|
+
if (!body.startsWith("[Zharp]")) {
|
|
823
|
+
logger.emit({ severityNumber, severityText, body, attributes: { "log.source": "console" } });
|
|
824
|
+
}
|
|
825
|
+
} catch {
|
|
826
|
+
} finally {
|
|
827
|
+
emitting = false;
|
|
828
|
+
}
|
|
829
|
+
};
|
|
830
|
+
patched.__zharp = true;
|
|
831
|
+
console[method] = patched;
|
|
832
|
+
}
|
|
833
|
+
return () => {
|
|
834
|
+
for (const [method, original] of originals) console[method] = original;
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// ../../internal/src/debug-ids.ts
|
|
839
|
+
var DEBUG_IDS_ATTRIBUTE = "zharp.debug_ids";
|
|
840
|
+
var files = /* @__PURE__ */ new Map();
|
|
841
|
+
var parsed = /* @__PURE__ */ new Set();
|
|
842
|
+
function registry() {
|
|
843
|
+
const g2 = typeof globalThis !== "undefined" ? globalThis : void 0;
|
|
844
|
+
const value = g2 && g2.__zharpDebugIds;
|
|
845
|
+
return value && typeof value === "object" ? value : void 0;
|
|
846
|
+
}
|
|
847
|
+
function frameFile(line) {
|
|
848
|
+
const text = line.trim();
|
|
849
|
+
if (!text) return void 0;
|
|
850
|
+
let match = /^at (?:async )?(?:.*? \()?(.+?):\d+:\d+\)?$/.exec(text);
|
|
851
|
+
if (match) return clean(match[1]);
|
|
852
|
+
if (text.startsWith("at ")) return void 0;
|
|
853
|
+
match = /^(?:[^@]*@)?(.+?):\d+:\d+$/.exec(text);
|
|
854
|
+
return match ? clean(match[1]) : void 0;
|
|
855
|
+
}
|
|
856
|
+
function clean(file) {
|
|
857
|
+
if (!file || file.includes("eval at ") || file === "<anonymous>" || file === "native") return void 0;
|
|
858
|
+
return file;
|
|
859
|
+
}
|
|
860
|
+
function stackFiles(stack) {
|
|
861
|
+
const out = [];
|
|
862
|
+
for (const line of stack.split("\n")) {
|
|
863
|
+
const file = frameFile(line);
|
|
864
|
+
if (file && !out.includes(file)) out.push(file);
|
|
865
|
+
}
|
|
866
|
+
return out;
|
|
867
|
+
}
|
|
868
|
+
function refresh() {
|
|
869
|
+
const entries = registry();
|
|
870
|
+
if (!entries) return;
|
|
871
|
+
for (const stack in entries) {
|
|
872
|
+
if (parsed.has(stack)) continue;
|
|
873
|
+
parsed.add(stack);
|
|
874
|
+
const id = entries[stack];
|
|
875
|
+
if (typeof id !== "string") continue;
|
|
876
|
+
for (const line of stack.split("\n")) {
|
|
877
|
+
const file = frameFile(line);
|
|
878
|
+
if (file) {
|
|
879
|
+
files.set(file, id);
|
|
880
|
+
break;
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
function debugIdsFor(stack) {
|
|
886
|
+
if (!stack) return void 0;
|
|
887
|
+
try {
|
|
888
|
+
refresh();
|
|
889
|
+
if (files.size === 0) return void 0;
|
|
890
|
+
let out;
|
|
891
|
+
for (const file of stackFiles(stack)) {
|
|
892
|
+
const id = files.get(file);
|
|
893
|
+
if (id) (out ??= {})[file] = id;
|
|
894
|
+
}
|
|
895
|
+
return out;
|
|
896
|
+
} catch {
|
|
897
|
+
return void 0;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
function debugIdAttributes(stack) {
|
|
901
|
+
const ids = debugIdsFor(stack);
|
|
902
|
+
return ids ? { [DEBUG_IDS_ATTRIBUTE]: JSON.stringify(ids) } : {};
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
// src/debug-ids.ts
|
|
906
|
+
var STACK = "exception.stacktrace";
|
|
907
|
+
var DebugIdSpanProcessor = class {
|
|
908
|
+
onStart(_span, _parentContext) {
|
|
909
|
+
}
|
|
910
|
+
/** Exception events are added while the span runs; by its end they are all there. */
|
|
911
|
+
onEnd(span) {
|
|
912
|
+
try {
|
|
913
|
+
for (const event of span.events) {
|
|
914
|
+
const attributes = event.attributes;
|
|
915
|
+
if (event.name !== "exception" || !attributes || attributes[DEBUG_IDS_ATTRIBUTE] !== void 0) continue;
|
|
916
|
+
const stack = attributes[STACK];
|
|
917
|
+
const ids = typeof stack === "string" ? debugIdsFor(stack) : void 0;
|
|
918
|
+
if (ids) attributes[DEBUG_IDS_ATTRIBUTE] = JSON.stringify(ids);
|
|
919
|
+
}
|
|
920
|
+
} catch {
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
forceFlush() {
|
|
924
|
+
return Promise.resolve();
|
|
925
|
+
}
|
|
926
|
+
shutdown() {
|
|
927
|
+
return Promise.resolve();
|
|
928
|
+
}
|
|
929
|
+
};
|
|
930
|
+
var DebugIdLogProcessor = class {
|
|
931
|
+
onEmit(record, _ctx) {
|
|
932
|
+
try {
|
|
933
|
+
const attributes = record.attributes;
|
|
934
|
+
const stack = attributes[STACK];
|
|
935
|
+
if (typeof stack !== "string" || attributes[DEBUG_IDS_ATTRIBUTE] !== void 0) return;
|
|
936
|
+
const ids = debugIdsFor(stack);
|
|
937
|
+
if (ids) record.setAttribute(DEBUG_IDS_ATTRIBUTE, JSON.stringify(ids));
|
|
938
|
+
} catch {
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
forceFlush() {
|
|
942
|
+
return Promise.resolve();
|
|
943
|
+
}
|
|
944
|
+
shutdown() {
|
|
945
|
+
return Promise.resolve();
|
|
946
|
+
}
|
|
947
|
+
};
|
|
948
|
+
|
|
949
|
+
// src/errors.ts
|
|
950
|
+
import { inspect } from "util";
|
|
951
|
+
var SEVERITY = { trace: 1, debug: 5, info: 9, warn: 13, error: 17, fatal: 21 };
|
|
952
|
+
function asError(value) {
|
|
953
|
+
if (value instanceof Error) return value;
|
|
954
|
+
if (value && typeof value === "object" && typeof value.message === "string") {
|
|
955
|
+
const error2 = new Error(value.message);
|
|
956
|
+
error2.name = typeof value.name === "string" ? value.name : "Error";
|
|
957
|
+
if (typeof value.stack === "string") error2.stack = value.stack;
|
|
958
|
+
return error2;
|
|
959
|
+
}
|
|
960
|
+
const text = typeof value === "string" ? value : inspect(value, { depth: 3, breakLength: Infinity });
|
|
961
|
+
const error = new Error(`Non-Error thrown: ${text}`);
|
|
962
|
+
return error;
|
|
963
|
+
}
|
|
964
|
+
function typeOf(error) {
|
|
965
|
+
const name = error.name && error.name !== "Error" ? error.name : error.constructor?.name;
|
|
966
|
+
return name || "Error";
|
|
967
|
+
}
|
|
968
|
+
function exceptionAttributes(error, handled) {
|
|
969
|
+
const type = typeOf(error);
|
|
970
|
+
const message = error.message || "";
|
|
971
|
+
let stack = typeof error.stack === "string" && error.stack ? error.stack : `${type}: ${message}`;
|
|
972
|
+
const cause = error.cause;
|
|
973
|
+
if (cause instanceof Error && cause.stack) stack += `
|
|
974
|
+
Caused by: ${cause.stack}`;
|
|
975
|
+
return {
|
|
976
|
+
"exception.type": type,
|
|
977
|
+
"exception.message": message,
|
|
978
|
+
"exception.stacktrace": stack,
|
|
979
|
+
"zharp.handled": handled ? "true" : "false",
|
|
980
|
+
...debugIdAttributes(stack)
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
// src/version.ts
|
|
985
|
+
var VERSION = "0.2.0";
|
|
986
|
+
|
|
987
|
+
// src/zharp.ts
|
|
988
|
+
var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
|
|
989
|
+
var EXIT_FLUSH_MS = 2e3;
|
|
990
|
+
var ZharpNode = class {
|
|
991
|
+
sdk = null;
|
|
992
|
+
spanProcessors = [];
|
|
993
|
+
logProcessors = [];
|
|
994
|
+
logger = null;
|
|
995
|
+
store = new ContextStore();
|
|
996
|
+
teardowns = [];
|
|
997
|
+
/** False in logs-only mode (`tracing: false` / `ZHARP_TRACING=false`). */
|
|
998
|
+
tracing = true;
|
|
999
|
+
/** Errors already sent, so one that is both rejected and then thrown is reported once. */
|
|
1000
|
+
reported = /* @__PURE__ */ new WeakSet();
|
|
1001
|
+
/** `Zharp.log.info("Order placed", { orderId })` — and debug, warn, error, fatal, trace. */
|
|
1002
|
+
log = {
|
|
1003
|
+
trace: (m, a) => this.emit("trace", m, a),
|
|
1004
|
+
debug: (m, a) => this.emit("debug", m, a),
|
|
1005
|
+
info: (m, a) => this.emit("info", m, a),
|
|
1006
|
+
warn: (m, a) => this.emit("warn", m, a),
|
|
1007
|
+
error: (m, a) => this.emit("error", m, a),
|
|
1008
|
+
fatal: (m, a) => this.emit("fatal", m, a)
|
|
1009
|
+
};
|
|
1010
|
+
/** Whether `init()` started the SDK. */
|
|
1011
|
+
get isActive() {
|
|
1012
|
+
return this.sdk !== null;
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Start sending traces, logs and errors. Call it once, before the application's own modules
|
|
1016
|
+
* load — from a file preloaded with `node --import` (see the README) — so that http, the
|
|
1017
|
+
* database drivers and the frameworks are instrumented when they are first imported.
|
|
1018
|
+
*/
|
|
1019
|
+
init(options = {}) {
|
|
1020
|
+
try {
|
|
1021
|
+
this.start(options);
|
|
1022
|
+
} catch (error) {
|
|
1023
|
+
warn(`Could not start: ${error?.message ?? error}`);
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
start(options) {
|
|
1027
|
+
if (this.sdk) {
|
|
1028
|
+
warn("Zharp.init() was called again \u2014 the first call's settings stay in effect.");
|
|
1029
|
+
return;
|
|
1030
|
+
}
|
|
1031
|
+
if (disabledByEnv()) {
|
|
1032
|
+
announce("Disabled by ZHARP_DISABLED \u2014 nothing will be sent");
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
const key = pick(options.key, nodeEnv("ZHARP_API_KEY"), nodeEnv("ZHARP_KEY"));
|
|
1036
|
+
if (!key) {
|
|
1037
|
+
warn("No key found \u2014 pass Zharp.init({ key }) or set ZHARP_API_KEY. Nothing will be sent.");
|
|
1038
|
+
return;
|
|
1039
|
+
}
|
|
1040
|
+
const service = pick(options.service, nodeEnv("ZHARP_SERVICE"), nodeEnv("OTEL_SERVICE_NAME"), packageName()) ?? "node-app";
|
|
1041
|
+
const environment = pick(options.environment, nodeEnv("ZHARP_ENV"), nodeEnv("NODE_ENV"));
|
|
1042
|
+
const release = pick(options.release, nodeEnv("ZHARP_RELEASE"), nodeEnv("ZHARP_VERSION"));
|
|
1043
|
+
const endpoint = (pick(options.endpoint, nodeEnv("ZHARP_ENDPOINT")) ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
|
|
1044
|
+
const tracing = tracingEnabled(options.tracing);
|
|
1045
|
+
this.tracing = tracing;
|
|
1046
|
+
if (options.debug) {
|
|
1047
|
+
const out = { error: console.error, warn: console.warn, info: console.info, debug: console.debug, verbose: console.debug };
|
|
1048
|
+
const prefixed = Object.fromEntries(
|
|
1049
|
+
Object.entries(out).map(([level, fn]) => [level, (message, ...args) => fn.call(console, `[Zharp][otel] ${message}`, ...args)])
|
|
1050
|
+
);
|
|
1051
|
+
diag.setLogger(prefixed, DiagLogLevel.DEBUG);
|
|
1052
|
+
}
|
|
1053
|
+
registerEsmHook();
|
|
1054
|
+
const headers = { Authorization: `Bearer ${key}` };
|
|
1055
|
+
const exporterOptions = { headers, compression: "gzip" };
|
|
1056
|
+
this.spanProcessors = tracing ? [
|
|
1057
|
+
new ContextSpanProcessor(this.store),
|
|
1058
|
+
new UrlRedactionSpanProcessor(),
|
|
1059
|
+
new DebugIdSpanProcessor(),
|
|
1060
|
+
new BatchSpanProcessor({ exporter: new OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) })
|
|
1061
|
+
] : [new ContextSpanProcessor(this.store)];
|
|
1062
|
+
this.logProcessors = [
|
|
1063
|
+
new ContextLogProcessor(this.store),
|
|
1064
|
+
new DebugIdLogProcessor(),
|
|
1065
|
+
new BatchLogRecordProcessor({ exporter: new OTLPLogExporter({ ...exporterOptions, url: `${endpoint}/v1/logs` }) })
|
|
1066
|
+
];
|
|
1067
|
+
const resource = resourceFromAttributes({
|
|
1068
|
+
"service.name": service,
|
|
1069
|
+
...release ? { "service.version": release } : {},
|
|
1070
|
+
...environment ? { "deployment.environment.name": environment } : {},
|
|
1071
|
+
"telemetry.sdk.name": "zharp",
|
|
1072
|
+
"telemetry.sdk.language": "nodejs",
|
|
1073
|
+
"telemetry.sdk.version": VERSION,
|
|
1074
|
+
"process.runtime.name": "nodejs",
|
|
1075
|
+
"process.runtime.version": process.versions.node
|
|
1076
|
+
});
|
|
1077
|
+
const propagator = new CompositePropagator({
|
|
1078
|
+
propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()]
|
|
1079
|
+
});
|
|
1080
|
+
const bodies = bodySettings(options.captureBodies, nodeEnv("ZHARP_CAPTURE_BODIES"));
|
|
1081
|
+
const rate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
|
|
1082
|
+
this.sdk = new NodeSDK({
|
|
1083
|
+
resource,
|
|
1084
|
+
// Host and OTEL_RESOURCE_ATTRIBUTES only. The process detector would send the command line,
|
|
1085
|
+
// which is where secrets passed as arguments live.
|
|
1086
|
+
resourceDetectors: [envDetector, hostDetector],
|
|
1087
|
+
sampler: tracing ? new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(rate) }) : new RecordOnlySampler(),
|
|
1088
|
+
textMapPropagator: tracing ? propagator : new ExtractOnlyPropagator(propagator),
|
|
1089
|
+
spanProcessors: this.spanProcessors,
|
|
1090
|
+
logRecordProcessors: this.logProcessors,
|
|
1091
|
+
// Without this the SDK would start an OTLP metrics exporter pointed at localhost:4318.
|
|
1092
|
+
metricReaders: [],
|
|
1093
|
+
instrumentations: [
|
|
1094
|
+
...tracing ? getNodeAutoInstrumentations({
|
|
1095
|
+
// A span per DNS lookup, socket and file read buries the requests that matter.
|
|
1096
|
+
"@opentelemetry/instrumentation-dns": { enabled: false },
|
|
1097
|
+
"@opentelemetry/instrumentation-net": { enabled: false },
|
|
1098
|
+
"@opentelemetry/instrumentation-fs": { enabled: false },
|
|
1099
|
+
...options.instrumentations,
|
|
1100
|
+
...bodies && {
|
|
1101
|
+
"@opentelemetry/instrumentation-http": withBodyCapture(bodies, options.instrumentations?.["@opentelemetry/instrumentation-http"])
|
|
1102
|
+
}
|
|
1103
|
+
}) : logsOnlyInstrumentations(options),
|
|
1104
|
+
...options.extraInstrumentations ?? []
|
|
1105
|
+
]
|
|
1106
|
+
});
|
|
1107
|
+
this.sdk.start();
|
|
1108
|
+
this.logger = logs.getLogger("@zharp/node", VERSION);
|
|
1109
|
+
if (options.captureConsole !== false) this.teardowns.push(captureConsole(this.logger));
|
|
1110
|
+
if (options.captureUncaught !== false) this.teardowns.push(this.captureProcessErrors());
|
|
1111
|
+
this.teardowns.push(this.flushOnExit());
|
|
1112
|
+
announce(`Application monitoring active${tracing ? "" : " (logs only)"} \u2014 ${describeTarget(service, environment)}`);
|
|
1113
|
+
}
|
|
1114
|
+
/**
|
|
1115
|
+
* The user the current request is for: `enduser.id` (and `enduser.email`, `enduser.name`) on
|
|
1116
|
+
* every span and log of the request from here on, and on the request's own span. Outside a
|
|
1117
|
+
* request it applies to everything the process sends — for a script or a worker that runs as
|
|
1118
|
+
* one user.
|
|
1119
|
+
*
|
|
1120
|
+
* Requests from a page running @zharp/browser already carry the user in their baggage; this
|
|
1121
|
+
* is for servers that know the user themselves.
|
|
1122
|
+
*/
|
|
1123
|
+
setUser(user) {
|
|
1124
|
+
try {
|
|
1125
|
+
this.store.setUser(user && user.id != null && user.id !== "" ? userAttributes(user) : null);
|
|
1126
|
+
} catch {
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
/** Forget the user — for the current request, or the process's when called outside one. */
|
|
1130
|
+
clearUser() {
|
|
1131
|
+
this.setUser(null);
|
|
1132
|
+
}
|
|
1133
|
+
/** An attribute on every span and log sent from now on, e.g. `setTag("region", "eu-west-1")`. */
|
|
1134
|
+
setTag(key, value) {
|
|
1135
|
+
if (value === null || value === void 0) delete this.store.tags[key];
|
|
1136
|
+
else this.store.tags[key] = value;
|
|
1137
|
+
}
|
|
1138
|
+
/**
|
|
1139
|
+
* Report an error you caught. It is sent as handled, in the trace of the request it happened
|
|
1140
|
+
* in, and grouped into an issue with every other occurrence.
|
|
1141
|
+
*/
|
|
1142
|
+
captureError(error, attributes) {
|
|
1143
|
+
this.report(error, true, "error", attributes);
|
|
1144
|
+
}
|
|
1145
|
+
/**
|
|
1146
|
+
* Run `fn` inside a span named `name`, which ends when `fn` returns or its promise settles. A
|
|
1147
|
+
* throw or rejection marks the span as failed and is passed on unchanged.
|
|
1148
|
+
*/
|
|
1149
|
+
startSpan(name, fn, options = {}) {
|
|
1150
|
+
if (!this.tracing) return fn(trace2.wrapSpanContext(trace2.getActiveSpan()?.spanContext() ?? INVALID_SPAN_CONTEXT));
|
|
1151
|
+
const tracer = trace2.getTracer("@zharp/node", VERSION);
|
|
1152
|
+
return tracer.startActiveSpan(name, options, (span) => {
|
|
1153
|
+
const fail = (error) => {
|
|
1154
|
+
span.setStatus({ code: SpanStatusCode.ERROR, message: asError(error).message });
|
|
1155
|
+
span.end();
|
|
1156
|
+
};
|
|
1157
|
+
let result;
|
|
1158
|
+
try {
|
|
1159
|
+
result = fn(span);
|
|
1160
|
+
} catch (error) {
|
|
1161
|
+
fail(error);
|
|
1162
|
+
throw error;
|
|
1163
|
+
}
|
|
1164
|
+
if (result && typeof result.then === "function") {
|
|
1165
|
+
return result.then(
|
|
1166
|
+
(value) => {
|
|
1167
|
+
span.end();
|
|
1168
|
+
return value;
|
|
1169
|
+
},
|
|
1170
|
+
(error) => {
|
|
1171
|
+
fail(error);
|
|
1172
|
+
throw error;
|
|
1173
|
+
}
|
|
1174
|
+
);
|
|
1175
|
+
}
|
|
1176
|
+
span.end();
|
|
1177
|
+
return result;
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
/** Send everything waiting now. Await it before a serverless function returns. */
|
|
1181
|
+
async flush(timeoutMs = 5e3) {
|
|
1182
|
+
const all = Promise.all([...this.spanProcessors, ...this.logProcessors].map((p) => p.forceFlush().catch(() => {
|
|
1183
|
+
})));
|
|
1184
|
+
await Promise.race([all, new Promise((resolve) => setTimeout(resolve, timeoutMs).unref())]);
|
|
1185
|
+
}
|
|
1186
|
+
/** Flush, stop, and put back everything that was patched. */
|
|
1187
|
+
async shutdown() {
|
|
1188
|
+
const sdk = this.sdk;
|
|
1189
|
+
if (!sdk) return;
|
|
1190
|
+
this.sdk = null;
|
|
1191
|
+
for (const undo of this.teardowns.splice(0)) undo();
|
|
1192
|
+
await sdk.shutdown().catch(() => {
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
// ── internals ─────────────────────────────────────────────────────────
|
|
1196
|
+
emit(level, message, attributes) {
|
|
1197
|
+
try {
|
|
1198
|
+
if (!this.logger) return;
|
|
1199
|
+
const extra = {};
|
|
1200
|
+
for (const [key, value] of Object.entries(attributes ?? {})) {
|
|
1201
|
+
if (value instanceof Error && (level === "error" || level === "fatal") && !extra["exception.type"]) {
|
|
1202
|
+
Object.assign(extra, exceptionAttributes(value, true));
|
|
1203
|
+
} else {
|
|
1204
|
+
extra[key] = value instanceof Error ? `${value.name}: ${value.message}` : value;
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
this.logger.emit({
|
|
1208
|
+
severityNumber: SEVERITY[level],
|
|
1209
|
+
severityText: level.toUpperCase(),
|
|
1210
|
+
body: typeof message === "string" ? message : message instanceof Error ? message.message : safeJson(message),
|
|
1211
|
+
attributes: extra
|
|
1212
|
+
});
|
|
1213
|
+
} catch {
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
report(value, handled, level, attributes) {
|
|
1217
|
+
try {
|
|
1218
|
+
if (!this.logger) return;
|
|
1219
|
+
const error = asError(value);
|
|
1220
|
+
if (value && typeof value === "object") {
|
|
1221
|
+
if (this.reported.has(value)) return;
|
|
1222
|
+
this.reported.add(value);
|
|
1223
|
+
}
|
|
1224
|
+
const exception = exceptionAttributes(error, handled);
|
|
1225
|
+
this.logger.emit({
|
|
1226
|
+
severityNumber: SEVERITY[level],
|
|
1227
|
+
severityText: level.toUpperCase(),
|
|
1228
|
+
body: `${exception["exception.type"]}: ${exception["exception.message"]}`,
|
|
1229
|
+
attributes: { ...attributes, ...exception }
|
|
1230
|
+
});
|
|
1231
|
+
if (!handled) trace2.getActiveSpan()?.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
|
|
1232
|
+
} catch {
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
/**
|
|
1236
|
+
* Uncaught exceptions and unhandled rejections, reported as unhandled.
|
|
1237
|
+
*
|
|
1238
|
+
* Listening for either changes what Node does — it no longer exits — so when Zharp's listener
|
|
1239
|
+
* is the only one, it finishes the job the way Node would have: print the error, then exit
|
|
1240
|
+
* with code 1, after the error has been sent. When the application has listeners of its own,
|
|
1241
|
+
* they decide, and Zharp only reports.
|
|
1242
|
+
*/
|
|
1243
|
+
captureProcessErrors() {
|
|
1244
|
+
const onException = (error, origin) => {
|
|
1245
|
+
this.report(error, false, "fatal", origin ? { "zharp.mechanism": origin } : void 0);
|
|
1246
|
+
if (process.listenerCount("uncaughtException") > 1) return;
|
|
1247
|
+
this.crash(error);
|
|
1248
|
+
};
|
|
1249
|
+
const onRejection = (reason) => {
|
|
1250
|
+
this.report(reason, false, "error", { "zharp.mechanism": "unhandledRejection" });
|
|
1251
|
+
if (process.listenerCount("unhandledRejection") > 1) return;
|
|
1252
|
+
const mode = unhandledRejectionsMode();
|
|
1253
|
+
if (mode === "warn" || mode === "none") return;
|
|
1254
|
+
if (mode === "warn-with-error-code") {
|
|
1255
|
+
process.exitCode = 1;
|
|
1256
|
+
return;
|
|
1257
|
+
}
|
|
1258
|
+
this.crash(reason);
|
|
1259
|
+
};
|
|
1260
|
+
process.on("uncaughtException", onException);
|
|
1261
|
+
process.on("unhandledRejection", onRejection);
|
|
1262
|
+
return () => {
|
|
1263
|
+
process.off("uncaughtException", onException);
|
|
1264
|
+
process.off("unhandledRejection", onRejection);
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
crashing = false;
|
|
1268
|
+
crash(error) {
|
|
1269
|
+
if (this.crashing) return;
|
|
1270
|
+
this.crashing = true;
|
|
1271
|
+
try {
|
|
1272
|
+
const text = error instanceof Error ? error.stack || String(error) : `Uncaught ${safeJson(error)}`;
|
|
1273
|
+
process.stderr.write(`${text}
|
|
1274
|
+
|
|
1275
|
+
Node.js ${process.version}
|
|
1276
|
+
`);
|
|
1277
|
+
} catch {
|
|
1278
|
+
}
|
|
1279
|
+
this.flush(EXIT_FLUSH_MS).finally(() => process.exit(1));
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* Send what is waiting when the process ends on its own (the event loop drains) or is told to
|
|
1283
|
+
* stop. A signal listener also replaces Node's default of exiting, so once the flush is done,
|
|
1284
|
+
* if no one else is listening, the signal is raised again with Zharp's listener gone.
|
|
1285
|
+
*/
|
|
1286
|
+
flushOnExit() {
|
|
1287
|
+
let flushing = false;
|
|
1288
|
+
const onBeforeExit = () => {
|
|
1289
|
+
if (flushing) return;
|
|
1290
|
+
flushing = true;
|
|
1291
|
+
this.flush(EXIT_FLUSH_MS).finally(() => flushing = false);
|
|
1292
|
+
};
|
|
1293
|
+
process.on("beforeExit", onBeforeExit);
|
|
1294
|
+
const signals = ["SIGTERM", "SIGINT"];
|
|
1295
|
+
const handlers = signals.map((signal) => {
|
|
1296
|
+
const handler = () => {
|
|
1297
|
+
this.flush(EXIT_FLUSH_MS).finally(() => {
|
|
1298
|
+
process.off(signal, handler);
|
|
1299
|
+
if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
|
|
1300
|
+
});
|
|
1301
|
+
};
|
|
1302
|
+
process.on(signal, handler);
|
|
1303
|
+
return [signal, handler];
|
|
1304
|
+
});
|
|
1305
|
+
return () => {
|
|
1306
|
+
process.off("beforeExit", onBeforeExit);
|
|
1307
|
+
for (const [signal, handler] of handlers) process.off(signal, handler);
|
|
1308
|
+
};
|
|
1309
|
+
}
|
|
1310
|
+
};
|
|
1311
|
+
function unhandledRejectionsMode() {
|
|
1312
|
+
const flags = [...process.execArgv, ...(process.env.NODE_OPTIONS ?? "").split(/\s+/)];
|
|
1313
|
+
for (const flag of flags) {
|
|
1314
|
+
const match = /^--unhandled-rejections=(.+)$/.exec(flag);
|
|
1315
|
+
if (match) return match[1];
|
|
1316
|
+
}
|
|
1317
|
+
return "throw";
|
|
1318
|
+
}
|
|
1319
|
+
function safeJson(value) {
|
|
1320
|
+
try {
|
|
1321
|
+
return typeof value === "string" ? value : JSON.stringify(value) ?? String(value);
|
|
1322
|
+
} catch {
|
|
1323
|
+
return String(value);
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
function registerEsmHook() {
|
|
1327
|
+
const g2 = globalThis;
|
|
1328
|
+
if (g2.__ZHARP_ESM_HOOK__) return;
|
|
1329
|
+
g2.__ZHARP_ESM_HOOK__ = true;
|
|
1330
|
+
try {
|
|
1331
|
+
registerLoader?.("@opentelemetry/instrumentation/hook.mjs", import.meta.url);
|
|
1332
|
+
} catch {
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
function tracingEnabled(option) {
|
|
1336
|
+
if (typeof option === "boolean") return option;
|
|
1337
|
+
const value = nodeEnv("ZHARP_TRACING");
|
|
1338
|
+
return !(value && /^(false|0|no|off)$/i.test(value));
|
|
1339
|
+
}
|
|
1340
|
+
function logsOnlyInstrumentations(options) {
|
|
1341
|
+
const previous = process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS;
|
|
1342
|
+
process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS = "http,pino,winston,bunyan";
|
|
1343
|
+
try {
|
|
1344
|
+
return getNodeAutoInstrumentations({
|
|
1345
|
+
...options.instrumentations,
|
|
1346
|
+
"@opentelemetry/instrumentation-http": {
|
|
1347
|
+
...options.instrumentations?.["@opentelemetry/instrumentation-http"],
|
|
1348
|
+
disableOutgoingRequestInstrumentation: true
|
|
1349
|
+
}
|
|
1350
|
+
});
|
|
1351
|
+
} finally {
|
|
1352
|
+
if (previous === void 0) delete process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS;
|
|
1353
|
+
else process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS = previous;
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
var RecordOnlySampler = class {
|
|
1357
|
+
shouldSample() {
|
|
1358
|
+
return { decision: SamplingDecision.RECORD };
|
|
1359
|
+
}
|
|
1360
|
+
toString() {
|
|
1361
|
+
return "ZharpRecordOnlySampler";
|
|
1362
|
+
}
|
|
1363
|
+
};
|
|
1364
|
+
var ExtractOnlyPropagator = class {
|
|
1365
|
+
constructor(inner) {
|
|
1366
|
+
this.inner = inner;
|
|
1367
|
+
}
|
|
1368
|
+
inner;
|
|
1369
|
+
inject() {
|
|
1370
|
+
}
|
|
1371
|
+
extract(context, carrier, getter) {
|
|
1372
|
+
return this.inner.extract(context, carrier, getter);
|
|
1373
|
+
}
|
|
1374
|
+
fields() {
|
|
1375
|
+
return [];
|
|
1376
|
+
}
|
|
1377
|
+
};
|
|
1378
|
+
|
|
1379
|
+
// src/index.ts
|
|
1380
|
+
var g = globalThis;
|
|
1381
|
+
var Zharp = g.__ZHARP_NODE__ ?? (g.__ZHARP_NODE__ = new ZharpNode());
|
|
1382
|
+
var index_default = Zharp;
|
|
1383
|
+
export {
|
|
1384
|
+
VERSION,
|
|
1385
|
+
Zharp,
|
|
1386
|
+
ZharpNode,
|
|
1387
|
+
index_default as default
|
|
1388
|
+
};
|
|
1389
|
+
//# sourceMappingURL=index.mjs.map
|