@autter/runtime-node 1.8.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 _chunkMOZOUEMAcjs = require('./chunk-MOZOUEMA.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,132 @@ 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);
977
1170
  function testPattern(pattern, type, message) {
978
1171
  if (typeof pattern === "string") {
979
1172
  return pattern !== "" && (message.includes(pattern) || type.includes(pattern));
@@ -983,11 +1176,11 @@ function testPattern(pattern, type, message) {
983
1176
  return re.test(message) || type !== "" && (re.test(type) || re.test(`${type}: ${message}`));
984
1177
  }
985
1178
  function isIgnoredError(patterns, type, message) {
986
- if (!_optionalChain([patterns, 'optionalAccess', _13 => _13.length])) return false;
1179
+ if (!_optionalChain([patterns, 'optionalAccess', _14 => _14.length])) return false;
987
1180
  for (const pattern of patterns) {
988
1181
  try {
989
1182
  if (testPattern(pattern, type, message)) return true;
990
- } catch (e15) {
1183
+ } catch (e18) {
991
1184
  }
992
1185
  }
993
1186
  return false;
@@ -1006,7 +1199,7 @@ function createErrorFilter(options = {}, random = Math.random) {
1006
1199
  const severity = _nullishCoalesce(input.severity, () => ( "error"));
1007
1200
  if (severity !== "error") return true;
1008
1201
  return random() < rate;
1009
- } catch (e16) {
1202
+ } catch (e19) {
1010
1203
  return true;
1011
1204
  }
1012
1205
  };
@@ -1022,6 +1215,267 @@ var _crypto = require('crypto');
1022
1215
 
1023
1216
 
1024
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
+
1025
1479
  // src/sinks.ts
1026
1480
 
1027
1481
 
@@ -1030,8 +1484,8 @@ var _crypto = require('crypto');
1030
1484
 
1031
1485
 
1032
1486
  var _fs = require('fs');
1033
- var _path = require('path');
1034
- var sinkStats = _chunkMOZOUEMAcjs.sharedSlot.call(void 0, "sinks", () => ({ dropped: 0 }));
1487
+
1488
+ var sinkStats = _chunkBHYHORUDcjs.sharedSlot.call(void 0, "sinks", () => ({ dropped: 0 }));
1035
1489
  function otlpSink(options = {}) {
1036
1490
  let context = null;
1037
1491
  let queue = [];
@@ -1107,7 +1561,7 @@ function otlpSink(options = {}) {
1107
1561
  Math.max(1, Math.min(3e3, deadline - Date.now()))
1108
1562
  )
1109
1563
  });
1110
- _chunkMOZOUEMAcjs.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" });
1111
1565
  if (!response.ok)
1112
1566
  throw new Error(`Runtime log export failed (${response.status})`);
1113
1567
  failure = void 0;
@@ -1157,7 +1611,7 @@ function otlpSink(options = {}) {
1157
1611
  }
1158
1612
  queue.push({ record, bytes });
1159
1613
  queueBytes += bytes;
1160
- _chunkMOZOUEMAcjs.noteCompatFeature.call(void 0, "operation_logging");
1614
+ _chunkBHYHORUDcjs.noteCompatFeature.call(void 0, "operation_logging");
1161
1615
  scheduleFlush();
1162
1616
  },
1163
1617
  flush,
@@ -1284,14 +1738,14 @@ function formatPretty(event, color = false) {
1284
1738
  return lines.join("\n");
1285
1739
  }
1286
1740
  function consoleSink(options = {}) {
1287
- const format = _nullishCoalesce(options.format, () => ( (process.env.NODE_ENV === "production" ? "json" : "pretty")));
1288
- const color = _nullishCoalesce(options.color, () => ( (_optionalChain([process, 'access', _14 => _14.stdout, 'optionalAccess', _15 => _15.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)));
1289
1743
  const write = _nullishCoalesce(options.write, () => ( ((line) => console.log(line))));
1290
1744
  return {
1291
1745
  name: "console",
1292
1746
  write(event) {
1293
1747
  write(
1294
- format === "json" ? JSON.stringify({
1748
+ format2 === "json" ? JSON.stringify({
1295
1749
  ...event.attributes,
1296
1750
  level: event.level,
1297
1751
  message: event.message
@@ -1330,14 +1784,14 @@ function fileSink(options = {}) {
1330
1784
  index = sameDay.length ? sameDay[sameDay.length - 1].index : 0;
1331
1785
  try {
1332
1786
  currentBytes = _fs.statSync.call(void 0, _path.join.call(void 0, dir, fileName(day, index))).size;
1333
- } catch (e17) {
1787
+ } catch (e32) {
1334
1788
  currentBytes = 0;
1335
1789
  }
1336
1790
  prune();
1337
1791
  };
1338
1792
  const disable = (error) => {
1339
1793
  disabled = true;
1340
- const code = _nullishCoalesce(_optionalChain([error, 'optionalAccess', _16 => _16.code]), () => ( "error"));
1794
+ const code = _nullishCoalesce(_optionalChain([error, 'optionalAccess', _41 => _41.code]), () => ( "error"));
1341
1795
  console.warn(
1342
1796
  `[autter-runtime] local runtime files disabled (${code} writing ${dir}); set logging.file: false to silence`
1343
1797
  );
@@ -1400,7 +1854,7 @@ function memorySink() {
1400
1854
  }
1401
1855
 
1402
1856
  // src/logger.ts
1403
- var shared = _chunkMOZOUEMAcjs.sharedSlot.call(void 0, "logger", () => ({
1857
+ var shared = _chunkBHYHORUDcjs.sharedSlot.call(void 0, "logger", () => ({
1404
1858
  local: new (0, _async_hooks.AsyncLocalStorage)(),
1405
1859
  config: null,
1406
1860
  sinks: [],
@@ -1410,7 +1864,7 @@ var local = shared.local;
1410
1864
  var extraSinks = shared.extraSinks;
1411
1865
  var fallbackConsole = null;
1412
1866
  function redact(attributes) {
1413
- return _nullishCoalesce(_optionalChain([shared, 'access', _17 => _17.config, 'optionalAccess', _18 => _18.redact, 'call', _19 => _19(attributes)]), () => ( redactAttributes(attributes)));
1867
+ return _nullishCoalesce(_optionalChain([shared, 'access', _42 => _42.config, 'optionalAccess', _43 => _43.redact, 'call', _44 => _44(attributes)]), () => ( redactAttributes(attributes)));
1414
1868
  }
1415
1869
  var safe = (attributes = {}) => boundContext(attributes, redact);
1416
1870
  var merge = (current, next) => mergeContext(current, next, redact);
@@ -1449,12 +1903,12 @@ function traceAttributes(state) {
1449
1903
  }
1450
1904
  function emit(level, message, attributes, extra = {}, options = {}) {
1451
1905
  const state = options.state !== void 0 ? _nullishCoalesce(options.state, () => ( void 0)) : local.getStore();
1452
- if (_optionalChain([state, 'optionalAccess', _20 => _20.sealed])) return;
1906
+ if (_optionalChain([state, 'optionalAccess', _45 => _45.sealed])) return;
1453
1907
  const summary = extra["autter.event.type"] === "operation";
1454
1908
  if (!summary) recordLogBreadcrumb(level, message, attributes, state);
1455
- if (!summary && LEVEL_SEVERITY[level] < LEVEL_SEVERITY[_nullishCoalesce(_optionalChain([shared, 'access', _21 => _21.config, 'optionalAccess', _22 => _22.options, 'optionalAccess', _23 => _23.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"))])
1456
1910
  return;
1457
- if (!summary && state && _optionalChain([shared, 'access', _24 => _24.config, 'optionalAccess', _25 => _25.options, 'optionalAccess', _26 => _26.inline]) !== false) {
1911
+ if (!summary && state && _optionalChain([shared, 'access', _49 => _49.config, 'optionalAccess', _50 => _50.options, 'optionalAccess', _51 => _51.inline]) !== false) {
1458
1912
  const { "exception.stacktrace": _stack, ...inlineAttrs } = userContext(
1459
1913
  attributes,
1460
1914
  redact
@@ -1462,20 +1916,20 @@ function emit(level, message, attributes, extra = {}, options = {}) {
1462
1916
  appendInlineLog(state.inline, level, message, inlineAttrs, redact);
1463
1917
  if (level === "debug" || level === "info") return;
1464
1918
  }
1465
- const span = _nullishCoalesce(options.span, () => ( _optionalChain([_api.trace, 'access', _27 => _27.getActiveSpan, 'call', _28 => _28(), 'optionalAccess', _29 => _29.spanContext, 'call', _30 => _30()])));
1466
- const user = merge(_nullishCoalesce(_optionalChain([state, 'optionalAccess', _31 => _31.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);
1467
1921
  const exceptions = Object.fromEntries(
1468
1922
  Object.entries(user).filter(([key]) => key.startsWith("exception."))
1469
1923
  );
1470
- const raw = {
1924
+ const raw = stackAttributesLast({
1471
1925
  "autter.event.id": _crypto.randomUUID.call(void 0, ),
1472
1926
  ...extra,
1473
1927
  ...exceptions,
1474
1928
  ...operationAttributes(state),
1475
1929
  ...user
1476
- };
1477
- const enrichers = _optionalChain([shared, 'access', _32 => _32.config, 'optionalAccess', _33 => _33.options, 'optionalAccess', _34 => _34.enrich]);
1478
- if (summary && state && _optionalChain([enrichers, 'optionalAccess', _35 => _35.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])) {
1479
1933
  const event2 = { level, message, attributes: raw };
1480
1934
  for (const enrich of enrichers) {
1481
1935
  try {
@@ -1484,7 +1938,7 @@ function emit(level, message, attributes, extra = {}, options = {}) {
1484
1938
  res: state.res,
1485
1939
  operation: { id: state.id, name: state.name, kind: state.kind }
1486
1940
  });
1487
- } catch (e18) {
1941
+ } catch (e33) {
1488
1942
  }
1489
1943
  }
1490
1944
  }
@@ -1497,7 +1951,7 @@ function emit(level, message, attributes, extra = {}, options = {}) {
1497
1951
  for (const sink of activeSinks()) {
1498
1952
  try {
1499
1953
  sink.write(event);
1500
- } catch (e19) {
1954
+ } catch (e34) {
1501
1955
  }
1502
1956
  }
1503
1957
  }
@@ -1506,7 +1960,7 @@ function configureRuntimeLogger(next) {
1506
1960
  shared.sinks = defaultSinks(next);
1507
1961
  for (const sink of shared.sinks) {
1508
1962
  try {
1509
- _optionalChain([sink, 'access', _36 => _36.start, 'optionalCall', _37 => _37({
1963
+ _optionalChain([sink, 'access', _61 => _61.start, 'optionalCall', _62 => _62({
1510
1964
  endpoint: next.endpoint,
1511
1965
  apiKey: next.apiKey,
1512
1966
  service: next.service,
@@ -1514,7 +1968,7 @@ function configureRuntimeLogger(next) {
1514
1968
  ...next.release ? { release: next.release } : {},
1515
1969
  ...next.distro ? { distro: next.distro } : {}
1516
1970
  })]);
1517
- } catch (e20) {
1971
+ } catch (e35) {
1518
1972
  }
1519
1973
  }
1520
1974
  }
@@ -1535,25 +1989,25 @@ function notifyException(error, attributes = {}) {
1535
1989
  type: isError(error) ? error.name : "Error",
1536
1990
  attributes: { ...attributes, ...errorAttributes(error) },
1537
1991
  ...state ? { operationId: state.id } : {},
1538
- ..._optionalChain([state, 'optionalAccess', _38 => _38.requestId]) ? { requestId: state.requestId } : {}
1992
+ ..._optionalChain([state, 'optionalAccess', _63 => _63.requestId]) ? { requestId: state.requestId } : {}
1539
1993
  };
1540
1994
  for (const sink of [...shared.sinks, ...extraSinks]) {
1541
1995
  try {
1542
- _optionalChain([sink, 'access', _39 => _39.exception, 'optionalCall', _40 => _40(record)]);
1543
- } catch (e21) {
1996
+ _optionalChain([sink, 'access', _64 => _64.exception, 'optionalCall', _65 => _65(record)]);
1997
+ } catch (e36) {
1544
1998
  }
1545
1999
  }
1546
2000
  }
1547
2001
  function runtimeLogStats() {
1548
2002
  return {
1549
- buffered: shared.sinks.reduce((sum, sink) => sum + (_nullishCoalesce(_optionalChain([sink, 'access', _41 => _41.buffered, 'optionalCall', _42 => _42()]), () => ( 0))), 0),
2003
+ buffered: shared.sinks.reduce((sum, sink) => sum + (_nullishCoalesce(_optionalChain([sink, 'access', _66 => _66.buffered, 'optionalCall', _67 => _67()]), () => ( 0))), 0),
1550
2004
  dropped: sinkStats.dropped
1551
2005
  };
1552
2006
  }
1553
2007
  async function flushRuntimeLogs() {
1554
2008
  if (!shared.config) return;
1555
2009
  const results = await Promise.allSettled(
1556
- shared.sinks.map((sink) => Promise.resolve().then(() => _optionalChain([sink, 'access', _43 => _43.flush, 'optionalCall', _44 => _44()])))
2010
+ shared.sinks.map((sink) => Promise.resolve().then(() => _optionalChain([sink, 'access', _68 => _68.flush, 'optionalCall', _69 => _69()])))
1557
2011
  );
1558
2012
  const failed = results.find((result) => result.status === "rejected");
1559
2013
  if (failed) throw failed.reason;
@@ -1561,7 +2015,7 @@ async function flushRuntimeLogs() {
1561
2015
  async function shutdownRuntimeLogger() {
1562
2016
  const active = shared.sinks;
1563
2017
  const results = await Promise.allSettled(
1564
- active.map((sink) => Promise.resolve().then(() => _optionalChain([sink, 'access', _45 => _45.shutdown, 'optionalCall', _46 => _46()])))
2018
+ active.map((sink) => Promise.resolve().then(() => _optionalChain([sink, 'access', _70 => _70.shutdown, 'optionalCall', _71 => _71()])))
1565
2019
  );
1566
2020
  shared.config = null;
1567
2021
  shared.sinks = [];
@@ -1583,29 +2037,32 @@ function createRuntimeLogger(attributes = {}) {
1583
2037
  debug: (message, extra) => emit("debug", message, merge(attrs, extra)),
1584
2038
  info: (message, extra) => emit("info", message, merge(attrs, extra)),
1585
2039
  warn: (message, extra) => emit("warning", message, merge(attrs, extra)),
1586
- error: (error, extra) => emit(
1587
- "error",
1588
- isError(error) ? error.message : String(error),
1589
- {
1590
- ...attrs,
1591
- ...extra,
1592
- ...isError(error) ? {
1593
- "exception.type": error.name,
1594
- "exception.stacktrace": _nullishCoalesce(error.stack, () => ( ""))
1595
- } : {}
1596
- },
1597
- errorAttributes(error)
1598
- )
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
+ }
1599
2056
  };
1600
2057
  }
1601
2058
  var runtimeLogger = createRuntimeLogger();
1602
- function captureExceptionAsLog(error, attributes = {}) {
2059
+ function captureExceptionAsLog(error, attributes = {}, level = "error") {
1603
2060
  const isErr = isError(error);
1604
2061
  const message = isErr ? error.message : String(error);
1605
- const stack = isErr && error.stack ? error.stack : _nullishCoalesce(_optionalChain([new Error(), 'access', _47 => _47.stack, 'optionalAccess', _48 => _48.split, 'call', _49 => _49("\n"), 'access', _50 => _50.filter, 'call', _51 => _51((line, i) => i === 0 || !/captureException/.test(line)), 'access', _52 => _52.join, 'call', _53 => _53("\n")]), () => ( ""));
1606
- 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);
1607
2064
  emit(
1608
- "error",
2065
+ level,
1609
2066
  message,
1610
2067
  {
1611
2068
  ...attributes,
@@ -1656,7 +2113,7 @@ function operationHandle(state) {
1656
2113
  setContext: (attrs) => {
1657
2114
  if (!state.sealed) {
1658
2115
  state.attributes = merge(state.attributes, attrs);
1659
- _optionalChain([_api.trace, 'access', _54 => _54.getActiveSpan, 'call', _55 => _55(), 'optionalAccess', _56 => _56.setAttributes, 'call', _57 => _57(traceAttributes(state))]);
2116
+ _optionalChain([_api.trace, 'access', _79 => _79.getActiveSpan, 'call', _80 => _80(), 'optionalAccess', _81 => _81.setAttributes, 'call', _82 => _82(traceAttributes(state))]);
1660
2117
  }
1661
2118
  },
1662
2119
  outcome: (status, message) => setOutcome(state, status, message),
@@ -1690,13 +2147,15 @@ function summaryExtra(state, level, http = {}) {
1690
2147
  "autter.operation.level": maxLevel(state.inline.level, level),
1691
2148
  ...state.ai ? { "autter.operation.ai": state.ai } : {},
1692
2149
  ...http,
1693
- ...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 }) : {},
1694
2152
  ...state.inline.logsTruncated ? { "autter.operation.logs_truncated": true } : {},
1695
2153
  ...state.inline.logs.length ? { "autter.operation.logs": state.inline.logs } : {}
1696
2154
  };
1697
2155
  }
1698
2156
  function emitSummary(state, options = {}) {
1699
2157
  if (state.sealed) return;
2158
+ settleDegraded(state);
1700
2159
  const err = state.error;
1701
2160
  const level = state.outcome === "failed" ? "error" : "info";
1702
2161
  emit(
@@ -1714,9 +2173,13 @@ function emitSummary(state, options = {}) {
1714
2173
  );
1715
2174
  state.sealed = true;
1716
2175
  }
2176
+ function settleDegraded(state) {
2177
+ if (state.degraded && state.outcome === "succeeded" && !state.explicitOutcome)
2178
+ state.outcome = "degraded";
2179
+ }
1717
2180
  function reportExplicitFailure(state) {
1718
2181
  if (state.outcome === "failed" && state.explicitOutcome && !state.errorThrown)
1719
- _optionalChain([shared, 'access', _58 => _58.config, 'optionalAccess', _59 => _59.reportOutcome, 'call', _60 => _60(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")), {
1720
2183
  ...traceAttributes(state),
1721
2184
  "autter.outcome.stack": _nullishCoalesce(state.reportingStack, () => ( ""))
1722
2185
  })]);
@@ -1724,7 +2187,7 @@ function reportExplicitFailure(state) {
1724
2187
  function startOperation(name, fn, attributes, options, internal = {}) {
1725
2188
  const parent = _nullishCoalesce(internal.forkParent, () => ( local.getStore()));
1726
2189
  const carrier = options.from ? parseCarrier(options.from) : null;
1727
- const traceparent = _optionalChain([carrier, 'optionalAccess', _61 => _61.traceparent]) ? parseTraceparent(carrier.traceparent) : null;
2190
+ const traceparent = _optionalChain([carrier, 'optionalAccess', _86 => _86.traceparent]) ? parseTraceparent(carrier.traceparent) : null;
1728
2191
  const linked = internal.forkParent !== void 0 || parent && !parent.sealed;
1729
2192
  const state = newState(
1730
2193
  name,
@@ -1736,7 +2199,7 @@ function startOperation(name, fn, attributes, options, internal = {}) {
1736
2199
  ...traceparent ? { parentTraceId: traceparent.traceId } : {}
1737
2200
  } : {
1738
2201
  ...linked && parent ? { parentId: parent.id, base: parent.attributes } : {},
1739
- ..._optionalChain([parent, 'optionalAccess', _62 => _62.requestId]) ? { requestId: parent.requestId } : {}
2202
+ ..._optionalChain([parent, 'optionalAccess', _87 => _87.requestId]) ? { requestId: parent.requestId } : {}
1740
2203
  }
1741
2204
  );
1742
2205
  if (linked && parent) state.breadcrumbs = parent.breadcrumbs ??= new BreadcrumbTrail();
@@ -1750,16 +2213,17 @@ function startOperation(name, fn, attributes, options, internal = {}) {
1750
2213
  thrown = error;
1751
2214
  noteOperationError(error, true, state);
1752
2215
  rememberThrownBreadcrumbs(error, state);
1753
- _optionalChain([shared, 'access', _63 => _63.config, 'optionalAccess', _64 => _64.captureThrown, 'optionalCall', _65 => _65(error)]);
2216
+ _optionalChain([shared, 'access', _88 => _88.config, 'optionalAccess', _89 => _89.captureThrown, 'optionalCall', _90 => _90(error)]);
1754
2217
  throw error;
1755
2218
  } finally {
1756
- _optionalChain([_api.trace, 'access', _66 => _66.getActiveSpan, 'call', _67 => _67(), 'optionalAccess', _68 => _68.setAttributes, 'call', _69 => _69({
2219
+ settleDegraded(state);
2220
+ _optionalChain([_api.trace, 'access', _91 => _91.getActiveSpan, 'call', _92 => _92(), 'optionalAccess', _93 => _93.setAttributes, 'call', _94 => _94({
1757
2221
  ...traceAttributes(state),
1758
2222
  "autter.operation.outcome": state.outcome,
1759
2223
  "autter.operation.kind": state.kind
1760
2224
  })]);
1761
2225
  if (state.outcome === "failed" && !thrown)
1762
- _optionalChain([shared, 'access', _70 => _70.config, 'optionalAccess', _71 => _71.reportOutcome, 'call', _72 => _72(
2226
+ _optionalChain([shared, 'access', _95 => _95.config, 'optionalAccess', _96 => _96.reportOutcome, 'call', _97 => _97(
1763
2227
  state.name,
1764
2228
  _nullishCoalesce(state.message, () => ( "Operation failed")),
1765
2229
  {
@@ -1780,14 +2244,14 @@ function startOperation(name, fn, attributes, options, internal = {}) {
1780
2244
  }
1781
2245
  }
1782
2246
  ] : [];
1783
- const promise = _optionalChain([shared, 'access', _73 => _73.config, 'optionalAccess', _74 => _74.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();
1784
2248
  if (!options.waitUntil) return promise;
1785
2249
  const waitUntil = options.waitUntil;
1786
2250
  return promise.finally(() => {
1787
2251
  try {
1788
2252
  waitUntil(flushRuntimeLogs().catch(() => {
1789
2253
  }));
1790
- } catch (e22) {
2254
+ } catch (e37) {
1791
2255
  }
1792
2256
  });
1793
2257
  }
@@ -1803,7 +2267,7 @@ var runtimeContext = {
1803
2267
  const state = currentOperation();
1804
2268
  if (!state) return;
1805
2269
  state.attributes = merge(state.attributes, attributes);
1806
- _optionalChain([_api.trace, 'access', _75 => _75.getActiveSpan, 'call', _76 => _76(), 'optionalAccess', _77 => _77.setAttributes, 'call', _78 => _78(traceAttributes(state))]);
2270
+ _optionalChain([_api.trace, 'access', _100 => _100.getActiveSpan, 'call', _101 => _101(), 'optionalAccess', _102 => _102.setAttributes, 'call', _103 => _103(traceAttributes(state))]);
1807
2271
  },
1808
2272
  /** Set the outcome explicitly (wins over status/thrown-error rules). */
1809
2273
  outcome(status, message) {
@@ -1824,13 +2288,37 @@ var runtimeContext = {
1824
2288
  noteOperationError(error);
1825
2289
  runtimeLogger.error(error, attributes);
1826
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
+ },
1827
2315
  /** Current operation id. */
1828
2316
  get id() {
1829
- return _optionalChain([local, 'access', _79 => _79.getStore, 'call', _80 => _80(), 'optionalAccess', _81 => _81.id]);
2317
+ return _optionalChain([local, 'access', _104 => _104.getStore, 'call', _105 => _105(), 'optionalAccess', _106 => _106.id]);
1830
2318
  },
1831
2319
  /** Current request id (inherited by child operations and forks). */
1832
2320
  get requestId() {
1833
- return _optionalChain([local, 'access', _82 => _82.getStore, 'call', _83 => _83(), 'optionalAccess', _84 => _84.requestId]);
2321
+ return _optionalChain([local, 'access', _107 => _107.getStore, 'call', _108 => _108(), 'optionalAccess', _109 => _109.requestId]);
1834
2322
  },
1835
2323
  /**
1836
2324
  * Run `fn` as a child operation whose parent link is captured NOW, so it
@@ -1844,7 +2332,7 @@ var runtimeContext = {
1844
2332
  carrier() {
1845
2333
  const state = local.getStore();
1846
2334
  if (!state) return void 0;
1847
- const span = _optionalChain([_api.trace, 'access', _85 => _85.getActiveSpan, 'call', _86 => _86(), 'optionalAccess', _87 => _87.spanContext, 'call', _88 => _88()]);
2335
+ const span = _optionalChain([_api.trace, 'access', _110 => _110.getActiveSpan, 'call', _111 => _111(), 'optionalAccess', _112 => _112.spanContext, 'call', _113 => _113()]);
1848
2336
  const traceparent = span ? formatTraceparent(span.traceId, span.spanId, (span.traceFlags & 1) === 1) : void 0;
1849
2337
  return createCarrier({
1850
2338
  op: state.id,
@@ -1853,11 +2341,20 @@ var runtimeContext = {
1853
2341
  });
1854
2342
  }
1855
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
+ );
1856
2353
 
1857
2354
  // src/breadcrumbs.ts
1858
2355
  var INVALID_TRACE_ID = "00000000000000000000000000000000";
1859
2356
  var MAX_TRACE_TRAILS = 200;
1860
- var trails = _chunkMOZOUEMAcjs.sharedSlot.call(void 0, "breadcrumbs", () => ({
2357
+ var trails = _chunkBHYHORUDcjs.sharedSlot.call(void 0, "breadcrumbs", () => ({
1861
2358
  byTrace: /* @__PURE__ */ new Map(),
1862
2359
  process: new BreadcrumbTrail(),
1863
2360
  thrown: /* @__PURE__ */ new WeakMap()
@@ -1866,14 +2363,14 @@ var byTrace = trails.byTrace;
1866
2363
  var processTrail = trails.process;
1867
2364
  var thrownTrails = trails.thrown;
1868
2365
  function redact2(attributes) {
1869
- return _nullishCoalesce(_optionalChain([loggerConfigured, 'call', _89 => _89(), 'optionalAccess', _90 => _90.redact, 'call', _91 => _91(attributes)]), () => ( redactAttributes(attributes)));
2366
+ return _nullishCoalesce(_optionalChain([loggerConfigured, 'call', _114 => _114(), 'optionalAccess', _115 => _115.redact, 'call', _116 => _116(attributes)]), () => ( redactAttributes(attributes)));
1870
2367
  }
1871
2368
  function trailFor(create, state = local.getStore()) {
1872
2369
  if (state) {
1873
2370
  if (!state.breadcrumbs && create) state.breadcrumbs = new BreadcrumbTrail();
1874
2371
  return state.breadcrumbs;
1875
2372
  }
1876
- const traceId = _optionalChain([_api.trace, 'access', _92 => _92.getActiveSpan, 'call', _93 => _93(), 'optionalAccess', _94 => _94.spanContext, 'call', _95 => _95(), 'access', _96 => _96.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]);
1877
2374
  if (traceId && traceId !== INVALID_TRACE_ID) {
1878
2375
  let trail = byTrace.get(traceId);
1879
2376
  if (!trail && create) {
@@ -1892,9 +2389,9 @@ function addBreadcrumb(input) {
1892
2389
  try {
1893
2390
  const crumb = normalizeBreadcrumb(input, redact2);
1894
2391
  if (!crumb) return;
1895
- _optionalChain([trailFor, 'call', _97 => _97(true), 'optionalAccess', _98 => _98.add, 'call', _99 => _99(crumb)]);
1896
- _chunkMOZOUEMAcjs.noteCompatFeature.call(void 0, "breadcrumbs");
1897
- } catch (e23) {
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) {
1898
2395
  }
1899
2396
  }
1900
2397
  function recordLogBreadcrumb(level, message, attributes, state) {
@@ -1910,15 +2407,15 @@ function recordLogBreadcrumb(level, message, attributes, state) {
1910
2407
  }
1911
2408
  }
1912
2409
  const crumb = normalizeBreadcrumb({ type: "log", level, message, data }, redact2);
1913
- if (crumb) _optionalChain([trailFor, 'call', _100 => _100(true, state), 'optionalAccess', _101 => _101.add, 'call', _102 => _102(crumb)]);
1914
- } catch (e24) {
2410
+ if (crumb) _optionalChain([trailFor, 'call', _125 => _125(true, state), 'optionalAccess', _126 => _126.add, 'call', _127 => _127(crumb)]);
2411
+ } catch (e40) {
1915
2412
  }
1916
2413
  }
1917
2414
  function attributeBudget() {
1918
- const limit = Number(
2415
+ const limit2 = Number(
1919
2416
  _nullishCoalesce(process.env.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, () => ( process.env.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT))
1920
2417
  );
1921
- 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;
1922
2419
  }
1923
2420
  function rememberThrownBreadcrumbs(error, state) {
1924
2421
  if (state.breadcrumbs && error !== null && (typeof error === "object" || typeof error === "function"))
@@ -1928,10 +2425,10 @@ function breadcrumbEventAttributes(scrub, error) {
1928
2425
  try {
1929
2426
  const thrown = error !== null && typeof error === "object" ? thrownTrails.get(error) : void 0;
1930
2427
  const trail = _nullishCoalesce(thrown, () => ( trailFor(false)));
1931
- if (!_optionalChain([trail, 'optionalAccess', _103 => _103.size])) return {};
2428
+ if (!_optionalChain([trail, 'optionalAccess', _128 => _128.size])) return {};
1932
2429
  const json = breadcrumbsAttribute(trail.list(), scrub, attributeBudget());
1933
2430
  return json ? { [BREADCRUMBS_ATTRIBUTE]: json } : {};
1934
- } catch (e25) {
2431
+ } catch (e41) {
1935
2432
  return {};
1936
2433
  }
1937
2434
  }
@@ -1987,4 +2484,9 @@ function breadcrumbEventAttributes(scrub, error) {
1987
2484
 
1988
2485
 
1989
2486
 
1990
- 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.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;
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;