@zharp/node 0.2.0 → 0.4.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 CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
@@ -33,7 +43,7 @@ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
33
43
 
34
44
  // src/zharp.ts
35
45
  var import_node_module = require("module");
36
- var import_api3 = require("@opentelemetry/api");
46
+ var import_api5 = require("@opentelemetry/api");
37
47
  var import_core = require("@opentelemetry/core");
38
48
  var import_resources = require("@opentelemetry/resources");
39
49
  var import_sdk_node = require("@opentelemetry/sdk-node");
@@ -210,24 +220,24 @@ function shorten(value) {
210
220
  if (BASE64.test(value) && /[0-9+/]/.test(value)) return `[base64 \xB7 ${formatSize(Math.floor(value.length * 3 / 4))}]`;
211
221
  return value;
212
222
  }
213
- function filterAll(value, depth) {
214
- if (depth > 20) return FILTERED;
223
+ function filterAll(value, depth2) {
224
+ if (depth2 > 20) return FILTERED;
215
225
  if (value === null || value === "") return value;
216
- if (Array.isArray(value)) return value.map((v) => filterAll(v, depth + 1));
226
+ if (Array.isArray(value)) return value.map((v) => filterAll(v, depth2 + 1));
217
227
  if (typeof value === "object") {
218
228
  const out = {};
219
- for (const [k, v] of Object.entries(value)) out[k] = filterAll(v, depth + 1);
229
+ for (const [k, v] of Object.entries(value)) out[k] = filterAll(v, depth2 + 1);
220
230
  return out;
221
231
  }
222
232
  return FILTERED;
223
233
  }
224
- function redactValue(value, extra, depth = 0) {
234
+ function redactValue(value, extra, depth2 = 0) {
225
235
  if (typeof value === "string") return shorten(value);
226
- if (depth > 20 || value === null || typeof value !== "object") return value;
227
- if (Array.isArray(value)) return value.map((v) => redactValue(v, extra, depth + 1));
236
+ if (depth2 > 20 || value === null || typeof value !== "object") return value;
237
+ if (Array.isArray(value)) return value.map((v) => redactValue(v, extra, depth2 + 1));
228
238
  const out = {};
229
239
  for (const [k, v] of Object.entries(value)) {
230
- out[k] = isSecretKey(k, extra) ? filterAll(v, depth + 1) : redactValue(v, extra, depth + 1);
240
+ out[k] = isSecretKey(k, extra) ? filterAll(v, depth2 + 1) : redactValue(v, extra, depth2 + 1);
231
241
  }
232
242
  return out;
233
243
  }
@@ -668,6 +678,571 @@ function withBodyCapture(settings, config = {}) {
668
678
  };
669
679
  }
670
680
 
681
+ // src/headers.ts
682
+ var import_node_http2 = require("http");
683
+ var SECRET = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie", "x-api-key", "x-auth-token", "x-csrf-token", "x-xsrf-token"]);
684
+ var MAX_HEADERS = 40;
685
+ var MAX_VALUE = 512;
686
+ function headerSettings(option, env) {
687
+ if (option === false || env === "false" || env === "0") return null;
688
+ return { redact: typeof option === "object" && option?.redact ? option.redact : [] };
689
+ }
690
+ function shown(name, value, settings) {
691
+ if (value === void 0 || value === null) return null;
692
+ if (SECRET.has(name) || isSecretKey(name, settings.redact)) return FILTERED;
693
+ const text = Array.isArray(value) ? value.join(", ") : String(value);
694
+ return text.length > MAX_VALUE ? `${text.slice(0, MAX_VALUE)}\u2026` : text;
695
+ }
696
+ function headerAttributes(side, headers, settings) {
697
+ const out = {};
698
+ let count = 0;
699
+ for (const [rawName, value] of Object.entries(headers ?? {})) {
700
+ if (count >= MAX_HEADERS) break;
701
+ const name = rawName.toLowerCase();
702
+ const text = shown(name, value, settings);
703
+ if (text === null) continue;
704
+ out[`http.${side}.header.${name}`] = text;
705
+ count++;
706
+ }
707
+ return out;
708
+ }
709
+ function withHeaderCapture(settings, config = {}) {
710
+ return {
711
+ ...config,
712
+ applyCustomAttributesOnSpan(span, request, response) {
713
+ config.applyCustomAttributesOnSpan?.(span, request, response);
714
+ try {
715
+ if (request instanceof import_node_http2.IncomingMessage) {
716
+ span.setAttributes(headerAttributes("request", request.headers, settings));
717
+ if (response instanceof import_node_http2.ServerResponse) span.setAttributes(headerAttributes("response", response.getHeaders(), settings));
718
+ } else if (request instanceof import_node_http2.ClientRequest) {
719
+ span.setAttributes(headerAttributes("request", request.getHeaders(), settings));
720
+ if (response instanceof import_node_http2.IncomingMessage) span.setAttributes(headerAttributes("response", response.headers, settings));
721
+ }
722
+ } catch {
723
+ }
724
+ }
725
+ };
726
+ }
727
+
728
+ // src/db-errors.ts
729
+ var import_api = require("@opentelemetry/api");
730
+ var import_instrumentation = require("@opentelemetry/instrumentation");
731
+
732
+ // src/version.ts
733
+ var VERSION = "0.4.0";
734
+
735
+ // src/source.ts
736
+ var import_node_fs = require("fs");
737
+ var import_node_path = require("path");
738
+ var import_node_url = require("url");
739
+ var nodeModule = __toESM(require("module"));
740
+ var SOURCE_CONTEXT_ATTRIBUTE = "zharp.source_context";
741
+ var AROUND = 5;
742
+ var MAX_FRAMES = 5;
743
+ var MAX_LINE = 300;
744
+ var MAX_BYTES = 12e3;
745
+ var MAX_FILE = 5e6;
746
+ var MAX_MAP = 3e7;
747
+ var MAX_CACHED = 50;
748
+ var enabled = true;
749
+ function setSourceContext(on) {
750
+ enabled = on;
751
+ }
752
+ var files = /* @__PURE__ */ new Map();
753
+ var maps = /* @__PURE__ */ new Map();
754
+ function remember(cache, key, value) {
755
+ if (cache.size >= MAX_CACHED) cache.delete(cache.keys().next().value);
756
+ cache.set(key, value);
757
+ return value;
758
+ }
759
+ function toPath(file) {
760
+ if (file.startsWith("file://")) {
761
+ try {
762
+ return (0, import_node_url.fileURLToPath)(file);
763
+ } catch {
764
+ return null;
765
+ }
766
+ }
767
+ return (0, import_node_path.isAbsolute)(file) ? file : null;
768
+ }
769
+ function isApp(path) {
770
+ return !/[\\/]node_modules[\\/]/.test(path) && !path.startsWith("node:") && !/[\\/]@zharp[\\/]/.test(path);
771
+ }
772
+ function linesOf(path, text) {
773
+ if (files.has(path)) return files.get(path);
774
+ let content = text ?? null;
775
+ if (content === null) {
776
+ try {
777
+ if ((0, import_node_fs.statSync)(path).size > MAX_FILE) return remember(files, path, null);
778
+ content = (0, import_node_fs.readFileSync)(path, "utf8");
779
+ } catch {
780
+ return remember(files, path, null);
781
+ }
782
+ }
783
+ return remember(files, path, content.split(/\r\n|\n|\r/));
784
+ }
785
+ function mapOf(path) {
786
+ if (maps.has(path)) return maps.get(path);
787
+ const SourceMap2 = nodeModule.SourceMap;
788
+ const lines = linesOf(path);
789
+ if (!SourceMap2 || !lines) return remember(maps, path, null);
790
+ try {
791
+ let payload = null;
792
+ let mapPath = `${path}.map`;
793
+ const tail = lines.slice(-5).join("\n");
794
+ const url = /[#@]\s*sourceMappingURL=(\S+)\s*$/m.exec(tail)?.[1];
795
+ if (url?.startsWith("data:")) {
796
+ const base64 = /;base64,(.*)$/.exec(url)?.[1];
797
+ payload = base64 ? JSON.parse(Buffer.from(base64, "base64").toString("utf8")) : null;
798
+ mapPath = path;
799
+ } else {
800
+ if (url) mapPath = (0, import_node_path.resolve)((0, import_node_path.dirname)(path), decodeURIComponent(url));
801
+ if ((0, import_node_fs.statSync)(mapPath).size > MAX_MAP) return remember(maps, path, null);
802
+ payload = JSON.parse((0, import_node_fs.readFileSync)(mapPath, "utf8"));
803
+ }
804
+ if (!payload || !Array.isArray(payload.sources)) return remember(maps, path, null);
805
+ return remember(maps, path, {
806
+ map: new SourceMap2(payload),
807
+ dir: (0, import_node_path.dirname)(mapPath),
808
+ sources: payload.sources,
809
+ sourceRoot: typeof payload.sourceRoot === "string" ? payload.sourceRoot : "",
810
+ contents: Array.isArray(payload.sourcesContent) ? payload.sourcesContent : []
811
+ });
812
+ } catch {
813
+ return remember(maps, path, null);
814
+ }
815
+ }
816
+ function original(path, line, column) {
817
+ const loaded = mapOf(path);
818
+ if (!loaded) return null;
819
+ const entry = loaded.map.findEntry(line - 1, Math.max(0, column - 1));
820
+ if (!entry?.originalSource || entry.originalLine === void 0) return null;
821
+ const index = loaded.sources.findIndex((s) => s === entry.originalSource || entry.originalSource.endsWith(s));
822
+ const source = entry.originalSource.replace(/^webpack:\/\/[^/]*\//, "").replace(/^file:\/\//, "");
823
+ const file = (0, import_node_path.isAbsolute)(source) ? source : (0, import_node_path.resolve)(loaded.dir, loaded.sourceRoot, source);
824
+ return { file, line: entry.originalLine + 1, column: (entry.originalColumn ?? 0) + 1, text: index >= 0 ? loaded.contents[index] ?? null : null };
825
+ }
826
+ var FRAME = /^(\s*at (?:async )?(?:.*? \()?)((?:file:\/\/)?(?:\/|[A-Za-z]:[\\/]).*?):(\d+):(\d+)(\)?)\s*$/;
827
+ function sourced(stack) {
828
+ if (!enabled || !stack) return { stack, context: null };
829
+ const out = [];
830
+ const seen = /* @__PURE__ */ new Set();
831
+ let mapped = 0;
832
+ const lines = stack.split("\n").map((text) => {
833
+ const m = FRAME.exec(text);
834
+ if (!m) return text;
835
+ const path = toPath(m[2]);
836
+ if (!path || !isApp(path) || mapped > 40) return text;
837
+ let file = m[2];
838
+ let line = Number(m[3]);
839
+ let column = Number(m[4]);
840
+ let content = null;
841
+ const from = /\.(c|m)?js$/.test(path) ? original(path, line, column) : null;
842
+ mapped++;
843
+ if (from && isApp(from.file)) {
844
+ file = from.file;
845
+ line = from.line;
846
+ column = from.column;
847
+ content = linesOf(from.file, from.text);
848
+ text = `${m[1]}${file}:${line}:${column}${m[5]}`;
849
+ } else if (!from) {
850
+ const built = linesOf(path);
851
+ const tail = built ? built.slice(-5).join("\n") : "";
852
+ content = /[#@]\s*(?:sourceMappingURL|debugId)=/.test(tail) ? null : built;
853
+ }
854
+ const key = `${file}:${line}`;
855
+ if (content && out.length < MAX_FRAMES && !seen.has(key) && content[line - 1] !== void 0) {
856
+ seen.add(key);
857
+ const cut = (s) => s.length > MAX_LINE ? `${s.slice(0, MAX_LINE - 1)}\u2026` : s;
858
+ out.push({
859
+ file,
860
+ line,
861
+ pre: content.slice(Math.max(0, line - 1 - AROUND), line - 1).map(cut),
862
+ code: cut(content[line - 1]),
863
+ post: content.slice(line, line + AROUND).map(cut)
864
+ });
865
+ }
866
+ return text;
867
+ });
868
+ while (out.length) {
869
+ const json = JSON.stringify(out);
870
+ if (Buffer.byteLength(json) <= MAX_BYTES) return { stack: lines.join("\n"), context: json };
871
+ out.pop();
872
+ }
873
+ return { stack: lines.join("\n"), context: null };
874
+ }
875
+
876
+ // src/db-errors.ts
877
+ var SQLSTATE = {
878
+ "23505": "UniqueViolation",
879
+ "23503": "ForeignKeyViolation",
880
+ "23502": "NotNullViolation",
881
+ "23514": "CheckViolation",
882
+ "23P01": "ExclusionViolation",
883
+ "22001": "StringDataRightTruncation",
884
+ "22003": "NumericValueOutOfRange",
885
+ "22P02": "InvalidTextRepresentation",
886
+ "22007": "InvalidDatetimeFormat",
887
+ "22008": "DatetimeFieldOverflow",
888
+ "22012": "DivisionByZero",
889
+ "42P01": "UndefinedTable",
890
+ "42703": "UndefinedColumn",
891
+ "42883": "UndefinedFunction",
892
+ "42601": "SyntaxError",
893
+ "42501": "InsufficientPrivilege",
894
+ "40001": "SerializationFailure",
895
+ "40P01": "DeadlockDetected",
896
+ "55P03": "LockNotAvailable",
897
+ "57014": "QueryCanceled",
898
+ "53300": "TooManyConnections",
899
+ "08006": "ConnectionFailure",
900
+ "08001": "ConnectionRefused",
901
+ "28P01": "InvalidPassword",
902
+ "3D000": "InvalidCatalogName"
903
+ };
904
+ var SYSTEM_NAMES = { postgresql: "Postgres", mysql: "MySQL", mariadb: "MariaDB", mongodb: "Mongo", redis: "Redis", mssql: "SqlServer", oracle: "Oracle", sqlite: "Sqlite" };
905
+ function dbErrorType(system, code, name) {
906
+ if (code && system === "postgresql" && SQLSTATE[code]) return SQLSTATE[code];
907
+ if (code && /^ER_[A-Z_]+$/.test(code)) return code;
908
+ if (name && !/^(error|Error|DatabaseError)$/.test(name)) return name;
909
+ return `${SYSTEM_NAMES[system] ?? "Database"}Error`;
910
+ }
911
+ function callSiteFrames(stack) {
912
+ const frames = (stack ?? "").split("\n").slice(1).filter((line) => /^\s+at /.test(line)).filter((line) => !/[\\/]@opentelemetry[\\/]|[\\/]@zharp[\\/]|\(node:|\bnode:internal\b|[\\/]require-in-the-middle[\\/]|[\\/]import-in-the-middle[\\/]/.test(line));
913
+ const firstApp = frames.findIndex((line) => !/[\\/]node_modules[\\/]/.test(line));
914
+ return (firstApp > 0 ? frames.slice(firstApp) : frames).slice(0, 40);
915
+ }
916
+ var CALL_SITE = (0, import_api.createContextKey)("zharp.db.callSite");
917
+ function stackFrom(fn) {
918
+ const limit = Error.stackTraceLimit;
919
+ Error.stackTraceLimit = 60;
920
+ const holder = {};
921
+ Error.captureStackTrace(holder, fn);
922
+ Error.stackTraceLimit = limit;
923
+ return holder.stack;
924
+ }
925
+ var attr = (attributes, ...names) => {
926
+ for (const name of names) {
927
+ const value = attributes[name];
928
+ if (value !== void 0 && value !== null && value !== "") return String(value);
929
+ }
930
+ return null;
931
+ };
932
+ function reportOf(failure) {
933
+ const error = failure.error;
934
+ const code = (error?.code !== void 0 ? String(error.code) : null) ?? failure.code;
935
+ const type = dbErrorType(failure.system, code, error?.name);
936
+ const message = error?.message || failure.scrubbed?.replace(/^.*?error of type '[^']*' occurred/i, `${SYSTEM_NAMES[failure.system] ?? "Database"} error`) || "The query failed";
937
+ const { stack, context: context3 } = sourced([`${type}: ${message}`, ...failure.frames].join("\n"));
938
+ const attributes = {
939
+ ...context3 ? { [SOURCE_CONTEXT_ATTRIBUTE]: context3 } : {},
940
+ "zharp.mechanism": "db",
941
+ "db.system": failure.system,
942
+ ...failure.statement ? { "db.statement": failure.statement.slice(0, 4e3) } : {},
943
+ ...failure.database ? { "db.name": failure.database } : {},
944
+ ...code ? { "db.error.code": code } : {},
945
+ ...error?.constraint ? { "db.error.constraint": error.constraint } : {}
946
+ };
947
+ return { type, message, stack, attributes, spanContext: failure.spanContext };
948
+ }
949
+ var LONE_WAIT_MS = 1500;
950
+ var MAX_PENDING = 200;
951
+ var DbErrorSpanProcessor = class _DbErrorSpanProcessor {
952
+ constructor(send) {
953
+ this.send = send;
954
+ }
955
+ send;
956
+ callSites = /* @__PURE__ */ new WeakMap();
957
+ /** Failures not yet reported, by trace. */
958
+ pending = /* @__PURE__ */ new Map();
959
+ onStart(span, parentContext) {
960
+ const attributes = span.attributes ?? {};
961
+ if (!attr(attributes, "db.system", "db.system.name")) return;
962
+ const carried = (parentContext ?? import_api.context.active()).getValue(CALL_SITE);
963
+ const entry = {
964
+ frames: callSiteFrames(carried ?? stackFrom(_DbErrorSpanProcessor.prototype.onStart))
965
+ };
966
+ this.callSites.set(span, entry);
967
+ const record = span.recordException.bind(span);
968
+ span.recordException = (exception, time) => {
969
+ if (entry.exception === void 0) entry.exception = exception;
970
+ else record(exception, time);
971
+ };
972
+ }
973
+ onEnd(span) {
974
+ const entry = this.callSites.get(span);
975
+ if (entry && span.status.code === import_api.SpanStatusCode.ERROR) {
976
+ const attributes = span.attributes ?? {};
977
+ const exception = entry.exception;
978
+ const failure = {
979
+ spanContext: span.spanContext(),
980
+ traceId: span.spanContext().traceId,
981
+ system: attr(attributes, "db.system", "db.system.name") ?? "database",
982
+ statement: attr(attributes, "db.statement", "db.query.text"),
983
+ database: attr(attributes, "db.name", "db.namespace"),
984
+ code: attr(attributes, "error.type", "db.response.status_code"),
985
+ frames: entry.frames,
986
+ scrubbed: typeof exception === "string" ? exception : exception?.message ?? span.status.message ?? null,
987
+ ...exception instanceof Error ? { error: exception } : {}
988
+ };
989
+ this.add(failure);
990
+ }
991
+ const root = span.kind === import_api.SpanKind.SERVER || !span.parentSpanContext || !!span.parentSpanContext.isRemote;
992
+ if (root) {
993
+ const traceId = span.spanContext().traceId;
994
+ if (!this.pending.has(traceId)) return;
995
+ if (entry || span.status.code === import_api.SpanStatusCode.ERROR) setTimeout(() => this.flush(traceId), LONE_WAIT_MS).unref?.();
996
+ else this.flush(traceId);
997
+ }
998
+ }
999
+ add(failure) {
1000
+ const list = this.pending.get(failure.traceId) ?? [];
1001
+ list.push(failure);
1002
+ this.pending.set(failure.traceId, list);
1003
+ if (this.pending.size > MAX_PENDING) this.flush(this.pending.keys().next().value);
1004
+ }
1005
+ /** The driver's error, seen by the query wrapper: joined to the trace's latest failure. */
1006
+ attach(traceId, error) {
1007
+ if (!traceId || !(error instanceof Error)) return;
1008
+ const list = this.pending.get(traceId);
1009
+ if (!list || list.some((f) => f.error === error)) return;
1010
+ const failure = [...list].reverse().find((f) => !f.error && !f.done);
1011
+ if (failure) failure.error = error;
1012
+ }
1013
+ /**
1014
+ * `error` is being reported (by a framework's handler, as unhandled, or by captureError): the
1015
+ * failed query it came from, if any, so its details go into that one report and it isn't sent
1016
+ * again. Matched by the error itself, or what wraps it (`driverError`, `cause`); `latest` also
1017
+ * takes the request's latest failure whose driver error was never seen.
1018
+ */
1019
+ consume(traceId, error, latest = false) {
1020
+ const inner = (candidate) => {
1021
+ if (!candidate || typeof candidate !== "object") return [];
1022
+ const c = candidate;
1023
+ return [candidate, c.driverError, c.cause, c.originalError].filter(Boolean);
1024
+ };
1025
+ const wanted2 = inner(error);
1026
+ const lists = traceId ? [this.pending.get(traceId) ?? []] : [...this.pending.values()];
1027
+ for (const list of lists) {
1028
+ const failure = list.find((f) => !f.done && f.error && wanted2.includes(f.error)) ?? (latest && traceId ? [...list].reverse().find((f) => !f.done && !f.error) : void 0);
1029
+ if (failure) {
1030
+ failure.done = true;
1031
+ return failure;
1032
+ }
1033
+ }
1034
+ return null;
1035
+ }
1036
+ flush(traceId) {
1037
+ const list = this.pending.get(traceId);
1038
+ if (!list) return;
1039
+ this.pending.delete(traceId);
1040
+ for (const failure of list) if (!failure.done) this.send(failure);
1041
+ }
1042
+ forceFlush() {
1043
+ for (const traceId of [...this.pending.keys()]) this.flush(traceId);
1044
+ return Promise.resolve();
1045
+ }
1046
+ shutdown() {
1047
+ return this.forceFlush();
1048
+ }
1049
+ };
1050
+ var DbDriverErrorsInstrumentation = class extends import_instrumentation.InstrumentationBase {
1051
+ constructor(onError) {
1052
+ super("@zharp/node/db-driver-errors", VERSION, {});
1053
+ this.onError = onError;
1054
+ }
1055
+ onError;
1056
+ init() {
1057
+ const onError = (traceId, err) => {
1058
+ try {
1059
+ this.onError(traceId, err);
1060
+ } catch {
1061
+ }
1062
+ };
1063
+ const wrapQuery = (original2) => {
1064
+ const run = (self, args) => {
1065
+ const traceId = import_api.trace.getActiveSpan()?.spanContext().traceId;
1066
+ const callback = args.findIndex((a) => typeof a === "function");
1067
+ if (callback >= 0) {
1068
+ const cb = args[callback];
1069
+ args[callback] = function(err, ...rest) {
1070
+ if (err) onError(traceId, err);
1071
+ return cb.call(this, err, ...rest);
1072
+ };
1073
+ return original2.apply(self, args);
1074
+ }
1075
+ const result = original2.apply(self, args);
1076
+ if (!result || typeof result.then !== "function" || typeof result.submit === "function") return result;
1077
+ result.then(void 0, (err) => onError(traceId, err));
1078
+ return result;
1079
+ };
1080
+ return function query(...args) {
1081
+ const active = import_api.context.active();
1082
+ if (active.getValue(CALL_SITE) !== void 0) return run(this, args);
1083
+ return import_api.context.with(active.setValue(CALL_SITE, stackFrom(query)), () => run(this, args));
1084
+ };
1085
+ };
1086
+ const patch = (moduleExports) => {
1087
+ for (const target of [moduleExports?.Client?.prototype, moduleExports?.Pool?.prototype]) {
1088
+ if (target?.query && !target.query.__zharpWrapped) {
1089
+ const wrapped = wrapQuery(target.query);
1090
+ wrapped.__zharpWrapped = true;
1091
+ wrapped.__zharpOriginal = target.query;
1092
+ target.query = wrapped;
1093
+ }
1094
+ }
1095
+ return moduleExports;
1096
+ };
1097
+ const unpatch = (moduleExports) => {
1098
+ for (const target of [moduleExports?.Client?.prototype, moduleExports?.Pool?.prototype]) {
1099
+ if (target?.query?.__zharpOriginal) target.query = target.query.__zharpOriginal;
1100
+ }
1101
+ };
1102
+ return [new import_instrumentation.InstrumentationNodeModuleDefinition("pg", [">=8 <9"], patch, unpatch)];
1103
+ }
1104
+ };
1105
+
1106
+ // src/framework-errors.ts
1107
+ var import_instrumentation2 = require("@opentelemetry/instrumentation");
1108
+ function statusOf(error) {
1109
+ if (!error || typeof error !== "object") return 500;
1110
+ const e = error;
1111
+ try {
1112
+ if (typeof e.getStatus === "function") {
1113
+ const status = Number(e.getStatus());
1114
+ if (Number.isFinite(status)) return status;
1115
+ }
1116
+ } catch {
1117
+ }
1118
+ for (const value of [e.status, e.statusCode]) {
1119
+ const status = Number(value);
1120
+ if (Number.isInteger(status) && status >= 100 && status < 600) return status;
1121
+ }
1122
+ return 500;
1123
+ }
1124
+ var WRAPPED = /* @__PURE__ */ Symbol.for("zharp.frameworkErrors");
1125
+ var FrameworkErrorsInstrumentation = class extends import_instrumentation2.InstrumentationBase {
1126
+ constructor(sink) {
1127
+ super("@zharp/node/framework-errors", VERSION, {});
1128
+ this.sink = sink;
1129
+ }
1130
+ sink;
1131
+ init() {
1132
+ const report = (error, mechanism) => {
1133
+ try {
1134
+ if (statusOf(error) >= 500) this.sink(error, mechanism);
1135
+ } catch {
1136
+ }
1137
+ };
1138
+ const nest = new import_instrumentation2.InstrumentationNodeModuleFile(
1139
+ "@nestjs/core/exceptions/exceptions-handler.js",
1140
+ [">=8 <13"],
1141
+ (moduleExports) => {
1142
+ const proto = moduleExports?.ExceptionsHandler?.prototype;
1143
+ if (proto?.next && !proto.next[WRAPPED]) {
1144
+ const original2 = proto.next;
1145
+ const next = function(exception, ...rest) {
1146
+ report(exception, "nestjs");
1147
+ return original2.call(this, exception, ...rest);
1148
+ };
1149
+ next[WRAPPED] = original2;
1150
+ proto.next = next;
1151
+ }
1152
+ return moduleExports;
1153
+ },
1154
+ (moduleExports) => {
1155
+ const proto = moduleExports?.ExceptionsHandler?.prototype;
1156
+ if (proto?.next?.[WRAPPED]) proto.next = proto.next[WRAPPED];
1157
+ }
1158
+ );
1159
+ const finalhandler = new import_instrumentation2.InstrumentationNodeModuleDefinition(
1160
+ "finalhandler",
1161
+ [">=1 <3"],
1162
+ (moduleExports) => {
1163
+ if (typeof moduleExports !== "function" || moduleExports[WRAPPED]) return moduleExports;
1164
+ const original2 = moduleExports;
1165
+ const wrapped = function(...args) {
1166
+ const done = original2.apply(this, args);
1167
+ return function(err, ...rest) {
1168
+ if (err) report(err, "express");
1169
+ return done.call(this, err, ...rest);
1170
+ };
1171
+ };
1172
+ Object.assign(wrapped, original2);
1173
+ wrapped[WRAPPED] = original2;
1174
+ return wrapped;
1175
+ },
1176
+ (moduleExports) => moduleExports?.[WRAPPED] ?? moduleExports
1177
+ );
1178
+ return [new import_instrumentation2.InstrumentationNodeModuleDefinition("@nestjs/core", [">=8 <13"], void 0, void 0, [nest]), finalhandler];
1179
+ }
1180
+ };
1181
+ var RecordedExceptionsProcessor = class {
1182
+ constructor(report) {
1183
+ this.report = report;
1184
+ }
1185
+ report;
1186
+ pending = /* @__PURE__ */ new Map();
1187
+ onStart(span) {
1188
+ const scope = span.instrumentationScope?.name ?? span.instrumentationLibrary?.name ?? "";
1189
+ if (!scope.startsWith("@opentelemetry/instrumentation-") && scope !== "next.js") return;
1190
+ if (span.attributes?.["db.system"] || span.attributes?.["db.system.name"]) return;
1191
+ const original2 = span.recordException.bind(span);
1192
+ span.recordException = (exception, time) => {
1193
+ try {
1194
+ if (!exception || typeof exception !== "object") return original2(exception, time);
1195
+ const name = typeof exception.name === "string" && exception.name !== "error" ? exception.name : exception.constructor?.name || "Error";
1196
+ span.addEvent("exception", {
1197
+ "exception.type": name,
1198
+ "exception.message": String(exception.message ?? ""),
1199
+ ...typeof exception.stack === "string" ? { "exception.stacktrace": exception.stack } : {},
1200
+ "zharp.deferred": "true"
1201
+ }, time);
1202
+ const traceId = span.spanContext().traceId;
1203
+ const list = this.pending.get(traceId) ?? [];
1204
+ if (!list.some((p) => p.error === exception)) list.push({ error: exception, spanContext: span.spanContext(), scope: mechanismOf(scope) });
1205
+ this.pending.set(traceId, list);
1206
+ if (this.pending.size > 500) this.pending.delete(this.pending.keys().next().value);
1207
+ } catch {
1208
+ original2(exception, time);
1209
+ }
1210
+ };
1211
+ }
1212
+ onEnd(span) {
1213
+ const parent = span.parentSpanContext;
1214
+ const isRoot = span.kind === 1 || !parent || parent.isRemote;
1215
+ if (!isRoot) return;
1216
+ const traceId = span.spanContext().traceId;
1217
+ const list = this.pending.get(traceId);
1218
+ if (!list) return;
1219
+ this.pending.delete(traceId);
1220
+ const status = Number(span.attributes?.["http.response.status_code"] ?? span.attributes?.["http.status_code"]);
1221
+ const failed = Number.isFinite(status) && status > 0 ? status >= 500 : span.status?.code === 2;
1222
+ if (!failed) return;
1223
+ const seen = /* @__PURE__ */ new Set();
1224
+ for (const p of list) {
1225
+ if (seen.has(p.error)) continue;
1226
+ seen.add(p.error);
1227
+ if (statusOf(p.error) < 500) continue;
1228
+ this.report(p.error, p.spanContext, p.scope);
1229
+ break;
1230
+ }
1231
+ }
1232
+ forceFlush() {
1233
+ return Promise.resolve();
1234
+ }
1235
+ shutdown() {
1236
+ this.pending.clear();
1237
+ return Promise.resolve();
1238
+ }
1239
+ };
1240
+ function mechanismOf(scope) {
1241
+ const name = scope.replace("@opentelemetry/instrumentation-", "").replace(/-core$/, "");
1242
+ if (name === "router") return "express";
1243
+ return name === "next.js" ? "nextjs" : name;
1244
+ }
1245
+
671
1246
  // src/urls.ts
672
1247
  var URL_KEYS = ["url.full", "http.url", "http.target"];
673
1248
  var UrlRedactionSpanProcessor = class {
@@ -703,7 +1278,7 @@ var UrlRedactionSpanProcessor = class {
703
1278
  };
704
1279
 
705
1280
  // src/context.ts
706
- var import_api = require("@opentelemetry/api");
1281
+ var import_api2 = require("@opentelemetry/api");
707
1282
  var BAGGAGE_KEYS = ["enduser.id", "session.id"];
708
1283
  function userAttributes(user) {
709
1284
  const out = { "enduser.id": String(user.id) };
@@ -720,7 +1295,7 @@ var ContextStore = class {
720
1295
  localRoots = /* @__PURE__ */ new Map();
721
1296
  /** Set the user for the request in progress, or for the whole process outside one. */
722
1297
  setUser(user) {
723
- const span = import_api.trace.getActiveSpan();
1298
+ const span = import_api2.trace.getActiveSpan();
724
1299
  const traceId = span?.spanContext().traceId;
725
1300
  if (!span || !traceId) {
726
1301
  this.globalUser = user;
@@ -740,7 +1315,7 @@ var ContextStore = class {
740
1315
  return user ? { ...this.tags, ...user } : { ...this.tags };
741
1316
  }
742
1317
  noteStart(span, parent) {
743
- const parentSpan = import_api.trace.getSpanContext(parent);
1318
+ const parentSpan = import_api2.trace.getSpanContext(parent);
744
1319
  if (!parentSpan || parentSpan.isRemote) {
745
1320
  const { traceId, spanId } = span.spanContext();
746
1321
  if (!this.localRoots.has(traceId)) this.localRoots.set(traceId, { spanId, span });
@@ -755,7 +1330,7 @@ var ContextStore = class {
755
1330
  };
756
1331
  function fromBaggage(ctx) {
757
1332
  const out = {};
758
- const baggage = import_api.propagation.getBaggage(ctx);
1333
+ const baggage = import_api2.propagation.getBaggage(ctx);
759
1334
  if (!baggage) return out;
760
1335
  for (const key of BAGGAGE_KEYS) {
761
1336
  const value = baggage.getEntry(key)?.value;
@@ -792,8 +1367,8 @@ var ContextLogProcessor = class {
792
1367
  store;
793
1368
  onEmit(record, ctx) {
794
1369
  try {
795
- const active = ctx ?? import_api.context.active();
796
- const traceId = record.spanContext?.traceId ?? import_api.trace.getSpanContext(active)?.traceId;
1370
+ const active = ctx ?? import_api2.context.active();
1371
+ const traceId = record.spanContext?.traceId ?? import_api2.trace.getSpanContext(active)?.traceId;
797
1372
  const add = { ...this.store.attributesFor(traceId), ...fromBaggage(active) };
798
1373
  for (const [key, value] of Object.entries(add)) {
799
1374
  if (record.attributes[key] === void 0) record.setAttribute(key, value);
@@ -811,24 +1386,62 @@ var ContextLogProcessor = class {
811
1386
 
812
1387
  // src/console.ts
813
1388
  var import_node_util = require("util");
814
- var import_api2 = require("@opentelemetry/api");
1389
+ var import_api3 = require("@opentelemetry/api");
1390
+
1391
+ // src/capture-state.ts
1392
+ var depth = 0;
1393
+ function quiet(fn) {
1394
+ depth++;
1395
+ try {
1396
+ return fn();
1397
+ } finally {
1398
+ depth--;
1399
+ }
1400
+ }
1401
+ var isQuiet = () => depth > 0;
1402
+ var RECENT_MS = 3e3;
1403
+ var RECENT_MAX = 500;
1404
+ var recent = [];
1405
+ var normalise = (text) => text.replace(/\s+/g, " ").trim();
1406
+ function rememberSent(body) {
1407
+ if (typeof body !== "string") return;
1408
+ const text = normalise(body);
1409
+ if (text.length < 4) return;
1410
+ recent.push({ at: Date.now(), text });
1411
+ if (recent.length > RECENT_MAX) recent.splice(0, recent.length - RECENT_MAX);
1412
+ }
1413
+ function alreadySent(line) {
1414
+ const now = Date.now();
1415
+ while (recent.length && now - recent[0].at > RECENT_MS) recent.shift();
1416
+ if (!recent.length) return false;
1417
+ const text = normalise(line);
1418
+ for (let i = recent.length - 1; i >= 0; i--) {
1419
+ if (text.includes(recent[i].text)) {
1420
+ recent.splice(i, 1);
1421
+ return true;
1422
+ }
1423
+ }
1424
+ return false;
1425
+ }
1426
+
1427
+ // src/console.ts
815
1428
  var LEVELS = [
816
- ["debug", import_api2.SeverityNumber.DEBUG, "DEBUG"],
817
- ["trace", import_api2.SeverityNumber.TRACE, "TRACE"],
818
- ["log", import_api2.SeverityNumber.INFO, "INFO"],
819
- ["info", import_api2.SeverityNumber.INFO, "INFO"],
820
- ["warn", import_api2.SeverityNumber.WARN, "WARN"],
821
- ["error", import_api2.SeverityNumber.ERROR, "ERROR"]
1429
+ ["debug", import_api3.SeverityNumber.DEBUG, "DEBUG"],
1430
+ ["trace", import_api3.SeverityNumber.TRACE, "TRACE"],
1431
+ ["log", import_api3.SeverityNumber.INFO, "INFO"],
1432
+ ["info", import_api3.SeverityNumber.INFO, "INFO"],
1433
+ ["warn", import_api3.SeverityNumber.WARN, "WARN"],
1434
+ ["error", import_api3.SeverityNumber.ERROR, "ERROR"]
822
1435
  ];
823
1436
  var emitting = false;
824
1437
  function captureConsole(logger) {
825
1438
  const originals = /* @__PURE__ */ new Map();
826
1439
  for (const [method, severityNumber, severityText] of LEVELS) {
827
- const original = console[method];
828
- if (typeof original !== "function" || original.__zharp) continue;
829
- originals.set(method, original);
1440
+ const original2 = console[method];
1441
+ if (typeof original2 !== "function" || original2.__zharp) continue;
1442
+ originals.set(method, original2);
830
1443
  const patched = function(...args) {
831
- original.apply(this ?? console, args);
1444
+ quiet(() => original2.apply(this ?? console, args));
832
1445
  if (emitting) return;
833
1446
  emitting = true;
834
1447
  try {
@@ -845,13 +1458,214 @@ function captureConsole(logger) {
845
1458
  console[method] = patched;
846
1459
  }
847
1460
  return () => {
848
- for (const [method, original] of originals) console[method] = original;
1461
+ for (const [method, original2] of originals) console[method] = original2;
849
1462
  };
850
1463
  }
851
1464
 
1465
+ // src/stdout.ts
1466
+ var import_api4 = require("@opentelemetry/api");
1467
+ var LEVELS2 = {
1468
+ trace: [import_api4.SeverityNumber.TRACE, "TRACE"],
1469
+ verbose: [import_api4.SeverityNumber.DEBUG, "DEBUG"],
1470
+ debug: [import_api4.SeverityNumber.DEBUG, "DEBUG"],
1471
+ log: [import_api4.SeverityNumber.INFO, "INFO"],
1472
+ info: [import_api4.SeverityNumber.INFO, "INFO"],
1473
+ notice: [import_api4.SeverityNumber.INFO, "INFO"],
1474
+ warn: [import_api4.SeverityNumber.WARN, "WARN"],
1475
+ warning: [import_api4.SeverityNumber.WARN, "WARN"],
1476
+ error: [import_api4.SeverityNumber.ERROR, "ERROR"],
1477
+ err: [import_api4.SeverityNumber.ERROR, "ERROR"],
1478
+ crit: [import_api4.SeverityNumber.FATAL, "FATAL"],
1479
+ critical: [import_api4.SeverityNumber.FATAL, "FATAL"],
1480
+ fatal: [import_api4.SeverityNumber.FATAL, "FATAL"],
1481
+ emerg: [import_api4.SeverityNumber.FATAL, "FATAL"],
1482
+ alert: [import_api4.SeverityNumber.FATAL, "FATAL"]
1483
+ };
1484
+ var NUMERIC = [[60, "fatal"], [50, "error"], [40, "warn"], [30, "info"], [20, "debug"], [0, "trace"]];
1485
+ var ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
1486
+ var NEST = /^\[Nest\]\s+\d+\s+-\s+.*?\s+(LOG|ERROR|WARN|DEBUG|VERBOSE|FATAL)\s+(?:\[([^\]]+)\]\s+)?([\s\S]*)$/;
1487
+ var WORD = /(?:^|[\s[(|:=])(trace|verbose|debug|info|notice|warn(?:ing)?|err(?:or)?|crit(?:ical)?|fatal|emerg|alert)(?=$|[\s\]):|,])/i;
1488
+ var MAX_LINE2 = 32 * 1024;
1489
+ var FLUSH_MS = 200;
1490
+ function levelOf(value) {
1491
+ if (typeof value === "number") {
1492
+ const found = NUMERIC.find(([n]) => value >= n);
1493
+ return found ? LEVELS2[found[1]] : null;
1494
+ }
1495
+ return typeof value === "string" ? LEVELS2[value.toLowerCase()] ?? null : null;
1496
+ }
1497
+ function parseLine(raw) {
1498
+ const line = raw.replace(ANSI, "").replace(/\s+$/, "");
1499
+ if (line.startsWith("{") && line.endsWith("}")) {
1500
+ try {
1501
+ const record = JSON.parse(line);
1502
+ const message = record.msg ?? record.message ?? record.event;
1503
+ return {
1504
+ level: levelOf(record.level ?? record.severity ?? record.lvl),
1505
+ body: typeof message === "string" ? message : line,
1506
+ attributes: {}
1507
+ };
1508
+ } catch {
1509
+ }
1510
+ }
1511
+ const nest = NEST.exec(line);
1512
+ if (nest) {
1513
+ return {
1514
+ level: LEVELS2[nest[1].toLowerCase()],
1515
+ body: nest[3],
1516
+ attributes: nest[2] ? { "log.logger": nest[2] } : {}
1517
+ };
1518
+ }
1519
+ const word = WORD.exec(line.slice(0, 120));
1520
+ return { level: word ? LEVELS2[word[1].toLowerCase()] ?? null : null, body: line, attributes: {} };
1521
+ }
1522
+ var SentLineProcessor = class {
1523
+ onEmit(record) {
1524
+ const source = record.attributes?.["log.source"];
1525
+ if (source !== "stdout" && source !== "stderr") rememberSent(record.body);
1526
+ }
1527
+ forceFlush() {
1528
+ return Promise.resolve();
1529
+ }
1530
+ shutdown() {
1531
+ return Promise.resolve();
1532
+ }
1533
+ };
1534
+ function captureOutput(logger) {
1535
+ const undo = [];
1536
+ for (const [stream, name, fallback] of [
1537
+ [process.stdout, "stdout", LEVELS2.info],
1538
+ [process.stderr, "stderr", LEVELS2.warn]
1539
+ ]) {
1540
+ if (!stream || typeof stream.write !== "function" || stream.write.__zharp) continue;
1541
+ const original2 = stream.write;
1542
+ let pending = "";
1543
+ let pendingContext;
1544
+ let timer;
1545
+ const emitLine = (line, ctx) => {
1546
+ if (!line.trim() || line.includes("[Zharp]") || alreadySent(line)) return;
1547
+ const parsed2 = parseLine(line.length > MAX_LINE2 ? line.slice(0, MAX_LINE2) : line);
1548
+ if (!parsed2.body.trim()) return;
1549
+ const [severityNumber, severityText] = parsed2.level ?? fallback;
1550
+ quiet(() => logger.emit({
1551
+ severityNumber,
1552
+ severityText,
1553
+ body: parsed2.body,
1554
+ attributes: { "log.source": name, "log.iostream": name, ...parsed2.attributes },
1555
+ ...ctx ? { context: ctx } : {}
1556
+ }));
1557
+ };
1558
+ const flush = () => {
1559
+ timer = void 0;
1560
+ const line = pending;
1561
+ const ctx = pendingContext;
1562
+ pending = "";
1563
+ pendingContext = void 0;
1564
+ emitLine(line, ctx);
1565
+ };
1566
+ const take = (chunk, encoding) => {
1567
+ if (isQuiet()) return;
1568
+ const text = typeof chunk === "string" ? chunk : chunk instanceof Uint8Array ? Buffer.from(chunk).toString(typeof encoding === "string" ? encoding : "utf8") : "";
1569
+ if (!text) return;
1570
+ if (!pending) pendingContext = import_api4.context.active();
1571
+ pending += text;
1572
+ const lines = pending.split("\n");
1573
+ pending = lines.pop() ?? "";
1574
+ const ctx = pendingContext;
1575
+ if (pending) pendingContext = import_api4.context.active();
1576
+ for (const line of lines) emitLine(line, ctx);
1577
+ if (pending.length > MAX_LINE2) flush();
1578
+ else if (pending && !timer) {
1579
+ timer = setTimeout(flush, FLUSH_MS);
1580
+ timer.unref?.();
1581
+ }
1582
+ };
1583
+ const patched = function(chunk, encoding, callback) {
1584
+ try {
1585
+ take(chunk, encoding);
1586
+ } catch {
1587
+ }
1588
+ return original2.call(this ?? stream, chunk, encoding, callback);
1589
+ };
1590
+ patched.__zharp = true;
1591
+ stream.write = patched;
1592
+ undo.push(() => {
1593
+ if (timer) clearTimeout(timer);
1594
+ if (pending) flush();
1595
+ stream.write = original2;
1596
+ });
1597
+ }
1598
+ return () => undo.forEach((fn) => fn());
1599
+ }
1600
+ function stampOutput() {
1601
+ const undo = [];
1602
+ for (const stream of [process.stdout, process.stderr]) {
1603
+ if (!stream || typeof stream.write !== "function" || stream.write.__zharpStamp) continue;
1604
+ const original2 = stream.write;
1605
+ const patched = function(chunk, encoding, callback) {
1606
+ let out = chunk;
1607
+ try {
1608
+ out = stamped(chunk, encoding);
1609
+ } catch {
1610
+ }
1611
+ return original2.call(this ?? stream, out, encoding, callback);
1612
+ };
1613
+ patched.__zharpStamp = true;
1614
+ stream.write = patched;
1615
+ undo.push(() => {
1616
+ stream.write = original2;
1617
+ });
1618
+ }
1619
+ return () => undo.forEach((fn) => fn());
1620
+ }
1621
+ function stamped(chunk, encoding) {
1622
+ const span = import_api4.trace.getActiveSpan()?.spanContext();
1623
+ if (!span || !(0, import_api4.isSpanContextValid)(span)) return chunk;
1624
+ const isBytes = chunk instanceof Uint8Array;
1625
+ if (typeof chunk !== "string" && !isBytes) return chunk;
1626
+ const enc = typeof encoding === "string" && Buffer.isEncoding(encoding) ? encoding : "utf8";
1627
+ if (isBytes && enc !== "utf8") return chunk;
1628
+ const text = isBytes ? Buffer.from(chunk).toString("utf8") : chunk;
1629
+ if (!text.includes("\n")) return chunk;
1630
+ const parts = text.split("\n");
1631
+ let last = -1;
1632
+ for (let i = parts.length - 2; i >= 0; i--) {
1633
+ if (parts[i].trim()) {
1634
+ last = i;
1635
+ break;
1636
+ }
1637
+ }
1638
+ let changed = false;
1639
+ for (let i = 0; i < parts.length - 1; i++) {
1640
+ if (i !== last && !parts[i].trimStart().startsWith("{")) continue;
1641
+ const next = stampLine(parts[i], span.traceId, span.spanId);
1642
+ if (next !== parts[i]) {
1643
+ parts[i] = next;
1644
+ changed = true;
1645
+ }
1646
+ }
1647
+ if (!changed) return chunk;
1648
+ const joined = parts.join("\n");
1649
+ return isBytes ? Buffer.from(joined, "utf8") : joined;
1650
+ }
1651
+ function stampLine(line, traceId, spanId) {
1652
+ const cr = line.endsWith("\r") ? "\r" : "";
1653
+ const body = cr ? line.slice(0, -1) : line;
1654
+ const trimmed = body.trimEnd();
1655
+ if (!trimmed.trim() || body.includes("trace_id") || body.includes("[Zharp]")) return line;
1656
+ if (trimmed.endsWith("}")) {
1657
+ if (!trimmed.trimStart().startsWith("{")) return line;
1658
+ const close = trimmed.lastIndexOf("}");
1659
+ const inner = trimmed.slice(trimmed.indexOf("{") + 1, close).trim();
1660
+ const fields = `"trace_id":"${traceId}","span_id":"${spanId}"`;
1661
+ return `${trimmed.slice(0, close)}${inner ? "," : ""}${fields}}${body.slice(trimmed.length)}${cr}`;
1662
+ }
1663
+ return `${trimmed} trace_id=${traceId} span_id=${spanId}${body.slice(trimmed.length)}${cr}`;
1664
+ }
1665
+
852
1666
  // ../../internal/src/debug-ids.ts
853
1667
  var DEBUG_IDS_ATTRIBUTE = "zharp.debug_ids";
854
- var files = /* @__PURE__ */ new Map();
1668
+ var files2 = /* @__PURE__ */ new Map();
855
1669
  var parsed = /* @__PURE__ */ new Set();
856
1670
  function registry() {
857
1671
  const g2 = typeof globalThis !== "undefined" ? globalThis : void 0;
@@ -890,7 +1704,7 @@ function refresh() {
890
1704
  for (const line of stack.split("\n")) {
891
1705
  const file = frameFile(line);
892
1706
  if (file) {
893
- files.set(file, id);
1707
+ files2.set(file, id);
894
1708
  break;
895
1709
  }
896
1710
  }
@@ -900,10 +1714,10 @@ function debugIdsFor(stack) {
900
1714
  if (!stack) return void 0;
901
1715
  try {
902
1716
  refresh();
903
- if (files.size === 0) return void 0;
1717
+ if (files2.size === 0) return void 0;
904
1718
  let out;
905
1719
  for (const file of stackFiles(stack)) {
906
- const id = files.get(file);
1720
+ const id = files2.get(file);
907
1721
  if (id) (out ??= {})[file] = id;
908
1722
  }
909
1723
  return out;
@@ -986,18 +1800,18 @@ function exceptionAttributes(error, handled) {
986
1800
  const cause = error.cause;
987
1801
  if (cause instanceof Error && cause.stack) stack += `
988
1802
  Caused by: ${cause.stack}`;
1803
+ const { stack: readable, context: context3 } = sourced(stack);
989
1804
  return {
990
1805
  "exception.type": type,
991
1806
  "exception.message": message,
992
- "exception.stacktrace": stack,
1807
+ "exception.stacktrace": readable,
993
1808
  "zharp.handled": handled ? "true" : "false",
994
- ...debugIdAttributes(stack)
1809
+ // From the stack as it ran: frames resolved here keep their bundle's ID for uploaded maps.
1810
+ ...debugIdAttributes(stack),
1811
+ ...context3 ? { [SOURCE_CONTEXT_ATTRIBUTE]: context3 } : {}
995
1812
  };
996
1813
  }
997
1814
 
998
- // src/version.ts
999
- var VERSION = "0.2.0";
1000
-
1001
1815
  // src/zharp.ts
1002
1816
  var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
1003
1817
  var EXIT_FLUSH_MS = 2e3;
@@ -1012,6 +1826,8 @@ var ZharpNode = class {
1012
1826
  tracing = true;
1013
1827
  /** Errors already sent, so one that is both rejected and then thrown is reported once. */
1014
1828
  reported = /* @__PURE__ */ new WeakSet();
1829
+ /** Failed queries waiting to be reported, once and with their call site. */
1830
+ dbErrors = null;
1015
1831
  /** `Zharp.log.info("Order placed", { orderId })` — and debug, warn, error, fatal, trace. */
1016
1832
  log = {
1017
1833
  trace: (m, a) => this.emit("trace", m, a),
@@ -1057,23 +1873,34 @@ var ZharpNode = class {
1057
1873
  const endpoint = (pick(options.endpoint, nodeEnv("ZHARP_ENDPOINT")) ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
1058
1874
  const tracing = tracingEnabled(options.tracing);
1059
1875
  this.tracing = tracing;
1876
+ const sendLogs = switchOn(options.logs, "ZHARP_LOGS", false);
1877
+ const correlation = switchOn(options.logCorrelation, "ZHARP_LOG_CORRELATION", true);
1878
+ const bridges = logBridges(sendLogs, correlation, options.instrumentations);
1060
1879
  if (options.debug) {
1061
1880
  const out = { error: console.error, warn: console.warn, info: console.info, debug: console.debug, verbose: console.debug };
1062
1881
  const prefixed = Object.fromEntries(
1063
1882
  Object.entries(out).map(([level, fn]) => [level, (message, ...args) => fn.call(console, `[Zharp][otel] ${message}`, ...args)])
1064
1883
  );
1065
- import_api3.diag.setLogger(prefixed, import_api3.DiagLogLevel.DEBUG);
1884
+ import_api5.diag.setLogger(prefixed, import_api5.DiagLogLevel.DEBUG);
1066
1885
  }
1067
1886
  registerEsmHook();
1068
1887
  const headers = { Authorization: `Bearer ${key}` };
1069
1888
  const exporterOptions = { headers, compression: "gzip" };
1889
+ setSourceContext(switchOn(options.captureSourceContext, "ZHARP_CAPTURE_SOURCE_CONTEXT", true));
1890
+ const queryErrors = tracing && switchOn(options.captureQueryErrors, "ZHARP_CAPTURE_QUERY_ERRORS", true);
1891
+ this.dbErrors = queryErrors ? new DbErrorSpanProcessor((failure) => this.sendQueryError(failure, true, "error", { "zharp.mechanism": "db" })) : null;
1070
1892
  this.spanProcessors = tracing ? [
1071
1893
  new ContextSpanProcessor(this.store),
1894
+ // Before the database processor: a request that failed claims its query's error first.
1895
+ ...options.captureUncaught !== false ? [new RecordedExceptionsProcessor((error, spanContext, mechanism) => import_api5.context.with(import_api5.trace.setSpanContext(import_api5.context.active(), spanContext), () => this.report(error, false, "error", { "zharp.mechanism": mechanism }, true)))] : [],
1896
+ // Before the exporter: it keeps the query's scrubbed exception off the span.
1897
+ ...this.dbErrors ? [this.dbErrors] : [],
1072
1898
  new UrlRedactionSpanProcessor(),
1073
1899
  new DebugIdSpanProcessor(),
1074
1900
  new import_sdk_trace.BatchSpanProcessor({ exporter: new import_exporter_trace_otlp_proto.OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) })
1075
1901
  ] : [new ContextSpanProcessor(this.store)];
1076
1902
  this.logProcessors = [
1903
+ new SentLineProcessor(),
1077
1904
  new ContextLogProcessor(this.store),
1078
1905
  new DebugIdLogProcessor(),
1079
1906
  new import_sdk_logs.BatchLogRecordProcessor({ exporter: new import_exporter_logs_otlp_proto.OTLPLogExporter({ ...exporterOptions, url: `${endpoint}/v1/logs` }) })
@@ -1092,6 +1919,10 @@ var ZharpNode = class {
1092
1919
  propagators: [new import_core.W3CTraceContextPropagator(), new import_core.W3CBaggagePropagator()]
1093
1920
  });
1094
1921
  const bodies = bodySettings(options.captureBodies, nodeEnv("ZHARP_CAPTURE_BODIES"));
1922
+ const headerCapture = headerSettings(options.captureHeaders, nodeEnv("ZHARP_CAPTURE_HEADERS"));
1923
+ const ownHttp = options.instrumentations?.["@opentelemetry/instrumentation-http"];
1924
+ const withBodies = bodies ? withBodyCapture(bodies, ownHttp) : ownHttp;
1925
+ const httpConfig = headerCapture ? withHeaderCapture(headerCapture, withBodies) : withBodies;
1095
1926
  const rate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
1096
1927
  this.sdk = new import_sdk_node.NodeSDK({
1097
1928
  resource,
@@ -1111,16 +1942,23 @@ var ZharpNode = class {
1111
1942
  "@opentelemetry/instrumentation-net": { enabled: false },
1112
1943
  "@opentelemetry/instrumentation-fs": { enabled: false },
1113
1944
  ...options.instrumentations,
1114
- ...bodies && {
1115
- "@opentelemetry/instrumentation-http": withBodyCapture(bodies, options.instrumentations?.["@opentelemetry/instrumentation-http"])
1116
- }
1117
- }) : logsOnlyInstrumentations(options),
1945
+ ...bridges,
1946
+ ...httpConfig && { "@opentelemetry/instrumentation-http": httpConfig }
1947
+ }) : logsOnlyInstrumentations({ ...options, instrumentations: { ...options.instrumentations, ...bridges } }),
1948
+ ...this.dbErrors ? [new DbDriverErrorsInstrumentation((traceId, error) => this.dbErrors?.attach(traceId, error))] : [],
1949
+ ...tracing && options.captureUncaught !== false ? [new FrameworkErrorsInstrumentation((error, mechanism) => this.report(error, false, "error", { "zharp.mechanism": mechanism }, true))] : [],
1118
1950
  ...options.extraInstrumentations ?? []
1119
1951
  ]
1120
1952
  });
1121
1953
  this.sdk.start();
1122
- this.logger = import_api3.logs.getLogger("@zharp/node", VERSION);
1123
- if (options.captureConsole !== false) this.teardowns.push(captureConsole(this.logger));
1954
+ this.logger = import_api5.logs.getLogger("@zharp/node", VERSION);
1955
+ if (correlation) this.teardowns.push(stampOutput());
1956
+ if (sendLogs) {
1957
+ if (options.captureConsole !== false) this.teardowns.push(captureConsole(this.logger));
1958
+ if (options.captureOutput !== false && nodeEnv("ZHARP_CAPTURE_OUTPUT") !== "false") {
1959
+ this.teardowns.push(captureOutput(this.logger));
1960
+ }
1961
+ }
1124
1962
  if (options.captureUncaught !== false) this.teardowns.push(this.captureProcessErrors());
1125
1963
  this.teardowns.push(this.flushOnExit());
1126
1964
  announce(`Application monitoring active${tracing ? "" : " (logs only)"} \u2014 ${describeTarget(service, environment)}`);
@@ -1156,16 +1994,36 @@ var ZharpNode = class {
1156
1994
  captureError(error, attributes) {
1157
1995
  this.report(error, true, "error", attributes);
1158
1996
  }
1997
+ /**
1998
+ * Next.js (15+): errors a route handler, server component, server action or middleware threw,
1999
+ * which Next answers with an error page and only prints. Export it from instrumentation.ts:
2000
+ *
2001
+ * export const onRequestError = Zharp.onRequestError;
2002
+ *
2003
+ * Each is reported once as a crash, with the request's path, method and route. A bound function,
2004
+ * so it can be exported as it is.
2005
+ */
2006
+ onRequestError = (error, request, context3) => {
2007
+ this.report(error, false, "error", {
2008
+ "zharp.mechanism": "nextjs",
2009
+ ...request?.method ? { "http.request.method": request.method } : {},
2010
+ ...request?.path ? { "url.path": request.path } : {},
2011
+ ...context3?.routePath ? { "http.route": context3.routePath } : {},
2012
+ ...context3?.routeType ? { "next.route_type": context3.routeType } : {},
2013
+ ...context3?.routerKind ? { "next.router_kind": context3.routerKind } : {},
2014
+ ...context3?.renderSource ? { "next.render_source": context3.renderSource } : {}
2015
+ }, true);
2016
+ };
1159
2017
  /**
1160
2018
  * Run `fn` inside a span named `name`, which ends when `fn` returns or its promise settles. A
1161
2019
  * throw or rejection marks the span as failed and is passed on unchanged.
1162
2020
  */
1163
2021
  startSpan(name, fn, options = {}) {
1164
- if (!this.tracing) return fn(import_api3.trace.wrapSpanContext(import_api3.trace.getActiveSpan()?.spanContext() ?? import_api3.INVALID_SPAN_CONTEXT));
1165
- const tracer = import_api3.trace.getTracer("@zharp/node", VERSION);
2022
+ if (!this.tracing) return fn(import_api5.trace.wrapSpanContext(import_api5.trace.getActiveSpan()?.spanContext() ?? import_api5.INVALID_SPAN_CONTEXT));
2023
+ const tracer = import_api5.trace.getTracer("@zharp/node", VERSION);
1166
2024
  return tracer.startActiveSpan(name, options, (span) => {
1167
2025
  const fail = (error) => {
1168
- span.setStatus({ code: import_api3.SpanStatusCode.ERROR, message: asError(error).message });
2026
+ span.setStatus({ code: import_api5.SpanStatusCode.ERROR, message: asError(error).message });
1169
2027
  span.end();
1170
2028
  };
1171
2029
  let result;
@@ -1195,7 +2053,7 @@ var ZharpNode = class {
1195
2053
  async flush(timeoutMs = 5e3) {
1196
2054
  const all = Promise.all([...this.spanProcessors, ...this.logProcessors].map((p) => p.forceFlush().catch(() => {
1197
2055
  })));
1198
- await Promise.race([all, new Promise((resolve) => setTimeout(resolve, timeoutMs).unref())]);
2056
+ await Promise.race([all, new Promise((resolve2) => setTimeout(resolve2, timeoutMs).unref())]);
1199
2057
  }
1200
2058
  /** Flush, stop, and put back everything that was patched. */
1201
2059
  async shutdown() {
@@ -1227,14 +2085,20 @@ var ZharpNode = class {
1227
2085
  } catch {
1228
2086
  }
1229
2087
  }
1230
- report(value, handled, level, attributes) {
2088
+ report(value, handled, level, attributes, fromFramework = false) {
1231
2089
  try {
1232
2090
  if (!this.logger) return;
1233
- const error = asError(value);
1234
- if (value && typeof value === "object") {
1235
- if (this.reported.has(value)) return;
1236
- this.reported.add(value);
2091
+ if (value && typeof value === "object" && this.reported.has(value)) return;
2092
+ const traceId = import_api5.trace.getActiveSpan()?.spanContext().traceId;
2093
+ const failure = this.dbErrors?.consume(traceId, value, fromFramework);
2094
+ if (failure) {
2095
+ if (value && typeof value === "object") this.reported.add(value);
2096
+ this.sendQueryError(failure, handled, level, attributes);
2097
+ if (!handled) import_api5.trace.getActiveSpan()?.setStatus({ code: import_api5.SpanStatusCode.ERROR, message: failure.error?.message ?? "The query failed" });
2098
+ return;
1237
2099
  }
2100
+ const error = asError(value);
2101
+ if (value && typeof value === "object") this.reported.add(value);
1238
2102
  const exception = exceptionAttributes(error, handled);
1239
2103
  this.logger.emit({
1240
2104
  severityNumber: SEVERITY[level],
@@ -1242,7 +2106,33 @@ var ZharpNode = class {
1242
2106
  body: `${exception["exception.type"]}: ${exception["exception.message"]}`,
1243
2107
  attributes: { ...attributes, ...exception }
1244
2108
  });
1245
- if (!handled) import_api3.trace.getActiveSpan()?.setStatus({ code: import_api3.SpanStatusCode.ERROR, message: error.message });
2109
+ if (!handled) import_api5.trace.getActiveSpan()?.setStatus({ code: import_api5.SpanStatusCode.ERROR, message: error.message });
2110
+ } catch {
2111
+ }
2112
+ }
2113
+ /** A failed query as an error, in the query's own span so the error shows the query. */
2114
+ sendQueryError(failure, handled, level = "error", attributes) {
2115
+ try {
2116
+ if (!this.logger) return;
2117
+ if (failure.error) {
2118
+ if (this.reported.has(failure.error) && handled) return;
2119
+ this.reported.add(failure.error);
2120
+ }
2121
+ const report = reportOf(failure);
2122
+ this.logger.emit({
2123
+ severityNumber: SEVERITY[level],
2124
+ severityText: level.toUpperCase(),
2125
+ body: `${report.type}: ${report.message}`,
2126
+ attributes: {
2127
+ ...report.attributes,
2128
+ ...attributes,
2129
+ "exception.type": report.type,
2130
+ "exception.message": report.message,
2131
+ "exception.stacktrace": report.stack,
2132
+ "zharp.handled": handled ? "true" : "false"
2133
+ },
2134
+ context: import_api5.trace.setSpanContext(import_api5.context.active(), report.spanContext)
2135
+ });
1246
2136
  } catch {
1247
2137
  }
1248
2138
  }
@@ -1346,6 +2236,25 @@ function registerEsmHook() {
1346
2236
  } catch {
1347
2237
  }
1348
2238
  }
2239
+ function switchOn(option, variable, fallback) {
2240
+ if (typeof option === "boolean") return option;
2241
+ const value = nodeEnv(variable);
2242
+ if (value && /^(true|1|yes|on)$/i.test(value)) return true;
2243
+ if (value && /^(false|0|no|off)$/i.test(value)) return false;
2244
+ return fallback;
2245
+ }
2246
+ function logBridges(sendLogs, correlation, own = {}) {
2247
+ const config = (name) => ({
2248
+ disableLogSending: !sendLogs,
2249
+ disableLogCorrelation: !correlation,
2250
+ ...own[name]
2251
+ });
2252
+ return {
2253
+ "@opentelemetry/instrumentation-pino": config("@opentelemetry/instrumentation-pino"),
2254
+ "@opentelemetry/instrumentation-winston": config("@opentelemetry/instrumentation-winston"),
2255
+ "@opentelemetry/instrumentation-bunyan": config("@opentelemetry/instrumentation-bunyan")
2256
+ };
2257
+ }
1349
2258
  function tracingEnabled(option) {
1350
2259
  if (typeof option === "boolean") return option;
1351
2260
  const value = nodeEnv("ZHARP_TRACING");
@@ -1382,8 +2291,8 @@ var ExtractOnlyPropagator = class {
1382
2291
  inner;
1383
2292
  inject() {
1384
2293
  }
1385
- extract(context, carrier, getter) {
1386
- return this.inner.extract(context, carrier, getter);
2294
+ extract(context3, carrier, getter) {
2295
+ return this.inner.extract(context3, carrier, getter);
1387
2296
  }
1388
2297
  fields() {
1389
2298
  return [];