@zharp/node 0.0.0-stage → 0.1.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/dist/index.js ADDED
@@ -0,0 +1,802 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ VERSION: () => VERSION,
24
+ Zharp: () => Zharp,
25
+ ZharpNode: () => ZharpNode,
26
+ default: () => index_default
27
+ });
28
+ module.exports = __toCommonJS(index_exports);
29
+
30
+ // ../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.26_typescript@5.9.3_yaml@2.9.1/node_modules/tsup/assets/cjs_shims.js
31
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
32
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
33
+
34
+ // src/zharp.ts
35
+ var import_node_module = require("module");
36
+ var import_api3 = require("@opentelemetry/api");
37
+ var import_core = require("@opentelemetry/core");
38
+ var import_resources = require("@opentelemetry/resources");
39
+ var import_sdk_node = require("@opentelemetry/sdk-node");
40
+ var import_sdk_trace = require("@opentelemetry/sdk-trace");
41
+ var import_sdk_logs = require("@opentelemetry/sdk-logs");
42
+ var import_exporter_trace_otlp_proto = require("@opentelemetry/exporter-trace-otlp-proto");
43
+ var import_exporter_logs_otlp_proto = require("@opentelemetry/exporter-logs-otlp-proto");
44
+ var import_auto_instrumentations_node = require("@opentelemetry/auto-instrumentations-node");
45
+
46
+ // ../../internal/src/builtins.ts
47
+ function loadBuiltin(name) {
48
+ try {
49
+ const proc = typeof process !== "undefined" ? process : void 0;
50
+ if (proc && typeof proc.getBuiltinModule === "function") {
51
+ return proc.getBuiltinModule(`node:${name}`) ?? null;
52
+ }
53
+ const req = typeof module !== "undefined" && typeof require === "function" ? require : null;
54
+ return req ? req(name) : null;
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ // ../../internal/src/env.ts
61
+ function nodeEnv(name) {
62
+ if (typeof window !== "undefined" || typeof process === "undefined" || !process.env) return void 0;
63
+ const value = process.env[name];
64
+ return value && value.trim() ? value.trim() : void 0;
65
+ }
66
+ function packageName() {
67
+ if (typeof window !== "undefined" || typeof process === "undefined") return void 0;
68
+ const fs = loadBuiltin("fs");
69
+ const path = loadBuiltin("path");
70
+ if (!fs || !path) return void 0;
71
+ const starts = [process.argv?.[1] ? path.dirname(path.resolve(process.argv[1])) : "", process.cwd?.() ?? ""];
72
+ for (const start of starts.filter(Boolean)) {
73
+ let dir = start;
74
+ for (let i = 0; i < 12; i++) {
75
+ if (path.basename(dir) !== "node_modules") {
76
+ try {
77
+ const name = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"))?.name;
78
+ if (typeof name === "string" && name.trim()) return name.trim().replace(/^@[^/]+\//, "");
79
+ } catch {
80
+ }
81
+ }
82
+ const parent = path.dirname(dir);
83
+ if (parent === dir) break;
84
+ dir = parent;
85
+ }
86
+ }
87
+ return void 0;
88
+ }
89
+ function disabledByEnv() {
90
+ const value = nodeEnv("ZHARP_DISABLED");
91
+ return !!value && /^(true|1|yes|on)$/i.test(value);
92
+ }
93
+ function pick(...values) {
94
+ for (const value of values) {
95
+ if (typeof value === "string" && value.trim()) return value.trim();
96
+ }
97
+ return void 0;
98
+ }
99
+ function describeTarget(service, environment) {
100
+ return `service "${service}", ${environment ? `environment "${environment}"` : "no environment set"}`;
101
+ }
102
+ function announce(message) {
103
+ console.info(`[Zharp] ${message}`);
104
+ }
105
+ function warn(message) {
106
+ console.warn(`[Zharp] ${message}`);
107
+ }
108
+
109
+ // src/context.ts
110
+ var import_api = require("@opentelemetry/api");
111
+ var BAGGAGE_KEYS = ["enduser.id", "session.id"];
112
+ function userAttributes(user) {
113
+ const out = { "enduser.id": String(user.id) };
114
+ if (user.email) out["enduser.email"] = String(user.email);
115
+ if (user.name) out["enduser.name"] = String(user.name);
116
+ return out;
117
+ }
118
+ var ContextStore = class {
119
+ /** Set outside any request: a script or worker that is one user's work throughout. */
120
+ globalUser = null;
121
+ tags = {};
122
+ byTrace = /* @__PURE__ */ new Map();
123
+ /** The first span of each trace in this process, which the user is also written onto. */
124
+ localRoots = /* @__PURE__ */ new Map();
125
+ /** Set the user for the request in progress, or for the whole process outside one. */
126
+ setUser(user) {
127
+ const span = import_api.trace.getActiveSpan();
128
+ const traceId = span?.spanContext().traceId;
129
+ if (!span || !traceId) {
130
+ this.globalUser = user;
131
+ return;
132
+ }
133
+ if (user) {
134
+ this.byTrace.set(traceId, user);
135
+ span.setAttributes(user);
136
+ this.localRoots.get(traceId)?.span.setAttributes(user);
137
+ } else {
138
+ this.byTrace.delete(traceId);
139
+ }
140
+ }
141
+ /** What every span and log in `traceId` should carry, before baggage. */
142
+ attributesFor(traceId) {
143
+ const user = traceId && this.byTrace.get(traceId) || this.globalUser;
144
+ return user ? { ...this.tags, ...user } : { ...this.tags };
145
+ }
146
+ noteStart(span, parent) {
147
+ const parentSpan = import_api.trace.getSpanContext(parent);
148
+ if (!parentSpan || parentSpan.isRemote) {
149
+ const { traceId, spanId } = span.spanContext();
150
+ if (!this.localRoots.has(traceId)) this.localRoots.set(traceId, { spanId, span });
151
+ }
152
+ }
153
+ noteEnd(span) {
154
+ const { traceId, spanId } = span.spanContext();
155
+ if (this.localRoots.get(traceId)?.spanId !== spanId) return;
156
+ this.localRoots.delete(traceId);
157
+ this.byTrace.delete(traceId);
158
+ }
159
+ };
160
+ function fromBaggage(ctx) {
161
+ const out = {};
162
+ const baggage = import_api.propagation.getBaggage(ctx);
163
+ if (!baggage) return out;
164
+ for (const key of BAGGAGE_KEYS) {
165
+ const value = baggage.getEntry(key)?.value;
166
+ if (value) out[key] = value;
167
+ }
168
+ return out;
169
+ }
170
+ var ContextSpanProcessor = class {
171
+ constructor(store) {
172
+ this.store = store;
173
+ }
174
+ store;
175
+ onStart(span, parentContext) {
176
+ try {
177
+ this.store.noteStart(span, parentContext);
178
+ span.setAttributes({ ...this.store.attributesFor(span.spanContext().traceId), ...fromBaggage(parentContext) });
179
+ } catch {
180
+ }
181
+ }
182
+ onEnd(span) {
183
+ this.store.noteEnd(span);
184
+ }
185
+ forceFlush() {
186
+ return Promise.resolve();
187
+ }
188
+ shutdown() {
189
+ return Promise.resolve();
190
+ }
191
+ };
192
+ var ContextLogProcessor = class {
193
+ constructor(store) {
194
+ this.store = store;
195
+ }
196
+ store;
197
+ onEmit(record, ctx) {
198
+ try {
199
+ const active = ctx ?? import_api.context.active();
200
+ const traceId = record.spanContext?.traceId ?? import_api.trace.getSpanContext(active)?.traceId;
201
+ const add = { ...this.store.attributesFor(traceId), ...fromBaggage(active) };
202
+ for (const [key, value] of Object.entries(add)) {
203
+ if (record.attributes[key] === void 0) record.setAttribute(key, value);
204
+ }
205
+ } catch {
206
+ }
207
+ }
208
+ forceFlush() {
209
+ return Promise.resolve();
210
+ }
211
+ shutdown() {
212
+ return Promise.resolve();
213
+ }
214
+ };
215
+
216
+ // src/console.ts
217
+ var import_node_util = require("util");
218
+ var import_api2 = require("@opentelemetry/api");
219
+ var LEVELS = [
220
+ ["debug", import_api2.SeverityNumber.DEBUG, "DEBUG"],
221
+ ["trace", import_api2.SeverityNumber.TRACE, "TRACE"],
222
+ ["log", import_api2.SeverityNumber.INFO, "INFO"],
223
+ ["info", import_api2.SeverityNumber.INFO, "INFO"],
224
+ ["warn", import_api2.SeverityNumber.WARN, "WARN"],
225
+ ["error", import_api2.SeverityNumber.ERROR, "ERROR"]
226
+ ];
227
+ var emitting = false;
228
+ function captureConsole(logger) {
229
+ const originals = /* @__PURE__ */ new Map();
230
+ for (const [method, severityNumber, severityText] of LEVELS) {
231
+ const original = console[method];
232
+ if (typeof original !== "function" || original.__zharp) continue;
233
+ originals.set(method, original);
234
+ const patched = function(...args) {
235
+ original.apply(this ?? console, args);
236
+ if (emitting) return;
237
+ emitting = true;
238
+ try {
239
+ const body = (0, import_node_util.format)(...args);
240
+ if (!body.startsWith("[Zharp]")) {
241
+ logger.emit({ severityNumber, severityText, body, attributes: { "log.source": "console" } });
242
+ }
243
+ } catch {
244
+ } finally {
245
+ emitting = false;
246
+ }
247
+ };
248
+ patched.__zharp = true;
249
+ console[method] = patched;
250
+ }
251
+ return () => {
252
+ for (const [method, original] of originals) console[method] = original;
253
+ };
254
+ }
255
+
256
+ // ../../internal/src/debug-ids.ts
257
+ var DEBUG_IDS_ATTRIBUTE = "zharp.debug_ids";
258
+ var files = /* @__PURE__ */ new Map();
259
+ var parsed = /* @__PURE__ */ new Set();
260
+ function registry() {
261
+ const g2 = typeof globalThis !== "undefined" ? globalThis : void 0;
262
+ const value = g2 && g2.__zharpDebugIds;
263
+ return value && typeof value === "object" ? value : void 0;
264
+ }
265
+ function frameFile(line) {
266
+ const text = line.trim();
267
+ if (!text) return void 0;
268
+ let match = /^at (?:async )?(?:.*? \()?(.+?):\d+:\d+\)?$/.exec(text);
269
+ if (match) return clean(match[1]);
270
+ if (text.startsWith("at ")) return void 0;
271
+ match = /^(?:[^@]*@)?(.+?):\d+:\d+$/.exec(text);
272
+ return match ? clean(match[1]) : void 0;
273
+ }
274
+ function clean(file) {
275
+ if (!file || file.includes("eval at ") || file === "<anonymous>" || file === "native") return void 0;
276
+ return file;
277
+ }
278
+ function stackFiles(stack) {
279
+ const out = [];
280
+ for (const line of stack.split("\n")) {
281
+ const file = frameFile(line);
282
+ if (file && !out.includes(file)) out.push(file);
283
+ }
284
+ return out;
285
+ }
286
+ function refresh() {
287
+ const entries = registry();
288
+ if (!entries) return;
289
+ for (const stack in entries) {
290
+ if (parsed.has(stack)) continue;
291
+ parsed.add(stack);
292
+ const id = entries[stack];
293
+ if (typeof id !== "string") continue;
294
+ for (const line of stack.split("\n")) {
295
+ const file = frameFile(line);
296
+ if (file) {
297
+ files.set(file, id);
298
+ break;
299
+ }
300
+ }
301
+ }
302
+ }
303
+ function debugIdsFor(stack) {
304
+ if (!stack) return void 0;
305
+ try {
306
+ refresh();
307
+ if (files.size === 0) return void 0;
308
+ let out;
309
+ for (const file of stackFiles(stack)) {
310
+ const id = files.get(file);
311
+ if (id) (out ??= {})[file] = id;
312
+ }
313
+ return out;
314
+ } catch {
315
+ return void 0;
316
+ }
317
+ }
318
+ function debugIdAttributes(stack) {
319
+ const ids = debugIdsFor(stack);
320
+ return ids ? { [DEBUG_IDS_ATTRIBUTE]: JSON.stringify(ids) } : {};
321
+ }
322
+
323
+ // src/debug-ids.ts
324
+ var STACK = "exception.stacktrace";
325
+ var DebugIdSpanProcessor = class {
326
+ onStart(_span, _parentContext) {
327
+ }
328
+ /** Exception events are added while the span runs; by its end they are all there. */
329
+ onEnd(span) {
330
+ try {
331
+ for (const event of span.events) {
332
+ const attributes = event.attributes;
333
+ if (event.name !== "exception" || !attributes || attributes[DEBUG_IDS_ATTRIBUTE] !== void 0) continue;
334
+ const stack = attributes[STACK];
335
+ const ids = typeof stack === "string" ? debugIdsFor(stack) : void 0;
336
+ if (ids) attributes[DEBUG_IDS_ATTRIBUTE] = JSON.stringify(ids);
337
+ }
338
+ } catch {
339
+ }
340
+ }
341
+ forceFlush() {
342
+ return Promise.resolve();
343
+ }
344
+ shutdown() {
345
+ return Promise.resolve();
346
+ }
347
+ };
348
+ var DebugIdLogProcessor = class {
349
+ onEmit(record, _ctx) {
350
+ try {
351
+ const attributes = record.attributes;
352
+ const stack = attributes[STACK];
353
+ if (typeof stack !== "string" || attributes[DEBUG_IDS_ATTRIBUTE] !== void 0) return;
354
+ const ids = debugIdsFor(stack);
355
+ if (ids) record.setAttribute(DEBUG_IDS_ATTRIBUTE, JSON.stringify(ids));
356
+ } catch {
357
+ }
358
+ }
359
+ forceFlush() {
360
+ return Promise.resolve();
361
+ }
362
+ shutdown() {
363
+ return Promise.resolve();
364
+ }
365
+ };
366
+
367
+ // src/errors.ts
368
+ var import_node_util2 = require("util");
369
+ var SEVERITY = { trace: 1, debug: 5, info: 9, warn: 13, error: 17, fatal: 21 };
370
+ function asError(value) {
371
+ if (value instanceof Error) return value;
372
+ if (value && typeof value === "object" && typeof value.message === "string") {
373
+ const error2 = new Error(value.message);
374
+ error2.name = typeof value.name === "string" ? value.name : "Error";
375
+ if (typeof value.stack === "string") error2.stack = value.stack;
376
+ return error2;
377
+ }
378
+ const text = typeof value === "string" ? value : (0, import_node_util2.inspect)(value, { depth: 3, breakLength: Infinity });
379
+ const error = new Error(`Non-Error thrown: ${text}`);
380
+ return error;
381
+ }
382
+ function typeOf(error) {
383
+ const name = error.name && error.name !== "Error" ? error.name : error.constructor?.name;
384
+ return name || "Error";
385
+ }
386
+ function exceptionAttributes(error, handled) {
387
+ const type = typeOf(error);
388
+ const message = error.message || "";
389
+ let stack = typeof error.stack === "string" && error.stack ? error.stack : `${type}: ${message}`;
390
+ const cause = error.cause;
391
+ if (cause instanceof Error && cause.stack) stack += `
392
+ Caused by: ${cause.stack}`;
393
+ return {
394
+ "exception.type": type,
395
+ "exception.message": message,
396
+ "exception.stacktrace": stack,
397
+ "zharp.handled": handled ? "true" : "false",
398
+ ...debugIdAttributes(stack)
399
+ };
400
+ }
401
+
402
+ // src/version.ts
403
+ var VERSION = "0.1.0";
404
+
405
+ // src/zharp.ts
406
+ var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
407
+ var EXIT_FLUSH_MS = 2e3;
408
+ var ZharpNode = class {
409
+ sdk = null;
410
+ spanProcessors = [];
411
+ logProcessors = [];
412
+ logger = null;
413
+ store = new ContextStore();
414
+ teardowns = [];
415
+ /** False in logs-only mode (`tracing: false` / `ZHARP_TRACING=false`). */
416
+ tracing = true;
417
+ /** Errors already sent, so one that is both rejected and then thrown is reported once. */
418
+ reported = /* @__PURE__ */ new WeakSet();
419
+ /** `Zharp.log.info("Order placed", { orderId })` — and debug, warn, error, fatal, trace. */
420
+ log = {
421
+ trace: (m, a) => this.emit("trace", m, a),
422
+ debug: (m, a) => this.emit("debug", m, a),
423
+ info: (m, a) => this.emit("info", m, a),
424
+ warn: (m, a) => this.emit("warn", m, a),
425
+ error: (m, a) => this.emit("error", m, a),
426
+ fatal: (m, a) => this.emit("fatal", m, a)
427
+ };
428
+ /** Whether `init()` started the SDK. */
429
+ get isActive() {
430
+ return this.sdk !== null;
431
+ }
432
+ /**
433
+ * Start sending traces, logs and errors. Call it once, before the application's own modules
434
+ * load — from a file preloaded with `node --import` (see the README) — so that http, the
435
+ * database drivers and the frameworks are instrumented when they are first imported.
436
+ */
437
+ init(options = {}) {
438
+ try {
439
+ this.start(options);
440
+ } catch (error) {
441
+ warn(`Could not start: ${error?.message ?? error}`);
442
+ }
443
+ }
444
+ start(options) {
445
+ if (this.sdk) {
446
+ warn("Zharp.init() was called again \u2014 the first call's settings stay in effect.");
447
+ return;
448
+ }
449
+ if (disabledByEnv()) {
450
+ announce("Disabled by ZHARP_DISABLED \u2014 nothing will be sent");
451
+ return;
452
+ }
453
+ const key = pick(options.key, nodeEnv("ZHARP_API_KEY"), nodeEnv("ZHARP_KEY"));
454
+ if (!key) {
455
+ warn("No key found \u2014 pass Zharp.init({ key }) or set ZHARP_API_KEY. Nothing will be sent.");
456
+ return;
457
+ }
458
+ const service = pick(options.service, nodeEnv("ZHARP_SERVICE"), nodeEnv("OTEL_SERVICE_NAME"), packageName()) ?? "node-app";
459
+ const environment = pick(options.environment, nodeEnv("ZHARP_ENV"), nodeEnv("NODE_ENV"));
460
+ const release = pick(options.release, nodeEnv("ZHARP_RELEASE"), nodeEnv("ZHARP_VERSION"));
461
+ const endpoint = (pick(options.endpoint, nodeEnv("ZHARP_ENDPOINT")) ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
462
+ const tracing = tracingEnabled(options.tracing);
463
+ this.tracing = tracing;
464
+ if (options.debug) {
465
+ const out = { error: console.error, warn: console.warn, info: console.info, debug: console.debug, verbose: console.debug };
466
+ const prefixed = Object.fromEntries(
467
+ Object.entries(out).map(([level, fn]) => [level, (message, ...args) => fn.call(console, `[Zharp][otel] ${message}`, ...args)])
468
+ );
469
+ import_api3.diag.setLogger(prefixed, import_api3.DiagLogLevel.DEBUG);
470
+ }
471
+ registerEsmHook();
472
+ const headers = { Authorization: `Bearer ${key}` };
473
+ const exporterOptions = { headers, compression: "gzip" };
474
+ this.spanProcessors = tracing ? [
475
+ new ContextSpanProcessor(this.store),
476
+ new DebugIdSpanProcessor(),
477
+ new import_sdk_trace.BatchSpanProcessor({ exporter: new import_exporter_trace_otlp_proto.OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) })
478
+ ] : [new ContextSpanProcessor(this.store)];
479
+ this.logProcessors = [
480
+ new ContextLogProcessor(this.store),
481
+ new DebugIdLogProcessor(),
482
+ new import_sdk_logs.BatchLogRecordProcessor({ exporter: new import_exporter_logs_otlp_proto.OTLPLogExporter({ ...exporterOptions, url: `${endpoint}/v1/logs` }) })
483
+ ];
484
+ const resource = (0, import_resources.resourceFromAttributes)({
485
+ "service.name": service,
486
+ ...release ? { "service.version": release } : {},
487
+ ...environment ? { "deployment.environment.name": environment } : {},
488
+ "telemetry.sdk.name": "zharp",
489
+ "telemetry.sdk.language": "nodejs",
490
+ "telemetry.sdk.version": VERSION,
491
+ "process.runtime.name": "nodejs",
492
+ "process.runtime.version": process.versions.node
493
+ });
494
+ const propagator = new import_core.CompositePropagator({
495
+ propagators: [new import_core.W3CTraceContextPropagator(), new import_core.W3CBaggagePropagator()]
496
+ });
497
+ const rate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
498
+ this.sdk = new import_sdk_node.NodeSDK({
499
+ resource,
500
+ // Host and OTEL_RESOURCE_ATTRIBUTES only. The process detector would send the command line,
501
+ // which is where secrets passed as arguments live.
502
+ resourceDetectors: [import_resources.envDetector, import_resources.hostDetector],
503
+ sampler: tracing ? new import_sdk_trace.ParentBasedSampler({ root: new import_sdk_trace.TraceIdRatioBasedSampler(rate) }) : new RecordOnlySampler(),
504
+ textMapPropagator: tracing ? propagator : new ExtractOnlyPropagator(propagator),
505
+ spanProcessors: this.spanProcessors,
506
+ logRecordProcessors: this.logProcessors,
507
+ // Without this the SDK would start an OTLP metrics exporter pointed at localhost:4318.
508
+ metricReaders: [],
509
+ instrumentations: [
510
+ ...tracing ? (0, import_auto_instrumentations_node.getNodeAutoInstrumentations)({
511
+ // A span per DNS lookup, socket and file read buries the requests that matter.
512
+ "@opentelemetry/instrumentation-dns": { enabled: false },
513
+ "@opentelemetry/instrumentation-net": { enabled: false },
514
+ "@opentelemetry/instrumentation-fs": { enabled: false },
515
+ ...options.instrumentations
516
+ }) : logsOnlyInstrumentations(options),
517
+ ...options.extraInstrumentations ?? []
518
+ ]
519
+ });
520
+ this.sdk.start();
521
+ this.logger = import_api3.logs.getLogger("@zharp/node", VERSION);
522
+ if (options.captureConsole !== false) this.teardowns.push(captureConsole(this.logger));
523
+ if (options.captureUncaught !== false) this.teardowns.push(this.captureProcessErrors());
524
+ this.teardowns.push(this.flushOnExit());
525
+ announce(`Application monitoring active${tracing ? "" : " (logs only)"} \u2014 ${describeTarget(service, environment)}`);
526
+ }
527
+ /**
528
+ * The user the current request is for: `enduser.id` (and `enduser.email`, `enduser.name`) on
529
+ * every span and log of the request from here on, and on the request's own span. Outside a
530
+ * request it applies to everything the process sends — for a script or a worker that runs as
531
+ * one user.
532
+ *
533
+ * Requests from a page running @zharp/browser already carry the user in their baggage; this
534
+ * is for servers that know the user themselves.
535
+ */
536
+ setUser(user) {
537
+ try {
538
+ this.store.setUser(user && user.id != null && user.id !== "" ? userAttributes(user) : null);
539
+ } catch {
540
+ }
541
+ }
542
+ /** Forget the user — for the current request, or the process's when called outside one. */
543
+ clearUser() {
544
+ this.setUser(null);
545
+ }
546
+ /** An attribute on every span and log sent from now on, e.g. `setTag("region", "eu-west-1")`. */
547
+ setTag(key, value) {
548
+ if (value === null || value === void 0) delete this.store.tags[key];
549
+ else this.store.tags[key] = value;
550
+ }
551
+ /**
552
+ * Report an error you caught. It is sent as handled, in the trace of the request it happened
553
+ * in, and grouped into an issue with every other occurrence.
554
+ */
555
+ captureError(error, attributes) {
556
+ this.report(error, true, "error", attributes);
557
+ }
558
+ /**
559
+ * Run `fn` inside a span named `name`, which ends when `fn` returns or its promise settles. A
560
+ * throw or rejection marks the span as failed and is passed on unchanged.
561
+ */
562
+ startSpan(name, fn, options = {}) {
563
+ if (!this.tracing) return fn(import_api3.trace.wrapSpanContext(import_api3.trace.getActiveSpan()?.spanContext() ?? import_api3.INVALID_SPAN_CONTEXT));
564
+ const tracer = import_api3.trace.getTracer("@zharp/node", VERSION);
565
+ return tracer.startActiveSpan(name, options, (span) => {
566
+ const fail = (error) => {
567
+ span.setStatus({ code: import_api3.SpanStatusCode.ERROR, message: asError(error).message });
568
+ span.end();
569
+ };
570
+ let result;
571
+ try {
572
+ result = fn(span);
573
+ } catch (error) {
574
+ fail(error);
575
+ throw error;
576
+ }
577
+ if (result && typeof result.then === "function") {
578
+ return result.then(
579
+ (value) => {
580
+ span.end();
581
+ return value;
582
+ },
583
+ (error) => {
584
+ fail(error);
585
+ throw error;
586
+ }
587
+ );
588
+ }
589
+ span.end();
590
+ return result;
591
+ });
592
+ }
593
+ /** Send everything waiting now. Await it before a serverless function returns. */
594
+ async flush(timeoutMs = 5e3) {
595
+ const all = Promise.all([...this.spanProcessors, ...this.logProcessors].map((p) => p.forceFlush().catch(() => {
596
+ })));
597
+ await Promise.race([all, new Promise((resolve) => setTimeout(resolve, timeoutMs).unref())]);
598
+ }
599
+ /** Flush, stop, and put back everything that was patched. */
600
+ async shutdown() {
601
+ const sdk = this.sdk;
602
+ if (!sdk) return;
603
+ this.sdk = null;
604
+ for (const undo of this.teardowns.splice(0)) undo();
605
+ await sdk.shutdown().catch(() => {
606
+ });
607
+ }
608
+ // ── internals ─────────────────────────────────────────────────────────
609
+ emit(level, message, attributes) {
610
+ try {
611
+ if (!this.logger) return;
612
+ const extra = {};
613
+ for (const [key, value] of Object.entries(attributes ?? {})) {
614
+ if (value instanceof Error && (level === "error" || level === "fatal") && !extra["exception.type"]) {
615
+ Object.assign(extra, exceptionAttributes(value, true));
616
+ } else {
617
+ extra[key] = value instanceof Error ? `${value.name}: ${value.message}` : value;
618
+ }
619
+ }
620
+ this.logger.emit({
621
+ severityNumber: SEVERITY[level],
622
+ severityText: level.toUpperCase(),
623
+ body: typeof message === "string" ? message : message instanceof Error ? message.message : safeJson(message),
624
+ attributes: extra
625
+ });
626
+ } catch {
627
+ }
628
+ }
629
+ report(value, handled, level, attributes) {
630
+ try {
631
+ if (!this.logger) return;
632
+ const error = asError(value);
633
+ if (value && typeof value === "object") {
634
+ if (this.reported.has(value)) return;
635
+ this.reported.add(value);
636
+ }
637
+ const exception = exceptionAttributes(error, handled);
638
+ this.logger.emit({
639
+ severityNumber: SEVERITY[level],
640
+ severityText: level.toUpperCase(),
641
+ body: `${exception["exception.type"]}: ${exception["exception.message"]}`,
642
+ attributes: { ...attributes, ...exception }
643
+ });
644
+ if (!handled) import_api3.trace.getActiveSpan()?.setStatus({ code: import_api3.SpanStatusCode.ERROR, message: error.message });
645
+ } catch {
646
+ }
647
+ }
648
+ /**
649
+ * Uncaught exceptions and unhandled rejections, reported as unhandled.
650
+ *
651
+ * Listening for either changes what Node does — it no longer exits — so when Zharp's listener
652
+ * is the only one, it finishes the job the way Node would have: print the error, then exit
653
+ * with code 1, after the error has been sent. When the application has listeners of its own,
654
+ * they decide, and Zharp only reports.
655
+ */
656
+ captureProcessErrors() {
657
+ const onException = (error, origin) => {
658
+ this.report(error, false, "fatal", origin ? { "zharp.mechanism": origin } : void 0);
659
+ if (process.listenerCount("uncaughtException") > 1) return;
660
+ this.crash(error);
661
+ };
662
+ const onRejection = (reason) => {
663
+ this.report(reason, false, "error", { "zharp.mechanism": "unhandledRejection" });
664
+ if (process.listenerCount("unhandledRejection") > 1) return;
665
+ const mode = unhandledRejectionsMode();
666
+ if (mode === "warn" || mode === "none") return;
667
+ if (mode === "warn-with-error-code") {
668
+ process.exitCode = 1;
669
+ return;
670
+ }
671
+ this.crash(reason);
672
+ };
673
+ process.on("uncaughtException", onException);
674
+ process.on("unhandledRejection", onRejection);
675
+ return () => {
676
+ process.off("uncaughtException", onException);
677
+ process.off("unhandledRejection", onRejection);
678
+ };
679
+ }
680
+ crashing = false;
681
+ crash(error) {
682
+ if (this.crashing) return;
683
+ this.crashing = true;
684
+ try {
685
+ const text = error instanceof Error ? error.stack || String(error) : `Uncaught ${safeJson(error)}`;
686
+ process.stderr.write(`${text}
687
+
688
+ Node.js ${process.version}
689
+ `);
690
+ } catch {
691
+ }
692
+ this.flush(EXIT_FLUSH_MS).finally(() => process.exit(1));
693
+ }
694
+ /**
695
+ * Send what is waiting when the process ends on its own (the event loop drains) or is told to
696
+ * stop. A signal listener also replaces Node's default of exiting, so once the flush is done,
697
+ * if no one else is listening, the signal is raised again with Zharp's listener gone.
698
+ */
699
+ flushOnExit() {
700
+ let flushing = false;
701
+ const onBeforeExit = () => {
702
+ if (flushing) return;
703
+ flushing = true;
704
+ this.flush(EXIT_FLUSH_MS).finally(() => flushing = false);
705
+ };
706
+ process.on("beforeExit", onBeforeExit);
707
+ const signals = ["SIGTERM", "SIGINT"];
708
+ const handlers = signals.map((signal) => {
709
+ const handler = () => {
710
+ this.flush(EXIT_FLUSH_MS).finally(() => {
711
+ process.off(signal, handler);
712
+ if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
713
+ });
714
+ };
715
+ process.on(signal, handler);
716
+ return [signal, handler];
717
+ });
718
+ return () => {
719
+ process.off("beforeExit", onBeforeExit);
720
+ for (const [signal, handler] of handlers) process.off(signal, handler);
721
+ };
722
+ }
723
+ };
724
+ function unhandledRejectionsMode() {
725
+ const flags = [...process.execArgv, ...(process.env.NODE_OPTIONS ?? "").split(/\s+/)];
726
+ for (const flag of flags) {
727
+ const match = /^--unhandled-rejections=(.+)$/.exec(flag);
728
+ if (match) return match[1];
729
+ }
730
+ return "throw";
731
+ }
732
+ function safeJson(value) {
733
+ try {
734
+ return typeof value === "string" ? value : JSON.stringify(value) ?? String(value);
735
+ } catch {
736
+ return String(value);
737
+ }
738
+ }
739
+ function registerEsmHook() {
740
+ const g2 = globalThis;
741
+ if (g2.__ZHARP_ESM_HOOK__) return;
742
+ g2.__ZHARP_ESM_HOOK__ = true;
743
+ try {
744
+ (0, import_node_module.register)?.("@opentelemetry/instrumentation/hook.mjs", importMetaUrl);
745
+ } catch {
746
+ }
747
+ }
748
+ function tracingEnabled(option) {
749
+ if (typeof option === "boolean") return option;
750
+ const value = nodeEnv("ZHARP_TRACING");
751
+ return !(value && /^(false|0|no|off)$/i.test(value));
752
+ }
753
+ function logsOnlyInstrumentations(options) {
754
+ const previous = process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS;
755
+ process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS = "http,pino,winston,bunyan";
756
+ try {
757
+ return (0, import_auto_instrumentations_node.getNodeAutoInstrumentations)({
758
+ ...options.instrumentations,
759
+ "@opentelemetry/instrumentation-http": {
760
+ ...options.instrumentations?.["@opentelemetry/instrumentation-http"],
761
+ disableOutgoingRequestInstrumentation: true
762
+ }
763
+ });
764
+ } finally {
765
+ if (previous === void 0) delete process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS;
766
+ else process.env.OTEL_NODE_ENABLED_INSTRUMENTATIONS = previous;
767
+ }
768
+ }
769
+ var RecordOnlySampler = class {
770
+ shouldSample() {
771
+ return { decision: import_sdk_trace.SamplingDecision.RECORD };
772
+ }
773
+ toString() {
774
+ return "ZharpRecordOnlySampler";
775
+ }
776
+ };
777
+ var ExtractOnlyPropagator = class {
778
+ constructor(inner) {
779
+ this.inner = inner;
780
+ }
781
+ inner;
782
+ inject() {
783
+ }
784
+ extract(context, carrier, getter) {
785
+ return this.inner.extract(context, carrier, getter);
786
+ }
787
+ fields() {
788
+ return [];
789
+ }
790
+ };
791
+
792
+ // src/index.ts
793
+ var g = globalThis;
794
+ var Zharp = g.__ZHARP_NODE__ ?? (g.__ZHARP_NODE__ = new ZharpNode());
795
+ var index_default = Zharp;
796
+ // Annotate the CommonJS export names for ESM import in node:
797
+ 0 && (module.exports = {
798
+ VERSION,
799
+ Zharp,
800
+ ZharpNode
801
+ });
802
+ //# sourceMappingURL=index.js.map