@autter/runtime-node 1.7.0 → 1.9.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.
@@ -1,8 +1,8 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2;
2
2
 
3
3
 
4
4
 
5
- var _chunkGYTQLITWcjs = require('./chunk-GYTQLITW.cjs');
5
+ var _chunkBHYHORUDcjs = require('./chunk-BHYHORUD.cjs');
6
6
 
7
7
  // ../runtime-core/dist/index.js
8
8
  var SENSITIVE_KEY_PATTERNS = [
@@ -132,8 +132,8 @@ function redactArray(value, r, state, depth) {
132
132
  state.ancestors.delete(value);
133
133
  return r.mask;
134
134
  }
135
- const limit = Math.min(length, MAX_COLLECTION_ENTRIES);
136
- for (let i = 0; i < limit; i += 1) {
135
+ const limit2 = Math.min(length, MAX_COLLECTION_ENTRIES);
136
+ for (let i = 0; i < limit2; i += 1) {
137
137
  let item;
138
138
  try {
139
139
  item = value[i];
@@ -143,7 +143,7 @@ function redactArray(value, r, state, depth) {
143
143
  }
144
144
  out.push(redactValue(item, r, state, depth + 1));
145
145
  }
146
- if (length > limit) {
146
+ if (length > limit2) {
147
147
  out.push(r.mask);
148
148
  }
149
149
  state.ancestors.delete(value);
@@ -392,6 +392,53 @@ function toSpanAttributes(context) {
392
392
  ])
393
393
  );
394
394
  }
395
+ var DEBUG_IDS_ATTRIBUTE = "autter.debug_ids";
396
+ var REGISTRY = "_autterDebugIds";
397
+ var pathOfKey = /* @__PURE__ */ new Map();
398
+ function withoutPosition(location) {
399
+ const match = /^(.*?):\d+:\d+$/.exec(location.trim());
400
+ return _optionalChain([match, 'optionalAccess', _6 => _6[1]]) ? match[1] : null;
401
+ }
402
+ function firstFramePath(stack) {
403
+ for (const raw of stack.split("\n")) {
404
+ const line = raw.trim();
405
+ if (line.startsWith("at ")) {
406
+ const body = line.slice(3).trim();
407
+ const withFn = /^(.*?)\s+\((.*)\)$/.exec(body);
408
+ const path = withoutPosition(withFn ? withFn[2] : body.replace(/^async /, ""));
409
+ if (path) return path;
410
+ continue;
411
+ }
412
+ const at = line.lastIndexOf("@");
413
+ if (at >= 0) {
414
+ const path = withoutPosition(line.slice(at + 1));
415
+ if (path) return path;
416
+ }
417
+ }
418
+ return null;
419
+ }
420
+ function debugIdsForStacks(stacks) {
421
+ try {
422
+ const registry = globalThis[REGISTRY];
423
+ if (!registry || typeof registry !== "object") return void 0;
424
+ const texts = stacks.filter((stack) => typeof stack === "string" && stack !== "");
425
+ if (texts.length === 0) return void 0;
426
+ let found;
427
+ for (const key of Object.keys(registry)) {
428
+ const id = registry[key];
429
+ if (typeof id !== "string" || !id) continue;
430
+ let path = pathOfKey.get(key);
431
+ if (path === void 0) {
432
+ path = firstFramePath(key);
433
+ pathOfKey.set(key, path);
434
+ }
435
+ if (path && texts.some((stack) => stack.includes(path))) (found ??= {})[path] = id;
436
+ }
437
+ return found;
438
+ } catch (e9) {
439
+ return void 0;
440
+ }
441
+ }
395
442
  var CODE_PATTERN = /^[a-z][a-z0-9_]*(\.[a-z0-9_]+){0,3}$/;
396
443
  var CODE_MAX_LENGTH = 80;
397
444
  var WHY_MAX = 1e3;
@@ -410,7 +457,7 @@ function warnInvalidCode(code) {
410
457
  console.warn(
411
458
  `[autter-runtime] error code ${JSON.stringify(key)} does not match ${CODE_PATTERN} (max ${CODE_MAX_LENGTH} chars); it is dropped and the error groups by message`
412
459
  );
413
- } catch (e9) {
460
+ } catch (e10) {
414
461
  }
415
462
  }
416
463
  var RuntimeError = class extends Error {
@@ -459,13 +506,13 @@ function defineRuntimeErrors(namespace, catalog) {
459
506
  const build = (definition, extras) => {
460
507
  const error = new RuntimeError({
461
508
  ...definition,
462
- ..._optionalChain([extras, 'optionalAccess', _6 => _6.message]) !== void 0 ? { message: extras.message } : {},
509
+ ..._optionalChain([extras, 'optionalAccess', _7 => _7.message]) !== void 0 ? { message: extras.message } : {},
463
510
  ...valid ? { code } : {},
464
- ..._optionalChain([extras, 'optionalAccess', _7 => _7.cause]) !== void 0 ? { cause: extras.cause } : {},
465
- ..._optionalChain([extras, 'optionalAccess', _8 => _8.internal]) !== void 0 ? { internal: extras.internal } : {}
511
+ ..._optionalChain([extras, 'optionalAccess', _8 => _8.cause]) !== void 0 ? { cause: extras.cause } : {},
512
+ ..._optionalChain([extras, 'optionalAccess', _9 => _9.internal]) !== void 0 ? { internal: extras.internal } : {}
466
513
  });
467
514
  const captureStackTrace = Error.captureStackTrace;
468
- _optionalChain([captureStackTrace, 'optionalCall', _9 => _9(error, factory)]);
515
+ _optionalChain([captureStackTrace, 'optionalCall', _10 => _10(error, factory)]);
469
516
  return error;
470
517
  };
471
518
  const factory = typeof entry === "function" ? (args, extras) => build(entry(args), extras) : (extras) => build(entry, extras);
@@ -481,7 +528,7 @@ function isError(value) {
481
528
  const native = Error.isError;
482
529
  if (typeof native === "function") return native(value) === true;
483
530
  return Object.prototype.toString.call(value) === "[object Error]";
484
- } catch (e10) {
531
+ } catch (e11) {
485
532
  return false;
486
533
  }
487
534
  }
@@ -495,7 +542,7 @@ function field(err, key) {
495
542
  if (!err || typeof err !== "object") return void 0;
496
543
  try {
497
544
  return err[key];
498
- } catch (e11) {
545
+ } catch (e12) {
499
546
  return void 0;
500
547
  }
501
548
  }
@@ -514,6 +561,13 @@ function errorStatusOf(err) {
514
561
  function isExpectedError(err) {
515
562
  return field(err, "expected") === true;
516
563
  }
564
+ var STACK_ATTRIBUTE_RE = /^exception\.cause\.\d+\.stacktrace$|^autter\.debug_ids$/;
565
+ function stackAttributesLast(attributes) {
566
+ const head = {};
567
+ const tail = {};
568
+ for (const [key, value] of Object.entries(attributes)) (STACK_ATTRIBUTE_RE.test(key) ? tail : head)[key] = value;
569
+ return { ...head, ...tail };
570
+ }
517
571
  function errorAttributes(err, options = {}) {
518
572
  const out = {};
519
573
  if (!err || typeof err !== "object") return out;
@@ -530,21 +584,33 @@ function errorAttributes(err, options = {}) {
530
584
  const expected = field(err, "expected");
531
585
  if (typeof expected === "boolean") out["autter.error.expected"] = expected;
532
586
  if (options.causes !== false) {
587
+ const stacks = options.stacks !== false;
588
+ const ownStack = field(err, "stack");
589
+ const allStacks = typeof ownStack === "string" && ownStack ? [ownStack] : [];
533
590
  let cause = field(err, "cause");
534
591
  const seen = /* @__PURE__ */ new Set([err]);
535
592
  for (let n = 1; n <= CAUSE_DEPTH && cause !== void 0 && cause !== null; n++) {
536
593
  if (seen.has(cause)) break;
537
594
  seen.add(cause);
538
595
  const isError2 = typeof cause === "object";
539
- const type = isError2 ? String(_nullishCoalesce(_nullishCoalesce(field(cause, "name"), () => ( _optionalChain([cause, 'access', _10 => _10.constructor, 'optionalAccess', _11 => _11.name]))), () => ( "Error"))) : typeof cause;
596
+ const type = isError2 ? String(_nullishCoalesce(_nullishCoalesce(field(cause, "name"), () => ( _optionalChain([cause, 'access', _11 => _11.constructor, 'optionalAccess', _12 => _12.name]))), () => ( "Error"))) : typeof cause;
540
597
  const message = isError2 ? field(cause, "message") : cause;
541
598
  out[`exception.cause.${n}.type`] = type.slice(0, 200);
542
599
  out[`exception.cause.${n}.message`] = String(_nullishCoalesce(message, () => ( ""))).slice(0, 1e3);
543
600
  const causeCode = field(cause, "code");
544
601
  if (typeof causeCode === "string" && causeCode)
545
602
  out[`exception.cause.${n}.code`] = causeCode.slice(0, CODE_MAX_LENGTH);
603
+ const causeStack = isError2 ? field(cause, "stack") : void 0;
604
+ if (stacks && typeof causeStack === "string" && causeStack) {
605
+ out[`exception.cause.${n}.stacktrace`] = causeStack;
606
+ allStacks.push(causeStack);
607
+ }
546
608
  cause = isError2 ? field(cause, "cause") : void 0;
547
609
  }
610
+ if (stacks) {
611
+ const ids = debugIdsForStacks(allStacks);
612
+ if (ids) out[DEBUG_IDS_ATTRIBUTE] = JSON.stringify(ids);
613
+ }
548
614
  }
549
615
  return out;
550
616
  }
@@ -712,7 +778,7 @@ var REQUEST_ID_PATTERN = /^[\w.-]{8,128}$/;
712
778
  var DEFAULT_REQUEST_ID_HEADER = "x-request-id";
713
779
  function randomId() {
714
780
  const c = globalThis.crypto;
715
- if (_optionalChain([c, 'optionalAccess', _12 => _12.randomUUID])) return c.randomUUID();
781
+ if (_optionalChain([c, 'optionalAccess', _13 => _13.randomUUID])) return c.randomUUID();
716
782
  return "10000000-1000-4000-8000-100000000000".replace(
717
783
  /[018]/g,
718
784
  (d) => (Number(d) ^ Math.random() * 16 >> Number(d) / 4).toString(16)
@@ -758,6 +824,7 @@ function requestOutcome(input) {
758
824
  if (input.error !== void 0 && isExpectedError(input.error)) return "degraded";
759
825
  if (input.thrown || input.status !== void 0 && input.status >= 500)
760
826
  return "failed";
827
+ if (input.degraded) return "degraded";
761
828
  if (input.aborted) return "cancelled";
762
829
  return "succeeded";
763
830
  }
@@ -791,7 +858,7 @@ function parseCarrier(input) {
791
858
  if (value.length > 1024) return null;
792
859
  try {
793
860
  value = JSON.parse(value);
794
- } catch (e12) {
861
+ } catch (e13) {
795
862
  return null;
796
863
  }
797
864
  }
@@ -900,7 +967,7 @@ function normalizeBreadcrumb(input, redact3, options = {}) {
900
967
  message: scrubber(redact3)(message, MAX_MESSAGE),
901
968
  ...data ? { data } : {}
902
969
  };
903
- } catch (e13) {
970
+ } catch (e14) {
904
971
  return null;
905
972
  }
906
973
  }
@@ -913,7 +980,7 @@ function sanitizeBreadcrumbs(raw, redact3) {
913
980
  const crumb = normalizeBreadcrumb(raw[i], redact3, { requireAt: true });
914
981
  if (crumb) out.push(crumb);
915
982
  }
916
- } catch (e14) {
983
+ } catch (e15) {
917
984
  }
918
985
  return out.length ? out.reverse() : void 0;
919
986
  }
@@ -974,6 +1041,169 @@ function splitFingerprint(attributes) {
974
1041
  const { fingerprint, ...rest } = attributes;
975
1042
  return { attributes: rest, fingerprint };
976
1043
  }
1044
+ var HANDLED_ATTRIBUTE = "autter.handled";
1045
+ var HANDLING_ATTRIBUTE = "autter.handling";
1046
+ var LOG_SOURCE_ATTRIBUTE = "autter.log.source";
1047
+ var LOG_MESSAGE_ATTRIBUTE = "autter.log.message";
1048
+ var DEGRADED_REASON_ATTRIBUTE = "autter.degraded.reason";
1049
+ var CAUGHT_DROPPED_ATTRIBUTE = "autter.caught.dropped";
1050
+ var LOG_MESSAGE_MAX = 1e3;
1051
+ var DEGRADED_REASON_MAX = 500;
1052
+ var CAUGHT_BURST = 10;
1053
+ var CAUGHT_REFILL_MS = 1e4;
1054
+ var SOURCES = ["console", "pino", "winston", "bunyan", "runtimeLogger"];
1055
+ function loggedErrorSources(option) {
1056
+ const out = {};
1057
+ for (const source of SOURCES)
1058
+ out[source] = option === false ? false : option === void 0 || option === true || typeof option !== "object" ? true : option[source] !== false;
1059
+ return out;
1060
+ }
1061
+ function handledErrorKind(error) {
1062
+ let type = "Error";
1063
+ let site = "";
1064
+ try {
1065
+ if (isError(error)) {
1066
+ type = String(error.name || "Error").slice(0, 200);
1067
+ const lines = String(_nullishCoalesce(error.stack, () => ( ""))).split("\n");
1068
+ site = (_nullishCoalesce(_nullishCoalesce(lines.find((line) => /^\s*at\s/.test(line)), () => ( lines[1])), () => ( ""))).trim().slice(0, 300);
1069
+ }
1070
+ } catch (e16) {
1071
+ }
1072
+ return { key: `${type}
1073
+ ${site}`, type };
1074
+ }
1075
+ function caughtErrorAttributes(source, message, dropped = 0) {
1076
+ return {
1077
+ [HANDLED_ATTRIBUTE]: true,
1078
+ [HANDLING_ATTRIBUTE]: "caught",
1079
+ [LOG_SOURCE_ATTRIBUTE]: source,
1080
+ ...message ? { [LOG_MESSAGE_ATTRIBUTE]: message.slice(0, LOG_MESSAGE_MAX) } : {},
1081
+ ...dropped > 0 ? { [CAUGHT_DROPPED_ATTRIBUTE]: dropped } : {}
1082
+ };
1083
+ }
1084
+ function degradedAttributes(reason, dropped = 0) {
1085
+ let text = "";
1086
+ try {
1087
+ text = String(_nullishCoalesce(reason, () => ( "")));
1088
+ } catch (e17) {
1089
+ }
1090
+ return {
1091
+ [HANDLED_ATTRIBUTE]: true,
1092
+ [HANDLING_ATTRIBUTE]: "deliberate",
1093
+ [DEGRADED_REASON_ATTRIBUTE]: text.slice(0, DEGRADED_REASON_MAX) || "degraded",
1094
+ ...dropped > 0 ? { [CAUGHT_DROPPED_ATTRIBUTE]: dropped } : {}
1095
+ };
1096
+ }
1097
+ var BurstLimiter = (_class2 = class {
1098
+ constructor(burst = CAUGHT_BURST, refillMs = CAUGHT_REFILL_MS, maxKeys = 1e3) {;_class2.prototype.__init2.call(this);_class2.prototype.__init3.call(this);
1099
+ this.burst = burst;
1100
+ this.refillMs = refillMs;
1101
+ this.maxKeys = maxKeys;
1102
+ }
1103
+
1104
+
1105
+
1106
+ __init2() {this.buckets = /* @__PURE__ */ new Map()}
1107
+ __init3() {this.evicted = []}
1108
+ /**
1109
+ * -1 when the record is left out (and counted). Otherwise it is sent,
1110
+ * and the number of its kind left out since the last one sent is
1111
+ * returned, to report with it.
1112
+ */
1113
+ take(key, type, now = Date.now()) {
1114
+ const bucket = _nullishCoalesce(this.buckets.get(key), () => ( { tokens: this.burst, at: now, dropped: 0, type }));
1115
+ this.buckets.delete(key);
1116
+ this.buckets.set(key, bucket);
1117
+ this.refill(bucket, now);
1118
+ let result;
1119
+ if (bucket.tokens < 1) {
1120
+ bucket.dropped += 1;
1121
+ result = -1;
1122
+ } else {
1123
+ bucket.tokens -= 1;
1124
+ result = bucket.dropped;
1125
+ bucket.dropped = 0;
1126
+ }
1127
+ while (this.buckets.size > this.maxKeys) {
1128
+ const oldest = this.buckets.keys().next().value;
1129
+ const gone = this.buckets.get(oldest);
1130
+ this.buckets.delete(oldest);
1131
+ if (gone.dropped > 0) this.evicted.push({ key: oldest, type: gone.type, dropped: gone.dropped });
1132
+ }
1133
+ return result;
1134
+ }
1135
+ /**
1136
+ * Counts no sent record carried: kinds that have a token again (nothing
1137
+ * of theirs came along to carry the count) or, with `all`, every kind
1138
+ * with a count. The counts returned are reset.
1139
+ */
1140
+ drain(now = Date.now(), all = false) {
1141
+ const out = this.evicted;
1142
+ this.evicted = [];
1143
+ for (const [key, bucket] of this.buckets) {
1144
+ if (bucket.dropped === 0) continue;
1145
+ this.refill(bucket, now);
1146
+ if (!all && bucket.tokens < 1) continue;
1147
+ out.push({ key, type: bucket.type, dropped: bucket.dropped });
1148
+ bucket.dropped = 0;
1149
+ }
1150
+ return out;
1151
+ }
1152
+ /** When the next uncarried count can be drained, or null when none is pending. */
1153
+ nextDrainAt() {
1154
+ if (this.evicted.length) return 0;
1155
+ let next = null;
1156
+ for (const bucket of this.buckets.values()) {
1157
+ if (bucket.dropped === 0) continue;
1158
+ const at = bucket.at + Math.max(0, 1 - bucket.tokens) * this.refillMs;
1159
+ if (next === null || at < next) next = at;
1160
+ }
1161
+ return next;
1162
+ }
1163
+ refill(bucket, now) {
1164
+ if (now > bucket.at) {
1165
+ bucket.tokens = Math.min(this.burst, bucket.tokens + (now - bucket.at) / this.refillMs);
1166
+ bucket.at = now;
1167
+ }
1168
+ }
1169
+ }, _class2);
1170
+ function testPattern(pattern, type, message) {
1171
+ if (typeof pattern === "string") {
1172
+ return pattern !== "" && (message.includes(pattern) || type.includes(pattern));
1173
+ }
1174
+ if (!(pattern instanceof RegExp)) return false;
1175
+ const re = pattern.global || pattern.sticky ? new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, "")) : pattern;
1176
+ return re.test(message) || type !== "" && (re.test(type) || re.test(`${type}: ${message}`));
1177
+ }
1178
+ function isIgnoredError(patterns, type, message) {
1179
+ if (!_optionalChain([patterns, 'optionalAccess', _14 => _14.length])) return false;
1180
+ for (const pattern of patterns) {
1181
+ try {
1182
+ if (testPattern(pattern, type, message)) return true;
1183
+ } catch (e18) {
1184
+ }
1185
+ }
1186
+ return false;
1187
+ }
1188
+ function effectiveSampleRate(rate) {
1189
+ return typeof rate === "number" && Number.isFinite(rate) && rate >= 0 && rate < 1 ? rate : null;
1190
+ }
1191
+ function createErrorFilter(options = {}, random = Math.random) {
1192
+ const patterns = Array.isArray(options.ignoreErrors) ? options.ignoreErrors.slice() : [];
1193
+ const rate = effectiveSampleRate(options.sampleRate);
1194
+ if (!patterns.length && rate === null) return () => true;
1195
+ return (input) => {
1196
+ try {
1197
+ if (isIgnoredError(patterns, _nullishCoalesce(input.type, () => ( "")), _nullishCoalesce(input.message, () => ( "")))) return false;
1198
+ if (rate === null || input.crash) return true;
1199
+ const severity = _nullishCoalesce(input.severity, () => ( "error"));
1200
+ if (severity !== "error") return true;
1201
+ return random() < rate;
1202
+ } catch (e19) {
1203
+ return true;
1204
+ }
1205
+ };
1206
+ }
977
1207
 
978
1208
  // src/breadcrumbs.ts
979
1209
  var _api = require('@opentelemetry/api');
@@ -985,6 +1215,267 @@ var _crypto = require('crypto');
985
1215
 
986
1216
 
987
1217
 
1218
+ // src/caught-errors.ts
1219
+ var _module = require('module');
1220
+ var _path = require('path');
1221
+ var _util = require('util');
1222
+ var _requireinthemiddle = require('require-in-the-middle');
1223
+
1224
+ // src/captured.ts
1225
+ var CAPTURED = _chunkBHYHORUDcjs.sharedSlot.call(void 0, "requests", () => ({ captured: /* @__PURE__ */ new WeakSet() })).captured;
1226
+ function markCaptured(error) {
1227
+ if (error && typeof error === "object") CAPTURED.add(error);
1228
+ }
1229
+ function isCaptured(error) {
1230
+ return !!error && typeof error === "object" && CAPTURED.has(error);
1231
+ }
1232
+
1233
+ // src/caught-errors.ts
1234
+ var S = _chunkBHYHORUDcjs.sharedSlot.call(void 0, "handled", () => ({
1235
+ sources: null,
1236
+ capture: null,
1237
+ tail: null,
1238
+ limiter: new BurstLimiter(),
1239
+ decided: /* @__PURE__ */ new WeakSet(),
1240
+ timer: null,
1241
+ hooked: false
1242
+ }));
1243
+ var PATCHED = /* @__PURE__ */ Symbol.for("autter.runtime.logged-errors");
1244
+ function setHandledCapture(capture) {
1245
+ S.capture = capture;
1246
+ }
1247
+ function setHandledTail(tail) {
1248
+ S.tail = tail;
1249
+ }
1250
+ function scheduleTail() {
1251
+ if (S.timer) return;
1252
+ const at = S.limiter.nextDrainAt();
1253
+ if (at === null) return;
1254
+ S.timer = setTimeout(() => sendTails(false), Math.max(0, at - Date.now()) + 5);
1255
+ _optionalChain([S, 'access', _15 => _15.timer, 'access', _16 => _16.unref, 'optionalCall', _17 => _17()]);
1256
+ }
1257
+ function sendTails(all) {
1258
+ if (S.timer) clearTimeout(S.timer);
1259
+ S.timer = null;
1260
+ for (const tail of S.limiter.drain(Date.now(), all)) {
1261
+ try {
1262
+ _optionalChain([S, 'access', _18 => _18.tail, 'optionalCall', _19 => _19(tail.type, tail.dropped)]);
1263
+ } catch (e20) {
1264
+ }
1265
+ }
1266
+ if (!all) scheduleTail();
1267
+ }
1268
+ function limit(prefix, error) {
1269
+ const kind = handledErrorKind(error);
1270
+ const dropped = S.limiter.take(`${prefix}
1271
+ ${kind.key}`, kind.type);
1272
+ if (dropped < 0) scheduleTail();
1273
+ return dropped;
1274
+ }
1275
+ function reportLoggedError(error, source, message, attributes) {
1276
+ if (!_optionalChain([S, 'access', _20 => _20.sources, 'optionalAccess', _21 => _21[source]]) || !isError(error)) return;
1277
+ if (S.decided.has(error) || isCaptured(error)) return;
1278
+ S.decided.add(error);
1279
+ const run = () => {
1280
+ try {
1281
+ if (isCaptured(error) || !S.capture || !S.sources) return;
1282
+ const dropped = limit("caught", error);
1283
+ if (dropped < 0) return;
1284
+ markCaptured(error);
1285
+ S.capture(error, { ...attributes, ...caughtErrorAttributes(source, message, dropped) }, "error");
1286
+ } catch (e21) {
1287
+ }
1288
+ };
1289
+ try {
1290
+ setImmediate(run);
1291
+ } catch (e22) {
1292
+ }
1293
+ }
1294
+ function reportDegraded(error, reason, attributes) {
1295
+ if (!S.capture) return;
1296
+ if (error && typeof error === "object") S.decided.add(error);
1297
+ const dropped = limit("deliberate", error);
1298
+ if (dropped < 0) return;
1299
+ markCaptured(error);
1300
+ S.capture(error, { ...attributes, ...degradedAttributes(reason, dropped) }, "warning");
1301
+ }
1302
+ function onConsoleError(args) {
1303
+ if (!_optionalChain([S, 'access', _22 => _22.sources, 'optionalAccess', _23 => _23.console])) return;
1304
+ if (typeof args[0] === "string" && args[0].startsWith("[autter")) return;
1305
+ for (const arg of args) {
1306
+ if (!isError(arg)) continue;
1307
+ let message = "";
1308
+ try {
1309
+ message = _util.format.call(void 0, ...args.filter((other) => other !== arg));
1310
+ } catch (e23) {
1311
+ }
1312
+ reportLoggedError(arg, "console", message);
1313
+ }
1314
+ }
1315
+ function patchConsole() {
1316
+ const target = console;
1317
+ try {
1318
+ if (target[PATCHED]) return;
1319
+ const original = target.error;
1320
+ if (typeof original !== "function") return;
1321
+ target.error = function(...args) {
1322
+ try {
1323
+ onConsoleError(args);
1324
+ } catch (e24) {
1325
+ }
1326
+ return original.apply(this, args);
1327
+ };
1328
+ Object.defineProperty(target, PATCHED, { value: true });
1329
+ } catch (e25) {
1330
+ }
1331
+ }
1332
+ function errorField(value) {
1333
+ if (!value || typeof value !== "object") return void 0;
1334
+ const record = value;
1335
+ for (const key of ["err", "error"]) if (isError(record[key])) return record[key];
1336
+ let seen = 0;
1337
+ for (const key of Object.keys(record)) {
1338
+ if (++seen > 20) break;
1339
+ if (isError(record[key])) return record[key];
1340
+ }
1341
+ return void 0;
1342
+ }
1343
+ function wrapMethod(target, key, inspect) {
1344
+ const original = target[key];
1345
+ if (typeof original !== "function") return;
1346
+ target[key] = function(...args) {
1347
+ try {
1348
+ inspect(this, args);
1349
+ } catch (e26) {
1350
+ }
1351
+ return original.apply(this, args);
1352
+ };
1353
+ }
1354
+ function markPatched(target) {
1355
+ const record = target;
1356
+ if (record[PATCHED]) return false;
1357
+ try {
1358
+ Object.defineProperty(target, PATCHED, { value: true });
1359
+ return true;
1360
+ } catch (e27) {
1361
+ return false;
1362
+ }
1363
+ }
1364
+ function patchPino(protoFactory) {
1365
+ if (typeof protoFactory !== "function") return;
1366
+ const proto = Object.getPrototypeOf(protoFactory());
1367
+ if (!proto) return;
1368
+ const write = Object.getOwnPropertySymbols(proto).find((symbol) => symbol.description === "pino.write");
1369
+ if (!write || typeof proto[write] !== "function" || !markPatched(proto)) return;
1370
+ wrapMethod(proto, write, (_self, [obj, msg, level]) => {
1371
+ if (!_optionalChain([S, 'access', _24 => _24.sources, 'optionalAccess', _25 => _25.pino]) || typeof level !== "number" || level < 50) return;
1372
+ const error = isError(obj) ? obj : errorField(obj);
1373
+ if (error) reportLoggedError(error, "pino", typeof msg === "string" ? msg : void 0);
1374
+ });
1375
+ }
1376
+ var WINSTON_ERROR_LEVELS = /^(?:error|fatal|crit|alert|emerg)$/;
1377
+ function winstonErrorLevel(logger, level) {
1378
+ if (typeof level !== "string") return false;
1379
+ const levels = _optionalChain([logger, 'optionalAccess', _26 => _26.levels]);
1380
+ if (levels && typeof levels[level] === "number" && typeof levels.error === "number")
1381
+ return levels[level] <= levels.error;
1382
+ return WINSTON_ERROR_LEVELS.test(level);
1383
+ }
1384
+ function patchWinston(Logger) {
1385
+ const proto = _optionalChain([Logger, 'optionalAccess', _27 => _27.prototype]);
1386
+ if (!proto || typeof proto.log !== "function" || !markPatched(proto)) return;
1387
+ wrapMethod(proto, "log", (self, [level, msg, ...meta]) => {
1388
+ if (!_optionalChain([S, 'access', _28 => _28.sources, 'optionalAccess', _29 => _29.winston]) || !winstonErrorLevel(self, level)) return;
1389
+ for (const arg of [msg, ...meta]) {
1390
+ const error = isError(arg) ? arg : errorField(arg);
1391
+ if (error) reportLoggedError(error, "winston", typeof msg === "string" ? msg : void 0);
1392
+ }
1393
+ });
1394
+ wrapMethod(proto, "_addDefaultMeta", (self, [info]) => {
1395
+ if (!_optionalChain([S, 'access', _30 => _30.sources, 'optionalAccess', _31 => _31.winston]) || !info || typeof info !== "object") return;
1396
+ if (!winstonErrorLevel(self, info.level)) return;
1397
+ if (isError(info)) reportLoggedError(info, "winston");
1398
+ else {
1399
+ const error = errorField(info);
1400
+ const message = info.message;
1401
+ if (error) reportLoggedError(error, "winston", typeof message === "string" ? message : void 0);
1402
+ }
1403
+ });
1404
+ }
1405
+ function patchBunyan(Logger) {
1406
+ const proto = _optionalChain([Logger, 'optionalAccess', _32 => _32.prototype]);
1407
+ if (!proto || typeof proto.error !== "function" || !markPatched(proto)) return;
1408
+ for (const [method, level] of [["error", 50], ["fatal", 60]]) {
1409
+ wrapMethod(proto, method, (self, args) => {
1410
+ if (!_optionalChain([S, 'access', _33 => _33.sources, 'optionalAccess', _34 => _34.bunyan]) || args.length === 0) return;
1411
+ const min = _optionalChain([self, 'optionalAccess', _35 => _35._level]);
1412
+ if (typeof min === "number" && min > level) return;
1413
+ const error = isError(args[0]) ? args[0] : errorField(args[0]);
1414
+ if (!error) return;
1415
+ let message = "";
1416
+ try {
1417
+ message = _util.format.call(void 0, ...args.slice(1));
1418
+ } catch (e28) {
1419
+ }
1420
+ reportLoggedError(error, "bunyan", message);
1421
+ });
1422
+ }
1423
+ }
1424
+ var TARGETS = [
1425
+ { file: "pino/lib/proto.js", patch: patchPino },
1426
+ { file: "winston/lib/winston/logger.js", patch: patchWinston },
1427
+ { file: "bunyan/lib/bunyan.js", patch: patchBunyan }
1428
+ ];
1429
+ function patchModule(file, exports) {
1430
+ const target = TARGETS.find((entry) => entry.file === file);
1431
+ if (!target) return;
1432
+ try {
1433
+ target.patch(exports);
1434
+ } catch (e29) {
1435
+ }
1436
+ }
1437
+ function scanModuleCache() {
1438
+ try {
1439
+ const cache = _module.createRequire.call(void 0, _path.join.call(void 0, process.cwd(), "autter-runtime-loggers.cjs")).cache;
1440
+ for (const [key, entry] of Object.entries(cache)) {
1441
+ const path = key.replace(/\\/g, "/");
1442
+ for (const target of TARGETS)
1443
+ if (path.endsWith(`/node_modules/${target.file}`)) patchModule(target.file, _optionalChain([entry, 'optionalAccess', _36 => _36.exports]));
1444
+ }
1445
+ } catch (e30) {
1446
+ }
1447
+ }
1448
+ function hookLaterLoads() {
1449
+ if (S.hooked) return;
1450
+ S.hooked = true;
1451
+ try {
1452
+ new (0, _requireinthemiddle.Hook)(["pino", "winston", "bunyan"], { internals: true }, (exports, name) => {
1453
+ const file = name.replace(/\\/g, "/");
1454
+ patchModule(file === "bunyan" ? "bunyan/lib/bunyan.js" : file, exports);
1455
+ return exports;
1456
+ });
1457
+ } catch (e31) {
1458
+ }
1459
+ for (const delay of [0, 1e3, 1e4]) {
1460
+ const timer = setTimeout(scanModuleCache, delay);
1461
+ _optionalChain([timer, 'access', _37 => _37.unref, 'optionalCall', _38 => _38()]);
1462
+ }
1463
+ }
1464
+ function startLoggedErrorCapture(option) {
1465
+ const sources = loggedErrorSources(option);
1466
+ S.sources = sources;
1467
+ if (!Object.values(sources).some(Boolean)) return;
1468
+ if (sources.console) patchConsole();
1469
+ if (sources.pino || sources.winston || sources.bunyan) {
1470
+ scanModuleCache();
1471
+ hookLaterLoads();
1472
+ }
1473
+ }
1474
+ function stopLoggedErrorCapture() {
1475
+ S.sources = null;
1476
+ sendTails(true);
1477
+ }
1478
+
988
1479
  // src/sinks.ts
989
1480
 
990
1481
 
@@ -993,8 +1484,8 @@ var _crypto = require('crypto');
993
1484
 
994
1485
 
995
1486
  var _fs = require('fs');
996
- var _path = require('path');
997
- var sinkStats = _chunkGYTQLITWcjs.sharedSlot.call(void 0, "sinks", () => ({ dropped: 0 }));
1487
+
1488
+ var sinkStats = _chunkBHYHORUDcjs.sharedSlot.call(void 0, "sinks", () => ({ dropped: 0 }));
998
1489
  function otlpSink(options = {}) {
999
1490
  let context = null;
1000
1491
  let queue = [];
@@ -1070,7 +1561,7 @@ function otlpSink(options = {}) {
1070
1561
  Math.max(1, Math.min(3e3, deadline - Date.now()))
1071
1562
  )
1072
1563
  });
1073
- _chunkGYTQLITWcjs.observeIngesterResponse.call(void 0, { status: response.status, headers: response.headers, route: "/v1/logs" });
1564
+ _chunkBHYHORUDcjs.observeIngesterResponse.call(void 0, { status: response.status, headers: response.headers, route: "/v1/logs" });
1074
1565
  if (!response.ok)
1075
1566
  throw new Error(`Runtime log export failed (${response.status})`);
1076
1567
  failure = void 0;
@@ -1120,7 +1611,7 @@ function otlpSink(options = {}) {
1120
1611
  }
1121
1612
  queue.push({ record, bytes });
1122
1613
  queueBytes += bytes;
1123
- _chunkGYTQLITWcjs.noteCompatFeature.call(void 0, "operation_logging");
1614
+ _chunkBHYHORUDcjs.noteCompatFeature.call(void 0, "operation_logging");
1124
1615
  scheduleFlush();
1125
1616
  },
1126
1617
  flush,
@@ -1247,14 +1738,14 @@ function formatPretty(event, color = false) {
1247
1738
  return lines.join("\n");
1248
1739
  }
1249
1740
  function consoleSink(options = {}) {
1250
- const format = _nullishCoalesce(options.format, () => ( (process.env.NODE_ENV === "production" ? "json" : "pretty")));
1251
- const color = _nullishCoalesce(options.color, () => ( (_optionalChain([process, 'access', _13 => _13.stdout, 'optionalAccess', _14 => _14.isTTY]) === true && !process.env.NO_COLOR)));
1741
+ const format2 = _nullishCoalesce(options.format, () => ( (process.env.NODE_ENV === "production" ? "json" : "pretty")));
1742
+ const color = _nullishCoalesce(options.color, () => ( (_optionalChain([process, 'access', _39 => _39.stdout, 'optionalAccess', _40 => _40.isTTY]) === true && !process.env.NO_COLOR)));
1252
1743
  const write = _nullishCoalesce(options.write, () => ( ((line) => console.log(line))));
1253
1744
  return {
1254
1745
  name: "console",
1255
1746
  write(event) {
1256
1747
  write(
1257
- format === "json" ? JSON.stringify({
1748
+ format2 === "json" ? JSON.stringify({
1258
1749
  ...event.attributes,
1259
1750
  level: event.level,
1260
1751
  message: event.message
@@ -1293,14 +1784,14 @@ function fileSink(options = {}) {
1293
1784
  index = sameDay.length ? sameDay[sameDay.length - 1].index : 0;
1294
1785
  try {
1295
1786
  currentBytes = _fs.statSync.call(void 0, _path.join.call(void 0, dir, fileName(day, index))).size;
1296
- } catch (e15) {
1787
+ } catch (e32) {
1297
1788
  currentBytes = 0;
1298
1789
  }
1299
1790
  prune();
1300
1791
  };
1301
1792
  const disable = (error) => {
1302
1793
  disabled = true;
1303
- const code = _nullishCoalesce(_optionalChain([error, 'optionalAccess', _15 => _15.code]), () => ( "error"));
1794
+ const code = _nullishCoalesce(_optionalChain([error, 'optionalAccess', _41 => _41.code]), () => ( "error"));
1304
1795
  console.warn(
1305
1796
  `[autter-runtime] local runtime files disabled (${code} writing ${dir}); set logging.file: false to silence`
1306
1797
  );
@@ -1363,7 +1854,7 @@ function memorySink() {
1363
1854
  }
1364
1855
 
1365
1856
  // src/logger.ts
1366
- var shared = _chunkGYTQLITWcjs.sharedSlot.call(void 0, "logger", () => ({
1857
+ var shared = _chunkBHYHORUDcjs.sharedSlot.call(void 0, "logger", () => ({
1367
1858
  local: new (0, _async_hooks.AsyncLocalStorage)(),
1368
1859
  config: null,
1369
1860
  sinks: [],
@@ -1373,7 +1864,7 @@ var local = shared.local;
1373
1864
  var extraSinks = shared.extraSinks;
1374
1865
  var fallbackConsole = null;
1375
1866
  function redact(attributes) {
1376
- return _nullishCoalesce(_optionalChain([shared, 'access', _16 => _16.config, 'optionalAccess', _17 => _17.redact, 'call', _18 => _18(attributes)]), () => ( redactAttributes(attributes)));
1867
+ return _nullishCoalesce(_optionalChain([shared, 'access', _42 => _42.config, 'optionalAccess', _43 => _43.redact, 'call', _44 => _44(attributes)]), () => ( redactAttributes(attributes)));
1377
1868
  }
1378
1869
  var safe = (attributes = {}) => boundContext(attributes, redact);
1379
1870
  var merge = (current, next) => mergeContext(current, next, redact);
@@ -1412,12 +1903,12 @@ function traceAttributes(state) {
1412
1903
  }
1413
1904
  function emit(level, message, attributes, extra = {}, options = {}) {
1414
1905
  const state = options.state !== void 0 ? _nullishCoalesce(options.state, () => ( void 0)) : local.getStore();
1415
- if (_optionalChain([state, 'optionalAccess', _19 => _19.sealed])) return;
1906
+ if (_optionalChain([state, 'optionalAccess', _45 => _45.sealed])) return;
1416
1907
  const summary = extra["autter.event.type"] === "operation";
1417
1908
  if (!summary) recordLogBreadcrumb(level, message, attributes, state);
1418
- if (!summary && LEVEL_SEVERITY[level] < LEVEL_SEVERITY[_nullishCoalesce(_optionalChain([shared, 'access', _20 => _20.config, 'optionalAccess', _21 => _21.options, 'optionalAccess', _22 => _22.minLevel]), () => ( "debug"))])
1909
+ if (!summary && LEVEL_SEVERITY[level] < LEVEL_SEVERITY[_nullishCoalesce(_optionalChain([shared, 'access', _46 => _46.config, 'optionalAccess', _47 => _47.options, 'optionalAccess', _48 => _48.minLevel]), () => ( "debug"))])
1419
1910
  return;
1420
- if (!summary && state && _optionalChain([shared, 'access', _23 => _23.config, 'optionalAccess', _24 => _24.options, 'optionalAccess', _25 => _25.inline]) !== false) {
1911
+ if (!summary && state && _optionalChain([shared, 'access', _49 => _49.config, 'optionalAccess', _50 => _50.options, 'optionalAccess', _51 => _51.inline]) !== false) {
1421
1912
  const { "exception.stacktrace": _stack, ...inlineAttrs } = userContext(
1422
1913
  attributes,
1423
1914
  redact
@@ -1425,20 +1916,20 @@ function emit(level, message, attributes, extra = {}, options = {}) {
1425
1916
  appendInlineLog(state.inline, level, message, inlineAttrs, redact);
1426
1917
  if (level === "debug" || level === "info") return;
1427
1918
  }
1428
- const span = _nullishCoalesce(options.span, () => ( _optionalChain([_api.trace, 'access', _26 => _26.getActiveSpan, 'call', _27 => _27(), 'optionalAccess', _28 => _28.spanContext, 'call', _29 => _29()])));
1429
- const user = merge(_nullishCoalesce(_optionalChain([state, 'optionalAccess', _30 => _30.attributes]), () => ( {})), attributes);
1919
+ const span = _nullishCoalesce(options.span, () => ( _optionalChain([_api.trace, 'access', _52 => _52.getActiveSpan, 'call', _53 => _53(), 'optionalAccess', _54 => _54.spanContext, 'call', _55 => _55()])));
1920
+ const user = merge(_nullishCoalesce(_optionalChain([state, 'optionalAccess', _56 => _56.attributes]), () => ( {})), attributes);
1430
1921
  const exceptions = Object.fromEntries(
1431
1922
  Object.entries(user).filter(([key]) => key.startsWith("exception."))
1432
1923
  );
1433
- const raw = {
1924
+ const raw = stackAttributesLast({
1434
1925
  "autter.event.id": _crypto.randomUUID.call(void 0, ),
1435
1926
  ...extra,
1436
1927
  ...exceptions,
1437
1928
  ...operationAttributes(state),
1438
1929
  ...user
1439
- };
1440
- const enrichers = _optionalChain([shared, 'access', _31 => _31.config, 'optionalAccess', _32 => _32.options, 'optionalAccess', _33 => _33.enrich]);
1441
- if (summary && state && _optionalChain([enrichers, 'optionalAccess', _34 => _34.length])) {
1930
+ });
1931
+ const enrichers = _optionalChain([shared, 'access', _57 => _57.config, 'optionalAccess', _58 => _58.options, 'optionalAccess', _59 => _59.enrich]);
1932
+ if (summary && state && _optionalChain([enrichers, 'optionalAccess', _60 => _60.length])) {
1442
1933
  const event2 = { level, message, attributes: raw };
1443
1934
  for (const enrich of enrichers) {
1444
1935
  try {
@@ -1447,7 +1938,7 @@ function emit(level, message, attributes, extra = {}, options = {}) {
1447
1938
  res: state.res,
1448
1939
  operation: { id: state.id, name: state.name, kind: state.kind }
1449
1940
  });
1450
- } catch (e16) {
1941
+ } catch (e33) {
1451
1942
  }
1452
1943
  }
1453
1944
  }
@@ -1460,7 +1951,7 @@ function emit(level, message, attributes, extra = {}, options = {}) {
1460
1951
  for (const sink of activeSinks()) {
1461
1952
  try {
1462
1953
  sink.write(event);
1463
- } catch (e17) {
1954
+ } catch (e34) {
1464
1955
  }
1465
1956
  }
1466
1957
  }
@@ -1469,7 +1960,7 @@ function configureRuntimeLogger(next) {
1469
1960
  shared.sinks = defaultSinks(next);
1470
1961
  for (const sink of shared.sinks) {
1471
1962
  try {
1472
- _optionalChain([sink, 'access', _35 => _35.start, 'optionalCall', _36 => _36({
1963
+ _optionalChain([sink, 'access', _61 => _61.start, 'optionalCall', _62 => _62({
1473
1964
  endpoint: next.endpoint,
1474
1965
  apiKey: next.apiKey,
1475
1966
  service: next.service,
@@ -1477,7 +1968,7 @@ function configureRuntimeLogger(next) {
1477
1968
  ...next.release ? { release: next.release } : {},
1478
1969
  ...next.distro ? { distro: next.distro } : {}
1479
1970
  })]);
1480
- } catch (e18) {
1971
+ } catch (e35) {
1481
1972
  }
1482
1973
  }
1483
1974
  }
@@ -1498,25 +1989,25 @@ function notifyException(error, attributes = {}) {
1498
1989
  type: isError(error) ? error.name : "Error",
1499
1990
  attributes: { ...attributes, ...errorAttributes(error) },
1500
1991
  ...state ? { operationId: state.id } : {},
1501
- ..._optionalChain([state, 'optionalAccess', _37 => _37.requestId]) ? { requestId: state.requestId } : {}
1992
+ ..._optionalChain([state, 'optionalAccess', _63 => _63.requestId]) ? { requestId: state.requestId } : {}
1502
1993
  };
1503
1994
  for (const sink of [...shared.sinks, ...extraSinks]) {
1504
1995
  try {
1505
- _optionalChain([sink, 'access', _38 => _38.exception, 'optionalCall', _39 => _39(record)]);
1506
- } catch (e19) {
1996
+ _optionalChain([sink, 'access', _64 => _64.exception, 'optionalCall', _65 => _65(record)]);
1997
+ } catch (e36) {
1507
1998
  }
1508
1999
  }
1509
2000
  }
1510
2001
  function runtimeLogStats() {
1511
2002
  return {
1512
- buffered: shared.sinks.reduce((sum, sink) => sum + (_nullishCoalesce(_optionalChain([sink, 'access', _40 => _40.buffered, 'optionalCall', _41 => _41()]), () => ( 0))), 0),
2003
+ buffered: shared.sinks.reduce((sum, sink) => sum + (_nullishCoalesce(_optionalChain([sink, 'access', _66 => _66.buffered, 'optionalCall', _67 => _67()]), () => ( 0))), 0),
1513
2004
  dropped: sinkStats.dropped
1514
2005
  };
1515
2006
  }
1516
2007
  async function flushRuntimeLogs() {
1517
2008
  if (!shared.config) return;
1518
2009
  const results = await Promise.allSettled(
1519
- shared.sinks.map((sink) => Promise.resolve().then(() => _optionalChain([sink, 'access', _42 => _42.flush, 'optionalCall', _43 => _43()])))
2010
+ shared.sinks.map((sink) => Promise.resolve().then(() => _optionalChain([sink, 'access', _68 => _68.flush, 'optionalCall', _69 => _69()])))
1520
2011
  );
1521
2012
  const failed = results.find((result) => result.status === "rejected");
1522
2013
  if (failed) throw failed.reason;
@@ -1524,7 +2015,7 @@ async function flushRuntimeLogs() {
1524
2015
  async function shutdownRuntimeLogger() {
1525
2016
  const active = shared.sinks;
1526
2017
  const results = await Promise.allSettled(
1527
- active.map((sink) => Promise.resolve().then(() => _optionalChain([sink, 'access', _44 => _44.shutdown, 'optionalCall', _45 => _45()])))
2018
+ active.map((sink) => Promise.resolve().then(() => _optionalChain([sink, 'access', _70 => _70.shutdown, 'optionalCall', _71 => _71()])))
1528
2019
  );
1529
2020
  shared.config = null;
1530
2021
  shared.sinks = [];
@@ -1546,29 +2037,32 @@ function createRuntimeLogger(attributes = {}) {
1546
2037
  debug: (message, extra) => emit("debug", message, merge(attrs, extra)),
1547
2038
  info: (message, extra) => emit("info", message, merge(attrs, extra)),
1548
2039
  warn: (message, extra) => emit("warning", message, merge(attrs, extra)),
1549
- error: (error, extra) => emit(
1550
- "error",
1551
- isError(error) ? error.message : String(error),
1552
- {
1553
- ...attrs,
1554
- ...extra,
1555
- ...isError(error) ? {
1556
- "exception.type": error.name,
1557
- "exception.stacktrace": _nullishCoalesce(error.stack, () => ( ""))
1558
- } : {}
1559
- },
1560
- errorAttributes(error)
1561
- )
2040
+ error: (error, extra) => {
2041
+ emit(
2042
+ "error",
2043
+ isError(error) ? error.message : String(error),
2044
+ {
2045
+ ...attrs,
2046
+ ...extra,
2047
+ ...isError(error) ? {
2048
+ "exception.type": error.name,
2049
+ "exception.stacktrace": _nullishCoalesce(error.stack, () => ( ""))
2050
+ } : {}
2051
+ },
2052
+ errorAttributes(error)
2053
+ );
2054
+ if (isError(error)) reportLoggedError(error, "runtimeLogger", void 0, toSpanAttributes(merge(attrs, extra)));
2055
+ }
1562
2056
  };
1563
2057
  }
1564
2058
  var runtimeLogger = createRuntimeLogger();
1565
- function captureExceptionAsLog(error, attributes = {}) {
2059
+ function captureExceptionAsLog(error, attributes = {}, level = "error") {
1566
2060
  const isErr = isError(error);
1567
2061
  const message = isErr ? error.message : String(error);
1568
- const stack = isErr && error.stack ? error.stack : _nullishCoalesce(_optionalChain([new Error(), 'access', _46 => _46.stack, 'optionalAccess', _47 => _47.split, 'call', _48 => _48("\n"), 'access', _49 => _49.filter, 'call', _50 => _50((line, i) => i === 0 || !/captureException/.test(line)), 'access', _51 => _51.join, 'call', _52 => _52("\n")]), () => ( ""));
1569
- noteOperationError(error);
2062
+ const stack = isErr && error.stack ? error.stack : _nullishCoalesce(_optionalChain([new Error(), 'access', _72 => _72.stack, 'optionalAccess', _73 => _73.split, 'call', _74 => _74("\n"), 'access', _75 => _75.filter, 'call', _76 => _76((line, i) => i === 0 || !/captureException/.test(line)), 'access', _77 => _77.join, 'call', _78 => _78("\n")]), () => ( ""));
2063
+ if (level === "error") noteOperationError(error);
1570
2064
  emit(
1571
- "error",
2065
+ level,
1572
2066
  message,
1573
2067
  {
1574
2068
  ...attributes,
@@ -1619,7 +2113,7 @@ function operationHandle(state) {
1619
2113
  setContext: (attrs) => {
1620
2114
  if (!state.sealed) {
1621
2115
  state.attributes = merge(state.attributes, attrs);
1622
- _optionalChain([_api.trace, 'access', _53 => _53.getActiveSpan, 'call', _54 => _54(), 'optionalAccess', _55 => _55.setAttributes, 'call', _56 => _56(traceAttributes(state))]);
2116
+ _optionalChain([_api.trace, 'access', _79 => _79.getActiveSpan, 'call', _80 => _80(), 'optionalAccess', _81 => _81.setAttributes, 'call', _82 => _82(traceAttributes(state))]);
1623
2117
  }
1624
2118
  },
1625
2119
  outcome: (status, message) => setOutcome(state, status, message),
@@ -1653,13 +2147,15 @@ function summaryExtra(state, level, http = {}) {
1653
2147
  "autter.operation.level": maxLevel(state.inline.level, level),
1654
2148
  ...state.ai ? { "autter.operation.ai": state.ai } : {},
1655
2149
  ...http,
1656
- ...err !== void 0 ? errorAttributes(err) : {},
2150
+ // A summary is no occurrence: no cause stacks or debug ids.
2151
+ ...err !== void 0 ? errorAttributes(err, { stacks: false }) : {},
1657
2152
  ...state.inline.logsTruncated ? { "autter.operation.logs_truncated": true } : {},
1658
2153
  ...state.inline.logs.length ? { "autter.operation.logs": state.inline.logs } : {}
1659
2154
  };
1660
2155
  }
1661
2156
  function emitSummary(state, options = {}) {
1662
2157
  if (state.sealed) return;
2158
+ settleDegraded(state);
1663
2159
  const err = state.error;
1664
2160
  const level = state.outcome === "failed" ? "error" : "info";
1665
2161
  emit(
@@ -1677,9 +2173,13 @@ function emitSummary(state, options = {}) {
1677
2173
  );
1678
2174
  state.sealed = true;
1679
2175
  }
2176
+ function settleDegraded(state) {
2177
+ if (state.degraded && state.outcome === "succeeded" && !state.explicitOutcome)
2178
+ state.outcome = "degraded";
2179
+ }
1680
2180
  function reportExplicitFailure(state) {
1681
2181
  if (state.outcome === "failed" && state.explicitOutcome && !state.errorThrown)
1682
- _optionalChain([shared, 'access', _57 => _57.config, 'optionalAccess', _58 => _58.reportOutcome, 'call', _59 => _59(state.name, _nullishCoalesce(state.message, () => ( "Operation failed")), {
2182
+ _optionalChain([shared, 'access', _83 => _83.config, 'optionalAccess', _84 => _84.reportOutcome, 'call', _85 => _85(state.name, _nullishCoalesce(state.message, () => ( "Operation failed")), {
1683
2183
  ...traceAttributes(state),
1684
2184
  "autter.outcome.stack": _nullishCoalesce(state.reportingStack, () => ( ""))
1685
2185
  })]);
@@ -1687,7 +2187,7 @@ function reportExplicitFailure(state) {
1687
2187
  function startOperation(name, fn, attributes, options, internal = {}) {
1688
2188
  const parent = _nullishCoalesce(internal.forkParent, () => ( local.getStore()));
1689
2189
  const carrier = options.from ? parseCarrier(options.from) : null;
1690
- const traceparent = _optionalChain([carrier, 'optionalAccess', _60 => _60.traceparent]) ? parseTraceparent(carrier.traceparent) : null;
2190
+ const traceparent = _optionalChain([carrier, 'optionalAccess', _86 => _86.traceparent]) ? parseTraceparent(carrier.traceparent) : null;
1691
2191
  const linked = internal.forkParent !== void 0 || parent && !parent.sealed;
1692
2192
  const state = newState(
1693
2193
  name,
@@ -1699,7 +2199,7 @@ function startOperation(name, fn, attributes, options, internal = {}) {
1699
2199
  ...traceparent ? { parentTraceId: traceparent.traceId } : {}
1700
2200
  } : {
1701
2201
  ...linked && parent ? { parentId: parent.id, base: parent.attributes } : {},
1702
- ..._optionalChain([parent, 'optionalAccess', _61 => _61.requestId]) ? { requestId: parent.requestId } : {}
2202
+ ..._optionalChain([parent, 'optionalAccess', _87 => _87.requestId]) ? { requestId: parent.requestId } : {}
1703
2203
  }
1704
2204
  );
1705
2205
  if (linked && parent) state.breadcrumbs = parent.breadcrumbs ??= new BreadcrumbTrail();
@@ -1713,16 +2213,17 @@ function startOperation(name, fn, attributes, options, internal = {}) {
1713
2213
  thrown = error;
1714
2214
  noteOperationError(error, true, state);
1715
2215
  rememberThrownBreadcrumbs(error, state);
1716
- _optionalChain([shared, 'access', _62 => _62.config, 'optionalAccess', _63 => _63.captureThrown, 'optionalCall', _64 => _64(error)]);
2216
+ _optionalChain([shared, 'access', _88 => _88.config, 'optionalAccess', _89 => _89.captureThrown, 'optionalCall', _90 => _90(error)]);
1717
2217
  throw error;
1718
2218
  } finally {
1719
- _optionalChain([_api.trace, 'access', _65 => _65.getActiveSpan, 'call', _66 => _66(), 'optionalAccess', _67 => _67.setAttributes, 'call', _68 => _68({
2219
+ settleDegraded(state);
2220
+ _optionalChain([_api.trace, 'access', _91 => _91.getActiveSpan, 'call', _92 => _92(), 'optionalAccess', _93 => _93.setAttributes, 'call', _94 => _94({
1720
2221
  ...traceAttributes(state),
1721
2222
  "autter.operation.outcome": state.outcome,
1722
2223
  "autter.operation.kind": state.kind
1723
2224
  })]);
1724
2225
  if (state.outcome === "failed" && !thrown)
1725
- _optionalChain([shared, 'access', _69 => _69.config, 'optionalAccess', _70 => _70.reportOutcome, 'call', _71 => _71(
2226
+ _optionalChain([shared, 'access', _95 => _95.config, 'optionalAccess', _96 => _96.reportOutcome, 'call', _97 => _97(
1726
2227
  state.name,
1727
2228
  _nullishCoalesce(state.message, () => ( "Operation failed")),
1728
2229
  {
@@ -1743,14 +2244,14 @@ function startOperation(name, fn, attributes, options, internal = {}) {
1743
2244
  }
1744
2245
  }
1745
2246
  ] : [];
1746
- const promise = _optionalChain([shared, 'access', _72 => _72.config, 'optionalAccess', _73 => _73.run]) ? shared.config.run(state.name, run, traceAttributes(state), links) : run();
2247
+ const promise = _optionalChain([shared, 'access', _98 => _98.config, 'optionalAccess', _99 => _99.run]) ? shared.config.run(state.name, run, traceAttributes(state), links) : run();
1747
2248
  if (!options.waitUntil) return promise;
1748
2249
  const waitUntil = options.waitUntil;
1749
2250
  return promise.finally(() => {
1750
2251
  try {
1751
2252
  waitUntil(flushRuntimeLogs().catch(() => {
1752
2253
  }));
1753
- } catch (e20) {
2254
+ } catch (e37) {
1754
2255
  }
1755
2256
  });
1756
2257
  }
@@ -1766,7 +2267,7 @@ var runtimeContext = {
1766
2267
  const state = currentOperation();
1767
2268
  if (!state) return;
1768
2269
  state.attributes = merge(state.attributes, attributes);
1769
- _optionalChain([_api.trace, 'access', _74 => _74.getActiveSpan, 'call', _75 => _75(), 'optionalAccess', _76 => _76.setAttributes, 'call', _77 => _77(traceAttributes(state))]);
2270
+ _optionalChain([_api.trace, 'access', _100 => _100.getActiveSpan, 'call', _101 => _101(), 'optionalAccess', _102 => _102.setAttributes, 'call', _103 => _103(traceAttributes(state))]);
1770
2271
  },
1771
2272
  /** Set the outcome explicitly (wins over status/thrown-error rules). */
1772
2273
  outcome(status, message) {
@@ -1787,13 +2288,37 @@ var runtimeContext = {
1787
2288
  noteOperationError(error);
1788
2289
  runtimeLogger.error(error, attributes);
1789
2290
  },
2291
+ /**
2292
+ * The app caught `error` and chose to continue on a fallback (RF-02):
2293
+ *
2294
+ * } catch (err) {
2295
+ * runtimeContext.degraded(err, "pricing service down, using cached prices");
2296
+ * }
2297
+ *
2298
+ * Recorded as an occurrence at `warning` severity, marked
2299
+ * `autter.handling = "deliberate"` with the reason (grouped by its code
2300
+ * when the error has one), never an incident. The current request or
2301
+ * operation ends "degraded" unless it failed or set its outcome.
2302
+ */
2303
+ degraded(error, reason, attributes) {
2304
+ try {
2305
+ const state = currentOperation();
2306
+ if (state) {
2307
+ state.degraded = true;
2308
+ noteOperationError(error, false, state);
2309
+ appendInlineLog(state.inline, "warning", `degraded: ${String(reason)}`, void 0, redact);
2310
+ }
2311
+ reportDegraded(error, reason, toSpanAttributes(userContext(attributes, redact)));
2312
+ } catch (e38) {
2313
+ }
2314
+ },
1790
2315
  /** Current operation id. */
1791
2316
  get id() {
1792
- return _optionalChain([local, 'access', _78 => _78.getStore, 'call', _79 => _79(), 'optionalAccess', _80 => _80.id]);
2317
+ return _optionalChain([local, 'access', _104 => _104.getStore, 'call', _105 => _105(), 'optionalAccess', _106 => _106.id]);
1793
2318
  },
1794
2319
  /** Current request id (inherited by child operations and forks). */
1795
2320
  get requestId() {
1796
- return _optionalChain([local, 'access', _81 => _81.getStore, 'call', _82 => _82(), 'optionalAccess', _83 => _83.requestId]);
2321
+ return _optionalChain([local, 'access', _107 => _107.getStore, 'call', _108 => _108(), 'optionalAccess', _109 => _109.requestId]);
1797
2322
  },
1798
2323
  /**
1799
2324
  * Run `fn` as a child operation whose parent link is captured NOW, so it
@@ -1807,7 +2332,7 @@ var runtimeContext = {
1807
2332
  carrier() {
1808
2333
  const state = local.getStore();
1809
2334
  if (!state) return void 0;
1810
- const span = _optionalChain([_api.trace, 'access', _84 => _84.getActiveSpan, 'call', _85 => _85(), 'optionalAccess', _86 => _86.spanContext, 'call', _87 => _87()]);
2335
+ const span = _optionalChain([_api.trace, 'access', _110 => _110.getActiveSpan, 'call', _111 => _111(), 'optionalAccess', _112 => _112.spanContext, 'call', _113 => _113()]);
1811
2336
  const traceparent = span ? formatTraceparent(span.traceId, span.spanId, (span.traceFlags & 1) === 1) : void 0;
1812
2337
  return createCarrier({
1813
2338
  op: state.id,
@@ -1816,11 +2341,20 @@ var runtimeContext = {
1816
2341
  });
1817
2342
  }
1818
2343
  };
2344
+ setHandledTail(
2345
+ (type, dropped) => emit(
2346
+ "warning",
2347
+ `${dropped} caught ${type} error(s) left out by the burst limit`,
2348
+ { "autter.caught.dropped": dropped, "autter.caught.type": type },
2349
+ {},
2350
+ { state: null }
2351
+ )
2352
+ );
1819
2353
 
1820
2354
  // src/breadcrumbs.ts
1821
2355
  var INVALID_TRACE_ID = "00000000000000000000000000000000";
1822
2356
  var MAX_TRACE_TRAILS = 200;
1823
- var trails = _chunkGYTQLITWcjs.sharedSlot.call(void 0, "breadcrumbs", () => ({
2357
+ var trails = _chunkBHYHORUDcjs.sharedSlot.call(void 0, "breadcrumbs", () => ({
1824
2358
  byTrace: /* @__PURE__ */ new Map(),
1825
2359
  process: new BreadcrumbTrail(),
1826
2360
  thrown: /* @__PURE__ */ new WeakMap()
@@ -1829,14 +2363,14 @@ var byTrace = trails.byTrace;
1829
2363
  var processTrail = trails.process;
1830
2364
  var thrownTrails = trails.thrown;
1831
2365
  function redact2(attributes) {
1832
- return _nullishCoalesce(_optionalChain([loggerConfigured, 'call', _88 => _88(), 'optionalAccess', _89 => _89.redact, 'call', _90 => _90(attributes)]), () => ( redactAttributes(attributes)));
2366
+ return _nullishCoalesce(_optionalChain([loggerConfigured, 'call', _114 => _114(), 'optionalAccess', _115 => _115.redact, 'call', _116 => _116(attributes)]), () => ( redactAttributes(attributes)));
1833
2367
  }
1834
2368
  function trailFor(create, state = local.getStore()) {
1835
2369
  if (state) {
1836
2370
  if (!state.breadcrumbs && create) state.breadcrumbs = new BreadcrumbTrail();
1837
2371
  return state.breadcrumbs;
1838
2372
  }
1839
- const traceId = _optionalChain([_api.trace, 'access', _91 => _91.getActiveSpan, 'call', _92 => _92(), 'optionalAccess', _93 => _93.spanContext, 'call', _94 => _94(), 'access', _95 => _95.traceId]);
2373
+ const traceId = _optionalChain([_api.trace, 'access', _117 => _117.getActiveSpan, 'call', _118 => _118(), 'optionalAccess', _119 => _119.spanContext, 'call', _120 => _120(), 'access', _121 => _121.traceId]);
1840
2374
  if (traceId && traceId !== INVALID_TRACE_ID) {
1841
2375
  let trail = byTrace.get(traceId);
1842
2376
  if (!trail && create) {
@@ -1855,9 +2389,9 @@ function addBreadcrumb(input) {
1855
2389
  try {
1856
2390
  const crumb = normalizeBreadcrumb(input, redact2);
1857
2391
  if (!crumb) return;
1858
- _optionalChain([trailFor, 'call', _96 => _96(true), 'optionalAccess', _97 => _97.add, 'call', _98 => _98(crumb)]);
1859
- _chunkGYTQLITWcjs.noteCompatFeature.call(void 0, "breadcrumbs");
1860
- } catch (e21) {
2392
+ _optionalChain([trailFor, 'call', _122 => _122(true), 'optionalAccess', _123 => _123.add, 'call', _124 => _124(crumb)]);
2393
+ _chunkBHYHORUDcjs.noteCompatFeature.call(void 0, "breadcrumbs");
2394
+ } catch (e39) {
1861
2395
  }
1862
2396
  }
1863
2397
  function recordLogBreadcrumb(level, message, attributes, state) {
@@ -1873,15 +2407,15 @@ function recordLogBreadcrumb(level, message, attributes, state) {
1873
2407
  }
1874
2408
  }
1875
2409
  const crumb = normalizeBreadcrumb({ type: "log", level, message, data }, redact2);
1876
- if (crumb) _optionalChain([trailFor, 'call', _99 => _99(true, state), 'optionalAccess', _100 => _100.add, 'call', _101 => _101(crumb)]);
1877
- } catch (e22) {
2410
+ if (crumb) _optionalChain([trailFor, 'call', _125 => _125(true, state), 'optionalAccess', _126 => _126.add, 'call', _127 => _127(crumb)]);
2411
+ } catch (e40) {
1878
2412
  }
1879
2413
  }
1880
2414
  function attributeBudget() {
1881
- const limit = Number(
2415
+ const limit2 = Number(
1882
2416
  _nullishCoalesce(process.env.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, () => ( process.env.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT))
1883
2417
  );
1884
- return Number.isFinite(limit) && limit > 0 ? Math.min(BREADCRUMBS_ATTRIBUTE_MAX_CHARS, limit) : BREADCRUMBS_ATTRIBUTE_MAX_CHARS;
2418
+ return Number.isFinite(limit2) && limit2 > 0 ? Math.min(BREADCRUMBS_ATTRIBUTE_MAX_CHARS, limit2) : BREADCRUMBS_ATTRIBUTE_MAX_CHARS;
1885
2419
  }
1886
2420
  function rememberThrownBreadcrumbs(error, state) {
1887
2421
  if (state.breadcrumbs && error !== null && (typeof error === "object" || typeof error === "function"))
@@ -1891,10 +2425,10 @@ function breadcrumbEventAttributes(scrub, error) {
1891
2425
  try {
1892
2426
  const thrown = error !== null && typeof error === "object" ? thrownTrails.get(error) : void 0;
1893
2427
  const trail = _nullishCoalesce(thrown, () => ( trailFor(false)));
1894
- if (!_optionalChain([trail, 'optionalAccess', _102 => _102.size])) return {};
2428
+ if (!_optionalChain([trail, 'optionalAccess', _128 => _128.size])) return {};
1895
2429
  const json = breadcrumbsAttribute(trail.list(), scrub, attributeBudget());
1896
2430
  return json ? { [BREADCRUMBS_ATTRIBUTE]: json } : {};
1897
- } catch (e23) {
2431
+ } catch (e41) {
1898
2432
  return {};
1899
2433
  }
1900
2434
  }
@@ -1949,4 +2483,10 @@ function breadcrumbEventAttributes(scrub, error) {
1949
2483
 
1950
2484
 
1951
2485
 
1952
- exports.redactAttributes = redactAttributes; exports.redactText = redactText; exports.makeRedactor = makeRedactor; exports.CODE_PATTERN = CODE_PATTERN; exports.RuntimeError = RuntimeError; exports.defineRuntimeErrors = defineRuntimeErrors; exports.isError = isError; exports.isRuntimeErrorLike = isRuntimeErrorLike; exports.errorCodeOf = errorCodeOf; exports.errorAttributes = errorAttributes; exports.errorInternal = errorInternal; exports.toClientError = toClientError; exports.responseStatusOf = responseStatusOf; exports.isSummary = isSummary; exports.DEFAULT_REQUEST_ID_HEADER = DEFAULT_REQUEST_ID_HEADER; exports.resolveRequestId = resolveRequestId; exports.normalizeRoutePath = normalizeRoutePath; exports.compileIgnore = compileIgnore; exports.requestOutcome = requestOutcome; exports.parseUserAgent = parseUserAgent; exports.sanitizeBreadcrumbs = sanitizeBreadcrumbs; exports.fingerprintValues = fingerprintValues; exports.fingerprintEventAttributes = fingerprintEventAttributes; exports.splitFingerprint = splitFingerprint; exports.addBreadcrumb = addBreadcrumb; exports.breadcrumbEventAttributes = breadcrumbEventAttributes; exports.otlpSink = otlpSink; exports.consoleSink = consoleSink; exports.fileSink = fileSink; exports.memorySink = memorySink; exports.local = local; exports.currentOperation = currentOperation; exports.configureRuntimeLogger = configureRuntimeLogger; exports.addRuntimeSink = addRuntimeSink; exports.notifyException = notifyException; exports.runtimeLogStats = runtimeLogStats; exports.flushRuntimeLogs = flushRuntimeLogs; exports.shutdownRuntimeLogger = shutdownRuntimeLogger; exports.noteOperationError = noteOperationError; exports.recordOperationAiUsage = recordOperationAiUsage; exports.createRuntimeLogger = createRuntimeLogger; exports.runtimeLogger = runtimeLogger; exports.captureExceptionAsLog = captureExceptionAsLog; exports.createRequestState = createRequestState; exports.emitSummary = emitSummary; exports.reportExplicitFailure = reportExplicitFailure; exports.withRuntimeOperation = withRuntimeOperation; exports.runInBackground = runInBackground; exports.runtimeContext = runtimeContext;
2486
+
2487
+
2488
+
2489
+
2490
+
2491
+
2492
+ exports.redactAttributes = redactAttributes; exports.redactText = redactText; exports.makeRedactor = makeRedactor; exports.CODE_PATTERN = CODE_PATTERN; exports.RuntimeError = RuntimeError; exports.defineRuntimeErrors = defineRuntimeErrors; exports.isError = isError; exports.isRuntimeErrorLike = isRuntimeErrorLike; exports.errorCodeOf = errorCodeOf; exports.errorAttributes = errorAttributes; exports.errorInternal = errorInternal; exports.toClientError = toClientError; exports.responseStatusOf = responseStatusOf; exports.isSummary = isSummary; exports.DEFAULT_REQUEST_ID_HEADER = DEFAULT_REQUEST_ID_HEADER; exports.resolveRequestId = resolveRequestId; exports.normalizeRoutePath = normalizeRoutePath; exports.compileIgnore = compileIgnore; exports.requestOutcome = requestOutcome; exports.parseUserAgent = parseUserAgent; exports.sanitizeBreadcrumbs = sanitizeBreadcrumbs; exports.fingerprintValues = fingerprintValues; exports.fingerprintEventAttributes = fingerprintEventAttributes; exports.splitFingerprint = splitFingerprint; exports.createErrorFilter = createErrorFilter; exports.addBreadcrumb = addBreadcrumb; exports.breadcrumbEventAttributes = breadcrumbEventAttributes; exports.markCaptured = markCaptured; exports.isCaptured = isCaptured; exports.setHandledCapture = setHandledCapture; exports.startLoggedErrorCapture = startLoggedErrorCapture; exports.stopLoggedErrorCapture = stopLoggedErrorCapture; exports.otlpSink = otlpSink; exports.consoleSink = consoleSink; exports.fileSink = fileSink; exports.memorySink = memorySink; exports.local = local; exports.currentOperation = currentOperation; exports.configureRuntimeLogger = configureRuntimeLogger; exports.addRuntimeSink = addRuntimeSink; exports.notifyException = notifyException; exports.runtimeLogStats = runtimeLogStats; exports.flushRuntimeLogs = flushRuntimeLogs; exports.shutdownRuntimeLogger = shutdownRuntimeLogger; exports.noteOperationError = noteOperationError; exports.recordOperationAiUsage = recordOperationAiUsage; exports.createRuntimeLogger = createRuntimeLogger; exports.runtimeLogger = runtimeLogger; exports.captureExceptionAsLog = captureExceptionAsLog; exports.createRequestState = createRequestState; exports.emitSummary = emitSummary; exports.reportExplicitFailure = reportExplicitFailure; exports.withRuntimeOperation = withRuntimeOperation; exports.runInBackground = runInBackground; exports.runtimeContext = runtimeContext;