rterm-backend 1.9.2 → 2.3.1

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.
Files changed (2) hide show
  1. package/bin/gybackend.js +2053 -178
  2. package/package.json +2 -2
package/bin/gybackend.js CHANGED
@@ -11234,7 +11234,7 @@ var require_subset = __commonJS({
11234
11234
  var { ANY } = Comparator;
11235
11235
  var satisfies = require_satisfies();
11236
11236
  var compare2 = require_compare();
11237
- var subset = (sub, dom, options = {}) => {
11237
+ var subset2 = (sub, dom, options = {}) => {
11238
11238
  if (sub === dom) {
11239
11239
  return true;
11240
11240
  }
@@ -11383,7 +11383,7 @@ var require_subset = __commonJS({
11383
11383
  const comp = compare2(a.semver, b.semver, options);
11384
11384
  return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;
11385
11385
  };
11386
- module.exports = subset;
11386
+ module.exports = subset2;
11387
11387
  }
11388
11388
  });
11389
11389
 
@@ -11431,7 +11431,7 @@ var require_semver2 = __commonJS({
11431
11431
  var ltr = require_ltr();
11432
11432
  var intersects = require_intersects();
11433
11433
  var simplifyRange = require_simplify();
11434
- var subset = require_subset();
11434
+ var subset2 = require_subset();
11435
11435
  module.exports = {
11436
11436
  parse: parse8,
11437
11437
  valid,
@@ -11469,7 +11469,7 @@ var require_semver2 = __commonJS({
11469
11469
  ltr,
11470
11470
  intersects,
11471
11471
  simplifyRange,
11472
- subset,
11472
+ subset: subset2,
11473
11473
  SemVer,
11474
11474
  re: internalRe.re,
11475
11475
  src: internalRe.src,
@@ -26550,7 +26550,7 @@ var require_pdf_worker = __commonJS({
26550
26550
  var calculateMD5 = (function calculateMD5Closure() {
26551
26551
  var r = new Uint8Array([7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]);
26552
26552
  var k = new Int32Array([-680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426, -1473231341, -45705983, 1770035416, -1958414417, -42063, -1990404162, 1804603682, -40341101, -1502002290, 1236535329, -165796510, -1069501632, 643717713, -373897302, -701558691, 38016083, -660478335, -405537848, 568446438, -1019803690, -187363961, 1163531501, -1444681467, -51403784, 1735328473, -1926607734, -378558, -2022574463, 1839030562, -35309556, -1530992060, 1272893353, -155497632, -1094730640, 681279174, -358537222, -722521979, 76029189, -640364487, -421815835, 530742520, -995338651, -198630844, 1126891415, -1416354905, -57434055, 1700485571, -1894986606, -1051523, -2054922799, 1873313359, -30611744, -1560198380, 1309151649, -145523070, -1120210379, 718787259, -343485551]);
26553
- function hash(data, offset, length) {
26553
+ function hash2(data, offset, length) {
26554
26554
  var h0 = 1732584193, h1 = -271733879, h2 = -1732584194, h3 = 271733878;
26555
26555
  var paddedLength = length + 72 & ~63;
26556
26556
  var padded = new Uint8Array(paddedLength);
@@ -26604,7 +26604,7 @@ var require_pdf_worker = __commonJS({
26604
26604
  }
26605
26605
  return new Uint8Array([h0 & 255, h0 >> 8 & 255, h0 >> 16 & 255, h0 >>> 24 & 255, h1 & 255, h1 >> 8 & 255, h1 >> 16 & 255, h1 >>> 24 & 255, h2 & 255, h2 >> 8 & 255, h2 >> 16 & 255, h2 >>> 24 & 255, h3 & 255, h3 >> 8 & 255, h3 >> 16 & 255, h3 >>> 24 & 255]);
26606
26606
  }
26607
- return hash;
26607
+ return hash2;
26608
26608
  })();
26609
26609
  var Word64 = (function Word64Closure() {
26610
26610
  function Word642(highInteger, lowInteger) {
@@ -26708,7 +26708,7 @@ var require_pdf_worker = __commonJS({
26708
26708
  return rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10;
26709
26709
  }
26710
26710
  var k = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298];
26711
- function hash(data, offset, length) {
26711
+ function hash2(data, offset, length) {
26712
26712
  var h0 = 1779033703, h1 = 3144134277, h2 = 1013904242, h3 = 2773480762, h4 = 1359893119, h5 = 2600822924, h6 = 528734635, h7 = 1541459225;
26713
26713
  var paddedLength = Math.ceil((length + 9) / 64) * 64;
26714
26714
  var padded = new Uint8Array(paddedLength);
@@ -26762,7 +26762,7 @@ var require_pdf_worker = __commonJS({
26762
26762
  }
26763
26763
  return new Uint8Array([h0 >> 24 & 255, h0 >> 16 & 255, h0 >> 8 & 255, h0 & 255, h1 >> 24 & 255, h1 >> 16 & 255, h1 >> 8 & 255, h1 & 255, h2 >> 24 & 255, h2 >> 16 & 255, h2 >> 8 & 255, h2 & 255, h3 >> 24 & 255, h3 >> 16 & 255, h3 >> 8 & 255, h3 & 255, h4 >> 24 & 255, h4 >> 16 & 255, h4 >> 8 & 255, h4 & 255, h5 >> 24 & 255, h5 >> 16 & 255, h5 >> 8 & 255, h5 & 255, h6 >> 24 & 255, h6 >> 16 & 255, h6 >> 8 & 255, h6 & 255, h7 >> 24 & 255, h7 >> 16 & 255, h7 >> 8 & 255, h7 & 255]);
26764
26764
  }
26765
- return hash;
26765
+ return hash2;
26766
26766
  })();
26767
26767
  var calculateSHA512 = (function calculateSHA512Closure() {
26768
26768
  function ch(result, x, y, z, tmp) {
@@ -26824,7 +26824,7 @@ var require_pdf_worker = __commonJS({
26824
26824
  result.xor(tmp);
26825
26825
  }
26826
26826
  var k = [new Word64(1116352408, 3609767458), new Word64(1899447441, 602891725), new Word64(3049323471, 3964484399), new Word64(3921009573, 2173295548), new Word64(961987163, 4081628472), new Word64(1508970993, 3053834265), new Word64(2453635748, 2937671579), new Word64(2870763221, 3664609560), new Word64(3624381080, 2734883394), new Word64(310598401, 1164996542), new Word64(607225278, 1323610764), new Word64(1426881987, 3590304994), new Word64(1925078388, 4068182383), new Word64(2162078206, 991336113), new Word64(2614888103, 633803317), new Word64(3248222580, 3479774868), new Word64(3835390401, 2666613458), new Word64(4022224774, 944711139), new Word64(264347078, 2341262773), new Word64(604807628, 2007800933), new Word64(770255983, 1495990901), new Word64(1249150122, 1856431235), new Word64(1555081692, 3175218132), new Word64(1996064986, 2198950837), new Word64(2554220882, 3999719339), new Word64(2821834349, 766784016), new Word64(2952996808, 2566594879), new Word64(3210313671, 3203337956), new Word64(3336571891, 1034457026), new Word64(3584528711, 2466948901), new Word64(113926993, 3758326383), new Word64(338241895, 168717936), new Word64(666307205, 1188179964), new Word64(773529912, 1546045734), new Word64(1294757372, 1522805485), new Word64(1396182291, 2643833823), new Word64(1695183700, 2343527390), new Word64(1986661051, 1014477480), new Word64(2177026350, 1206759142), new Word64(2456956037, 344077627), new Word64(2730485921, 1290863460), new Word64(2820302411, 3158454273), new Word64(3259730800, 3505952657), new Word64(3345764771, 106217008), new Word64(3516065817, 3606008344), new Word64(3600352804, 1432725776), new Word64(4094571909, 1467031594), new Word64(275423344, 851169720), new Word64(430227734, 3100823752), new Word64(506948616, 1363258195), new Word64(659060556, 3750685593), new Word64(883997877, 3785050280), new Word64(958139571, 3318307427), new Word64(1322822218, 3812723403), new Word64(1537002063, 2003034995), new Word64(1747873779, 3602036899), new Word64(1955562222, 1575990012), new Word64(2024104815, 1125592928), new Word64(2227730452, 2716904306), new Word64(2361852424, 442776044), new Word64(2428436474, 593698344), new Word64(2756734187, 3733110249), new Word64(3204031479, 2999351573), new Word64(3329325298, 3815920427), new Word64(3391569614, 3928383900), new Word64(3515267271, 566280711), new Word64(3940187606, 3454069534), new Word64(4118630271, 4000239992), new Word64(116418474, 1914138554), new Word64(174292421, 2731055270), new Word64(289380356, 3203993006), new Word64(460393269, 320620315), new Word64(685471733, 587496836), new Word64(852142971, 1086792851), new Word64(1017036298, 365543100), new Word64(1126000580, 2618297676), new Word64(1288033470, 3409855158), new Word64(1501505948, 4234509866), new Word64(1607167915, 987167468), new Word64(1816402316, 1246189591)];
26827
- function hash(data, offset, length, mode384) {
26827
+ function hash2(data, offset, length, mode384) {
26828
26828
  mode384 = !!mode384;
26829
26829
  var h0, h1, h2, h3, h4, h5, h6, h7;
26830
26830
  if (!mode384) {
@@ -26959,13 +26959,13 @@ var require_pdf_worker = __commonJS({
26959
26959
  }
26960
26960
  return result;
26961
26961
  }
26962
- return hash;
26962
+ return hash2;
26963
26963
  })();
26964
26964
  var calculateSHA384 = /* @__PURE__ */ (function calculateSHA384Closure() {
26965
- function hash(data, offset, length) {
26965
+ function hash2(data, offset, length) {
26966
26966
  return calculateSHA512(data, offset, length, true);
26967
26967
  }
26968
- return hash;
26968
+ return hash2;
26969
26969
  })();
26970
26970
  var NullCipher = (function NullCipherClosure() {
26971
26971
  function NullCipher2() {
@@ -27749,14 +27749,14 @@ var require_pdf_worker = __commonJS({
27749
27749
  hashData[i++] = 255;
27750
27750
  hashData[i++] = 255;
27751
27751
  }
27752
- var hash = calculateMD5(hashData, 0, i);
27752
+ var hash2 = calculateMD5(hashData, 0, i);
27753
27753
  var keyLengthInBytes = keyLength >> 3;
27754
27754
  if (revision >= 3) {
27755
27755
  for (j = 0; j < 50; ++j) {
27756
- hash = calculateMD5(hash, 0, keyLengthInBytes);
27756
+ hash2 = calculateMD5(hash2, 0, keyLengthInBytes);
27757
27757
  }
27758
27758
  }
27759
- var encryptionKey = hash.subarray(0, keyLengthInBytes);
27759
+ var encryptionKey = hash2.subarray(0, keyLengthInBytes);
27760
27760
  var cipher, checkData;
27761
27761
  if (revision >= 3) {
27762
27762
  for (i = 0; i < 32; ++i) {
@@ -27802,11 +27802,11 @@ var require_pdf_worker = __commonJS({
27802
27802
  while (i < 32) {
27803
27803
  hashData[i++] = defaultPasswordBytes[j++];
27804
27804
  }
27805
- var hash = calculateMD5(hashData, 0, i);
27805
+ var hash2 = calculateMD5(hashData, 0, i);
27806
27806
  var keyLengthInBytes = keyLength >> 3;
27807
27807
  if (revision >= 3) {
27808
27808
  for (j = 0; j < 50; ++j) {
27809
- hash = calculateMD5(hash, 0, hash.length);
27809
+ hash2 = calculateMD5(hash2, 0, hash2.length);
27810
27810
  }
27811
27811
  }
27812
27812
  var cipher, userPassword;
@@ -27815,13 +27815,13 @@ var require_pdf_worker = __commonJS({
27815
27815
  var derivedKey = new Uint8Array(keyLengthInBytes), k;
27816
27816
  for (j = 19; j >= 0; j--) {
27817
27817
  for (k = 0; k < keyLengthInBytes; ++k) {
27818
- derivedKey[k] = hash[k] ^ j;
27818
+ derivedKey[k] = hash2[k] ^ j;
27819
27819
  }
27820
27820
  cipher = new ARCFourCipher(derivedKey);
27821
27821
  userPassword = cipher.encryptBlock(userPassword);
27822
27822
  }
27823
27823
  } else {
27824
- cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));
27824
+ cipher = new ARCFourCipher(hash2.subarray(0, keyLengthInBytes));
27825
27825
  userPassword = cipher.encryptBlock(ownerPassword);
27826
27826
  }
27827
27827
  return userPassword;
@@ -27927,8 +27927,8 @@ var require_pdf_worker = __commonJS({
27927
27927
  key[i++] = 108;
27928
27928
  key[i++] = 84;
27929
27929
  }
27930
- var hash = calculateMD5(key, 0, i);
27931
- return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));
27930
+ var hash2 = calculateMD5(key, 0, i);
27931
+ return hash2.subarray(0, Math.min(encryptionKey.length + 5, 16));
27932
27932
  }
27933
27933
  function buildCipherConstructor(cf, name, num2, gen, key) {
27934
27934
  if (!(0, _primitives.isName)(name)) {
@@ -28571,20 +28571,20 @@ var require_pdf_worker = __commonJS({
28571
28571
  descriptor.fontAliases = /* @__PURE__ */ Object.create(null);
28572
28572
  }
28573
28573
  var fontAliases = descriptor.fontAliases;
28574
- var hash = preEvaluatedFont.hash;
28575
- if (fontAliases[hash]) {
28576
- var aliasFontRef = fontAliases[hash].aliasRef;
28574
+ var hash2 = preEvaluatedFont.hash;
28575
+ if (fontAliases[hash2]) {
28576
+ var aliasFontRef = fontAliases[hash2].aliasRef;
28577
28577
  if (fontRefIsRef && aliasFontRef && this.fontCache.has(aliasFontRef)) {
28578
28578
  this.fontCache.putAlias(fontRef, aliasFontRef);
28579
28579
  return this.fontCache.get(fontRef);
28580
28580
  }
28581
28581
  } else {
28582
- fontAliases[hash] = { fontID: _fonts.Font.getFontID() };
28582
+ fontAliases[hash2] = { fontID: _fonts.Font.getFontID() };
28583
28583
  }
28584
28584
  if (fontRefIsRef) {
28585
- fontAliases[hash].aliasRef = fontRef;
28585
+ fontAliases[hash2].aliasRef = fontRef;
28586
28586
  }
28587
- fontID = fontAliases[hash].fontID;
28587
+ fontID = fontAliases[hash2].fontID;
28588
28588
  }
28589
28589
  if (fontRefIsRef) {
28590
28590
  this.fontCache.put(fontRef, fontCapability.promise);
@@ -29793,20 +29793,20 @@ var require_pdf_worker = __commonJS({
29793
29793
  }
29794
29794
  var descriptor = dict.get("FontDescriptor");
29795
29795
  if (descriptor) {
29796
- var hash = new _murmurhash.MurmurHash3_64();
29796
+ var hash2 = new _murmurhash.MurmurHash3_64();
29797
29797
  var encoding = baseDict.getRaw("Encoding");
29798
29798
  if ((0, _primitives.isName)(encoding)) {
29799
- hash.update(encoding.name);
29799
+ hash2.update(encoding.name);
29800
29800
  } else if ((0, _primitives.isRef)(encoding)) {
29801
- hash.update(encoding.toString());
29801
+ hash2.update(encoding.toString());
29802
29802
  } else if ((0, _primitives.isDict)(encoding)) {
29803
29803
  var keys = encoding.getKeys();
29804
29804
  for (var i = 0, ii = keys.length; i < ii; i++) {
29805
29805
  var entry = encoding.getRaw(keys[i]);
29806
29806
  if ((0, _primitives.isName)(entry)) {
29807
- hash.update(entry.name);
29807
+ hash2.update(entry.name);
29808
29808
  } else if ((0, _primitives.isRef)(entry)) {
29809
- hash.update(entry.toString());
29809
+ hash2.update(entry.toString());
29810
29810
  } else if (Array.isArray(entry)) {
29811
29811
  var diffLength = entry.length, diffBuf = new Array(diffLength);
29812
29812
  for (var j = 0; j < diffLength; j++) {
@@ -29817,7 +29817,7 @@ var require_pdf_worker = __commonJS({
29817
29817
  diffBuf[j] = diffEntry.toString();
29818
29818
  }
29819
29819
  }
29820
- hash.update(diffBuf.join());
29820
+ hash2.update(diffBuf.join());
29821
29821
  }
29822
29822
  }
29823
29823
  }
@@ -29825,14 +29825,14 @@ var require_pdf_worker = __commonJS({
29825
29825
  if ((0, _primitives.isStream)(toUnicode)) {
29826
29826
  var stream = toUnicode.str || toUnicode;
29827
29827
  uint8array = stream.buffer ? new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) : new Uint8Array(stream.bytes.buffer, stream.start, stream.end - stream.start);
29828
- hash.update(uint8array);
29828
+ hash2.update(uint8array);
29829
29829
  } else if ((0, _primitives.isName)(toUnicode)) {
29830
- hash.update(toUnicode.name);
29830
+ hash2.update(toUnicode.name);
29831
29831
  }
29832
29832
  var widths = dict.get("Widths") || baseDict.get("Widths");
29833
29833
  if (widths) {
29834
29834
  uint8array = new Uint8Array(new Uint32Array(widths).buffer);
29835
- hash.update(uint8array);
29835
+ hash2.update(uint8array);
29836
29836
  }
29837
29837
  }
29838
29838
  return {
@@ -29841,7 +29841,7 @@ var require_pdf_worker = __commonJS({
29841
29841
  baseDict,
29842
29842
  composite,
29843
29843
  type: type.name,
29844
- hash: hash ? hash.hexdigest() : ""
29844
+ hash: hash2 ? hash2.hexdigest() : ""
29845
29845
  };
29846
29846
  },
29847
29847
  translateFont: function PartialEvaluator_translateFont(preEvaluatedFont) {
@@ -43397,18 +43397,18 @@ var require_pdf_worker = __commonJS({
43397
43397
  return (0, _util.shadow)(this, "documentInfo", docInfo);
43398
43398
  },
43399
43399
  get fingerprint() {
43400
- var xref = this.xref, hash, fileID = "";
43400
+ var xref = this.xref, hash2, fileID = "";
43401
43401
  var idArray = xref.trailer.get("ID");
43402
43402
  if (Array.isArray(idArray) && idArray[0] && (0, _util.isString)(idArray[0]) && idArray[0] !== EMPTY_FINGERPRINT) {
43403
- hash = (0, _util.stringToBytes)(idArray[0]);
43403
+ hash2 = (0, _util.stringToBytes)(idArray[0]);
43404
43404
  } else {
43405
43405
  if (this.stream.ensureRange) {
43406
43406
  this.stream.ensureRange(0, Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
43407
43407
  }
43408
- hash = (0, _crypto.calculateMD5)(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
43408
+ hash2 = (0, _crypto.calculateMD5)(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
43409
43409
  }
43410
- for (var i = 0, n2 = hash.length; i < n2; i++) {
43411
- var hex = hash[i].toString(16);
43410
+ for (var i = 0, n2 = hash2.length; i < n2; i++) {
43411
+ var hex = hash2[i].toString(16);
43412
43412
  fileID += hex.length === 1 ? "0" + hex : hex;
43413
43413
  }
43414
43414
  return (0, _util.shadow)(this, "fingerprint", fileID);
@@ -88754,7 +88754,7 @@ var require_pdf_worker2 = __commonJS({
88754
88754
  var calculateMD5 = (function calculateMD5Closure() {
88755
88755
  var r = new Uint8Array([7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]);
88756
88756
  var k = new Int32Array([-680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426, -1473231341, -45705983, 1770035416, -1958414417, -42063, -1990404162, 1804603682, -40341101, -1502002290, 1236535329, -165796510, -1069501632, 643717713, -373897302, -701558691, 38016083, -660478335, -405537848, 568446438, -1019803690, -187363961, 1163531501, -1444681467, -51403784, 1735328473, -1926607734, -378558, -2022574463, 1839030562, -35309556, -1530992060, 1272893353, -155497632, -1094730640, 681279174, -358537222, -722521979, 76029189, -640364487, -421815835, 530742520, -995338651, -198630844, 1126891415, -1416354905, -57434055, 1700485571, -1894986606, -1051523, -2054922799, 1873313359, -30611744, -1560198380, 1309151649, -145523070, -1120210379, 718787259, -343485551]);
88757
- function hash(data, offset, length) {
88757
+ function hash2(data, offset, length) {
88758
88758
  var h0 = 1732584193, h1 = -271733879, h2 = -1732584194, h3 = 271733878;
88759
88759
  var paddedLength = length + 72 & ~63;
88760
88760
  var padded = new Uint8Array(paddedLength);
@@ -88808,7 +88808,7 @@ var require_pdf_worker2 = __commonJS({
88808
88808
  }
88809
88809
  return new Uint8Array([h0 & 255, h0 >> 8 & 255, h0 >> 16 & 255, h0 >>> 24 & 255, h1 & 255, h1 >> 8 & 255, h1 >> 16 & 255, h1 >>> 24 & 255, h2 & 255, h2 >> 8 & 255, h2 >> 16 & 255, h2 >>> 24 & 255, h3 & 255, h3 >> 8 & 255, h3 >> 16 & 255, h3 >>> 24 & 255]);
88810
88810
  }
88811
- return hash;
88811
+ return hash2;
88812
88812
  })();
88813
88813
  var Word64 = (function Word64Closure() {
88814
88814
  function Word642(highInteger, lowInteger) {
@@ -88912,7 +88912,7 @@ var require_pdf_worker2 = __commonJS({
88912
88912
  return rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10;
88913
88913
  }
88914
88914
  var k = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298];
88915
- function hash(data, offset, length) {
88915
+ function hash2(data, offset, length) {
88916
88916
  var h0 = 1779033703, h1 = 3144134277, h2 = 1013904242, h3 = 2773480762, h4 = 1359893119, h5 = 2600822924, h6 = 528734635, h7 = 1541459225;
88917
88917
  var paddedLength = Math.ceil((length + 9) / 64) * 64;
88918
88918
  var padded = new Uint8Array(paddedLength);
@@ -88966,7 +88966,7 @@ var require_pdf_worker2 = __commonJS({
88966
88966
  }
88967
88967
  return new Uint8Array([h0 >> 24 & 255, h0 >> 16 & 255, h0 >> 8 & 255, h0 & 255, h1 >> 24 & 255, h1 >> 16 & 255, h1 >> 8 & 255, h1 & 255, h2 >> 24 & 255, h2 >> 16 & 255, h2 >> 8 & 255, h2 & 255, h3 >> 24 & 255, h3 >> 16 & 255, h3 >> 8 & 255, h3 & 255, h4 >> 24 & 255, h4 >> 16 & 255, h4 >> 8 & 255, h4 & 255, h5 >> 24 & 255, h5 >> 16 & 255, h5 >> 8 & 255, h5 & 255, h6 >> 24 & 255, h6 >> 16 & 255, h6 >> 8 & 255, h6 & 255, h7 >> 24 & 255, h7 >> 16 & 255, h7 >> 8 & 255, h7 & 255]);
88968
88968
  }
88969
- return hash;
88969
+ return hash2;
88970
88970
  })();
88971
88971
  var calculateSHA512 = (function calculateSHA512Closure() {
88972
88972
  function ch(result, x, y, z, tmp) {
@@ -89028,7 +89028,7 @@ var require_pdf_worker2 = __commonJS({
89028
89028
  result.xor(tmp);
89029
89029
  }
89030
89030
  var k = [new Word64(1116352408, 3609767458), new Word64(1899447441, 602891725), new Word64(3049323471, 3964484399), new Word64(3921009573, 2173295548), new Word64(961987163, 4081628472), new Word64(1508970993, 3053834265), new Word64(2453635748, 2937671579), new Word64(2870763221, 3664609560), new Word64(3624381080, 2734883394), new Word64(310598401, 1164996542), new Word64(607225278, 1323610764), new Word64(1426881987, 3590304994), new Word64(1925078388, 4068182383), new Word64(2162078206, 991336113), new Word64(2614888103, 633803317), new Word64(3248222580, 3479774868), new Word64(3835390401, 2666613458), new Word64(4022224774, 944711139), new Word64(264347078, 2341262773), new Word64(604807628, 2007800933), new Word64(770255983, 1495990901), new Word64(1249150122, 1856431235), new Word64(1555081692, 3175218132), new Word64(1996064986, 2198950837), new Word64(2554220882, 3999719339), new Word64(2821834349, 766784016), new Word64(2952996808, 2566594879), new Word64(3210313671, 3203337956), new Word64(3336571891, 1034457026), new Word64(3584528711, 2466948901), new Word64(113926993, 3758326383), new Word64(338241895, 168717936), new Word64(666307205, 1188179964), new Word64(773529912, 1546045734), new Word64(1294757372, 1522805485), new Word64(1396182291, 2643833823), new Word64(1695183700, 2343527390), new Word64(1986661051, 1014477480), new Word64(2177026350, 1206759142), new Word64(2456956037, 344077627), new Word64(2730485921, 1290863460), new Word64(2820302411, 3158454273), new Word64(3259730800, 3505952657), new Word64(3345764771, 106217008), new Word64(3516065817, 3606008344), new Word64(3600352804, 1432725776), new Word64(4094571909, 1467031594), new Word64(275423344, 851169720), new Word64(430227734, 3100823752), new Word64(506948616, 1363258195), new Word64(659060556, 3750685593), new Word64(883997877, 3785050280), new Word64(958139571, 3318307427), new Word64(1322822218, 3812723403), new Word64(1537002063, 2003034995), new Word64(1747873779, 3602036899), new Word64(1955562222, 1575990012), new Word64(2024104815, 1125592928), new Word64(2227730452, 2716904306), new Word64(2361852424, 442776044), new Word64(2428436474, 593698344), new Word64(2756734187, 3733110249), new Word64(3204031479, 2999351573), new Word64(3329325298, 3815920427), new Word64(3391569614, 3928383900), new Word64(3515267271, 566280711), new Word64(3940187606, 3454069534), new Word64(4118630271, 4000239992), new Word64(116418474, 1914138554), new Word64(174292421, 2731055270), new Word64(289380356, 3203993006), new Word64(460393269, 320620315), new Word64(685471733, 587496836), new Word64(852142971, 1086792851), new Word64(1017036298, 365543100), new Word64(1126000580, 2618297676), new Word64(1288033470, 3409855158), new Word64(1501505948, 4234509866), new Word64(1607167915, 987167468), new Word64(1816402316, 1246189591)];
89031
- function hash(data, offset, length, mode384) {
89031
+ function hash2(data, offset, length, mode384) {
89032
89032
  mode384 = !!mode384;
89033
89033
  var h0, h1, h2, h3, h4, h5, h6, h7;
89034
89034
  if (!mode384) {
@@ -89163,13 +89163,13 @@ var require_pdf_worker2 = __commonJS({
89163
89163
  }
89164
89164
  return result;
89165
89165
  }
89166
- return hash;
89166
+ return hash2;
89167
89167
  })();
89168
89168
  var calculateSHA384 = /* @__PURE__ */ (function calculateSHA384Closure() {
89169
- function hash(data, offset, length) {
89169
+ function hash2(data, offset, length) {
89170
89170
  return calculateSHA512(data, offset, length, true);
89171
89171
  }
89172
- return hash;
89172
+ return hash2;
89173
89173
  })();
89174
89174
  var NullCipher = (function NullCipherClosure() {
89175
89175
  function NullCipher2() {
@@ -89953,14 +89953,14 @@ var require_pdf_worker2 = __commonJS({
89953
89953
  hashData[i++] = 255;
89954
89954
  hashData[i++] = 255;
89955
89955
  }
89956
- var hash = calculateMD5(hashData, 0, i);
89956
+ var hash2 = calculateMD5(hashData, 0, i);
89957
89957
  var keyLengthInBytes = keyLength >> 3;
89958
89958
  if (revision >= 3) {
89959
89959
  for (j = 0; j < 50; ++j) {
89960
- hash = calculateMD5(hash, 0, keyLengthInBytes);
89960
+ hash2 = calculateMD5(hash2, 0, keyLengthInBytes);
89961
89961
  }
89962
89962
  }
89963
- var encryptionKey = hash.subarray(0, keyLengthInBytes);
89963
+ var encryptionKey = hash2.subarray(0, keyLengthInBytes);
89964
89964
  var cipher, checkData;
89965
89965
  if (revision >= 3) {
89966
89966
  for (i = 0; i < 32; ++i) {
@@ -90006,11 +90006,11 @@ var require_pdf_worker2 = __commonJS({
90006
90006
  while (i < 32) {
90007
90007
  hashData[i++] = defaultPasswordBytes[j++];
90008
90008
  }
90009
- var hash = calculateMD5(hashData, 0, i);
90009
+ var hash2 = calculateMD5(hashData, 0, i);
90010
90010
  var keyLengthInBytes = keyLength >> 3;
90011
90011
  if (revision >= 3) {
90012
90012
  for (j = 0; j < 50; ++j) {
90013
- hash = calculateMD5(hash, 0, hash.length);
90013
+ hash2 = calculateMD5(hash2, 0, hash2.length);
90014
90014
  }
90015
90015
  }
90016
90016
  var cipher, userPassword;
@@ -90019,13 +90019,13 @@ var require_pdf_worker2 = __commonJS({
90019
90019
  var derivedKey = new Uint8Array(keyLengthInBytes), k;
90020
90020
  for (j = 19; j >= 0; j--) {
90021
90021
  for (k = 0; k < keyLengthInBytes; ++k) {
90022
- derivedKey[k] = hash[k] ^ j;
90022
+ derivedKey[k] = hash2[k] ^ j;
90023
90023
  }
90024
90024
  cipher = new ARCFourCipher(derivedKey);
90025
90025
  userPassword = cipher.encryptBlock(userPassword);
90026
90026
  }
90027
90027
  } else {
90028
- cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));
90028
+ cipher = new ARCFourCipher(hash2.subarray(0, keyLengthInBytes));
90029
90029
  userPassword = cipher.encryptBlock(ownerPassword);
90030
90030
  }
90031
90031
  return userPassword;
@@ -90131,8 +90131,8 @@ var require_pdf_worker2 = __commonJS({
90131
90131
  key[i++] = 108;
90132
90132
  key[i++] = 84;
90133
90133
  }
90134
- var hash = calculateMD5(key, 0, i);
90135
- return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));
90134
+ var hash2 = calculateMD5(key, 0, i);
90135
+ return hash2.subarray(0, Math.min(encryptionKey.length + 5, 16));
90136
90136
  }
90137
90137
  function buildCipherConstructor(cf, name, num2, gen, key) {
90138
90138
  if (!(0, _primitives.isName)(name)) {
@@ -90775,20 +90775,20 @@ var require_pdf_worker2 = __commonJS({
90775
90775
  descriptor.fontAliases = /* @__PURE__ */ Object.create(null);
90776
90776
  }
90777
90777
  var fontAliases = descriptor.fontAliases;
90778
- var hash = preEvaluatedFont.hash;
90779
- if (fontAliases[hash]) {
90780
- var aliasFontRef = fontAliases[hash].aliasRef;
90778
+ var hash2 = preEvaluatedFont.hash;
90779
+ if (fontAliases[hash2]) {
90780
+ var aliasFontRef = fontAliases[hash2].aliasRef;
90781
90781
  if (fontRefIsRef && aliasFontRef && this.fontCache.has(aliasFontRef)) {
90782
90782
  this.fontCache.putAlias(fontRef, aliasFontRef);
90783
90783
  return this.fontCache.get(fontRef);
90784
90784
  }
90785
90785
  } else {
90786
- fontAliases[hash] = { fontID: _fonts.Font.getFontID() };
90786
+ fontAliases[hash2] = { fontID: _fonts.Font.getFontID() };
90787
90787
  }
90788
90788
  if (fontRefIsRef) {
90789
- fontAliases[hash].aliasRef = fontRef;
90789
+ fontAliases[hash2].aliasRef = fontRef;
90790
90790
  }
90791
- fontID = fontAliases[hash].fontID;
90791
+ fontID = fontAliases[hash2].fontID;
90792
90792
  }
90793
90793
  if (fontRefIsRef) {
90794
90794
  this.fontCache.put(fontRef, fontCapability.promise);
@@ -91997,20 +91997,20 @@ var require_pdf_worker2 = __commonJS({
91997
91997
  }
91998
91998
  var descriptor = dict.get("FontDescriptor");
91999
91999
  if (descriptor) {
92000
- var hash = new _murmurhash.MurmurHash3_64();
92000
+ var hash2 = new _murmurhash.MurmurHash3_64();
92001
92001
  var encoding = baseDict.getRaw("Encoding");
92002
92002
  if ((0, _primitives.isName)(encoding)) {
92003
- hash.update(encoding.name);
92003
+ hash2.update(encoding.name);
92004
92004
  } else if ((0, _primitives.isRef)(encoding)) {
92005
- hash.update(encoding.toString());
92005
+ hash2.update(encoding.toString());
92006
92006
  } else if ((0, _primitives.isDict)(encoding)) {
92007
92007
  var keys = encoding.getKeys();
92008
92008
  for (var i = 0, ii = keys.length; i < ii; i++) {
92009
92009
  var entry = encoding.getRaw(keys[i]);
92010
92010
  if ((0, _primitives.isName)(entry)) {
92011
- hash.update(entry.name);
92011
+ hash2.update(entry.name);
92012
92012
  } else if ((0, _primitives.isRef)(entry)) {
92013
- hash.update(entry.toString());
92013
+ hash2.update(entry.toString());
92014
92014
  } else if (Array.isArray(entry)) {
92015
92015
  var diffLength = entry.length, diffBuf = new Array(diffLength);
92016
92016
  for (var j = 0; j < diffLength; j++) {
@@ -92021,7 +92021,7 @@ var require_pdf_worker2 = __commonJS({
92021
92021
  diffBuf[j] = diffEntry.toString();
92022
92022
  }
92023
92023
  }
92024
- hash.update(diffBuf.join());
92024
+ hash2.update(diffBuf.join());
92025
92025
  }
92026
92026
  }
92027
92027
  }
@@ -92029,14 +92029,14 @@ var require_pdf_worker2 = __commonJS({
92029
92029
  if ((0, _primitives.isStream)(toUnicode)) {
92030
92030
  var stream = toUnicode.str || toUnicode;
92031
92031
  uint8array = stream.buffer ? new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) : new Uint8Array(stream.bytes.buffer, stream.start, stream.end - stream.start);
92032
- hash.update(uint8array);
92032
+ hash2.update(uint8array);
92033
92033
  } else if ((0, _primitives.isName)(toUnicode)) {
92034
- hash.update(toUnicode.name);
92034
+ hash2.update(toUnicode.name);
92035
92035
  }
92036
92036
  var widths = dict.get("Widths") || baseDict.get("Widths");
92037
92037
  if (widths) {
92038
92038
  uint8array = new Uint8Array(new Uint32Array(widths).buffer);
92039
- hash.update(uint8array);
92039
+ hash2.update(uint8array);
92040
92040
  }
92041
92041
  }
92042
92042
  return {
@@ -92045,7 +92045,7 @@ var require_pdf_worker2 = __commonJS({
92045
92045
  baseDict,
92046
92046
  composite,
92047
92047
  type: type.name,
92048
- hash: hash ? hash.hexdigest() : ""
92048
+ hash: hash2 ? hash2.hexdigest() : ""
92049
92049
  };
92050
92050
  },
92051
92051
  translateFont: function PartialEvaluator_translateFont(preEvaluatedFont) {
@@ -105605,18 +105605,18 @@ var require_pdf_worker2 = __commonJS({
105605
105605
  return (0, _util.shadow)(this, "documentInfo", docInfo);
105606
105606
  },
105607
105607
  get fingerprint() {
105608
- var xref = this.xref, hash, fileID = "";
105608
+ var xref = this.xref, hash2, fileID = "";
105609
105609
  var idArray = xref.trailer.get("ID");
105610
105610
  if (Array.isArray(idArray) && idArray[0] && (0, _util.isString)(idArray[0]) && idArray[0] !== EMPTY_FINGERPRINT) {
105611
- hash = (0, _util.stringToBytes)(idArray[0]);
105611
+ hash2 = (0, _util.stringToBytes)(idArray[0]);
105612
105612
  } else {
105613
105613
  if (this.stream.ensureRange) {
105614
105614
  this.stream.ensureRange(0, Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
105615
105615
  }
105616
- hash = (0, _crypto.calculateMD5)(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
105616
+ hash2 = (0, _crypto.calculateMD5)(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
105617
105617
  }
105618
- for (var i = 0, n2 = hash.length; i < n2; i++) {
105619
- var hex = hash[i].toString(16);
105618
+ for (var i = 0, n2 = hash2.length; i < n2; i++) {
105619
+ var hex = hash2[i].toString(16);
105620
105620
  fileID += hex.length === 1 ? "0" + hex : hex;
105621
105621
  }
105622
105622
  return (0, _util.shadow)(this, "fingerprint", fileID);
@@ -150881,7 +150881,7 @@ var require_pdf_worker3 = __commonJS({
150881
150881
  var calculateMD5 = (function calculateMD5Closure() {
150882
150882
  var r = new Uint8Array([7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]);
150883
150883
  var k = new Int32Array([-680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426, -1473231341, -45705983, 1770035416, -1958414417, -42063, -1990404162, 1804603682, -40341101, -1502002290, 1236535329, -165796510, -1069501632, 643717713, -373897302, -701558691, 38016083, -660478335, -405537848, 568446438, -1019803690, -187363961, 1163531501, -1444681467, -51403784, 1735328473, -1926607734, -378558, -2022574463, 1839030562, -35309556, -1530992060, 1272893353, -155497632, -1094730640, 681279174, -358537222, -722521979, 76029189, -640364487, -421815835, 530742520, -995338651, -198630844, 1126891415, -1416354905, -57434055, 1700485571, -1894986606, -1051523, -2054922799, 1873313359, -30611744, -1560198380, 1309151649, -145523070, -1120210379, 718787259, -343485551]);
150884
- function hash(data, offset, length) {
150884
+ function hash2(data, offset, length) {
150885
150885
  var h0 = 1732584193, h1 = -271733879, h2 = -1732584194, h3 = 271733878;
150886
150886
  var paddedLength = length + 72 & ~63;
150887
150887
  var padded = new Uint8Array(paddedLength);
@@ -150935,7 +150935,7 @@ var require_pdf_worker3 = __commonJS({
150935
150935
  }
150936
150936
  return new Uint8Array([h0 & 255, h0 >> 8 & 255, h0 >> 16 & 255, h0 >>> 24 & 255, h1 & 255, h1 >> 8 & 255, h1 >> 16 & 255, h1 >>> 24 & 255, h2 & 255, h2 >> 8 & 255, h2 >> 16 & 255, h2 >>> 24 & 255, h3 & 255, h3 >> 8 & 255, h3 >> 16 & 255, h3 >>> 24 & 255]);
150937
150937
  }
150938
- return hash;
150938
+ return hash2;
150939
150939
  })();
150940
150940
  var Word64 = (function Word64Closure() {
150941
150941
  function Word642(highInteger, lowInteger) {
@@ -151039,7 +151039,7 @@ var require_pdf_worker3 = __commonJS({
151039
151039
  return rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10;
151040
151040
  }
151041
151041
  var k = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298];
151042
- function hash(data, offset, length) {
151042
+ function hash2(data, offset, length) {
151043
151043
  var h0 = 1779033703, h1 = 3144134277, h2 = 1013904242, h3 = 2773480762, h4 = 1359893119, h5 = 2600822924, h6 = 528734635, h7 = 1541459225;
151044
151044
  var paddedLength = Math.ceil((length + 9) / 64) * 64;
151045
151045
  var padded = new Uint8Array(paddedLength);
@@ -151093,7 +151093,7 @@ var require_pdf_worker3 = __commonJS({
151093
151093
  }
151094
151094
  return new Uint8Array([h0 >> 24 & 255, h0 >> 16 & 255, h0 >> 8 & 255, h0 & 255, h1 >> 24 & 255, h1 >> 16 & 255, h1 >> 8 & 255, h1 & 255, h2 >> 24 & 255, h2 >> 16 & 255, h2 >> 8 & 255, h2 & 255, h3 >> 24 & 255, h3 >> 16 & 255, h3 >> 8 & 255, h3 & 255, h4 >> 24 & 255, h4 >> 16 & 255, h4 >> 8 & 255, h4 & 255, h5 >> 24 & 255, h5 >> 16 & 255, h5 >> 8 & 255, h5 & 255, h6 >> 24 & 255, h6 >> 16 & 255, h6 >> 8 & 255, h6 & 255, h7 >> 24 & 255, h7 >> 16 & 255, h7 >> 8 & 255, h7 & 255]);
151095
151095
  }
151096
- return hash;
151096
+ return hash2;
151097
151097
  })();
151098
151098
  var calculateSHA512 = (function calculateSHA512Closure() {
151099
151099
  function ch(result, x, y, z, tmp) {
@@ -151155,7 +151155,7 @@ var require_pdf_worker3 = __commonJS({
151155
151155
  result.xor(tmp);
151156
151156
  }
151157
151157
  var k = [new Word64(1116352408, 3609767458), new Word64(1899447441, 602891725), new Word64(3049323471, 3964484399), new Word64(3921009573, 2173295548), new Word64(961987163, 4081628472), new Word64(1508970993, 3053834265), new Word64(2453635748, 2937671579), new Word64(2870763221, 3664609560), new Word64(3624381080, 2734883394), new Word64(310598401, 1164996542), new Word64(607225278, 1323610764), new Word64(1426881987, 3590304994), new Word64(1925078388, 4068182383), new Word64(2162078206, 991336113), new Word64(2614888103, 633803317), new Word64(3248222580, 3479774868), new Word64(3835390401, 2666613458), new Word64(4022224774, 944711139), new Word64(264347078, 2341262773), new Word64(604807628, 2007800933), new Word64(770255983, 1495990901), new Word64(1249150122, 1856431235), new Word64(1555081692, 3175218132), new Word64(1996064986, 2198950837), new Word64(2554220882, 3999719339), new Word64(2821834349, 766784016), new Word64(2952996808, 2566594879), new Word64(3210313671, 3203337956), new Word64(3336571891, 1034457026), new Word64(3584528711, 2466948901), new Word64(113926993, 3758326383), new Word64(338241895, 168717936), new Word64(666307205, 1188179964), new Word64(773529912, 1546045734), new Word64(1294757372, 1522805485), new Word64(1396182291, 2643833823), new Word64(1695183700, 2343527390), new Word64(1986661051, 1014477480), new Word64(2177026350, 1206759142), new Word64(2456956037, 344077627), new Word64(2730485921, 1290863460), new Word64(2820302411, 3158454273), new Word64(3259730800, 3505952657), new Word64(3345764771, 106217008), new Word64(3516065817, 3606008344), new Word64(3600352804, 1432725776), new Word64(4094571909, 1467031594), new Word64(275423344, 851169720), new Word64(430227734, 3100823752), new Word64(506948616, 1363258195), new Word64(659060556, 3750685593), new Word64(883997877, 3785050280), new Word64(958139571, 3318307427), new Word64(1322822218, 3812723403), new Word64(1537002063, 2003034995), new Word64(1747873779, 3602036899), new Word64(1955562222, 1575990012), new Word64(2024104815, 1125592928), new Word64(2227730452, 2716904306), new Word64(2361852424, 442776044), new Word64(2428436474, 593698344), new Word64(2756734187, 3733110249), new Word64(3204031479, 2999351573), new Word64(3329325298, 3815920427), new Word64(3391569614, 3928383900), new Word64(3515267271, 566280711), new Word64(3940187606, 3454069534), new Word64(4118630271, 4000239992), new Word64(116418474, 1914138554), new Word64(174292421, 2731055270), new Word64(289380356, 3203993006), new Word64(460393269, 320620315), new Word64(685471733, 587496836), new Word64(852142971, 1086792851), new Word64(1017036298, 365543100), new Word64(1126000580, 2618297676), new Word64(1288033470, 3409855158), new Word64(1501505948, 4234509866), new Word64(1607167915, 987167468), new Word64(1816402316, 1246189591)];
151158
- function hash(data, offset, length, mode384) {
151158
+ function hash2(data, offset, length, mode384) {
151159
151159
  mode384 = !!mode384;
151160
151160
  var h0, h1, h2, h3, h4, h5, h6, h7;
151161
151161
  if (!mode384) {
@@ -151290,13 +151290,13 @@ var require_pdf_worker3 = __commonJS({
151290
151290
  }
151291
151291
  return result;
151292
151292
  }
151293
- return hash;
151293
+ return hash2;
151294
151294
  })();
151295
151295
  var calculateSHA384 = /* @__PURE__ */ (function calculateSHA384Closure() {
151296
- function hash(data, offset, length) {
151296
+ function hash2(data, offset, length) {
151297
151297
  return calculateSHA512(data, offset, length, true);
151298
151298
  }
151299
- return hash;
151299
+ return hash2;
151300
151300
  })();
151301
151301
  var NullCipher = (function NullCipherClosure() {
151302
151302
  function NullCipher2() {
@@ -152080,14 +152080,14 @@ var require_pdf_worker3 = __commonJS({
152080
152080
  hashData[i++] = 255;
152081
152081
  hashData[i++] = 255;
152082
152082
  }
152083
- var hash = calculateMD5(hashData, 0, i);
152083
+ var hash2 = calculateMD5(hashData, 0, i);
152084
152084
  var keyLengthInBytes = keyLength >> 3;
152085
152085
  if (revision >= 3) {
152086
152086
  for (j = 0; j < 50; ++j) {
152087
- hash = calculateMD5(hash, 0, keyLengthInBytes);
152087
+ hash2 = calculateMD5(hash2, 0, keyLengthInBytes);
152088
152088
  }
152089
152089
  }
152090
- var encryptionKey = hash.subarray(0, keyLengthInBytes);
152090
+ var encryptionKey = hash2.subarray(0, keyLengthInBytes);
152091
152091
  var cipher, checkData;
152092
152092
  if (revision >= 3) {
152093
152093
  for (i = 0; i < 32; ++i) {
@@ -152133,11 +152133,11 @@ var require_pdf_worker3 = __commonJS({
152133
152133
  while (i < 32) {
152134
152134
  hashData[i++] = defaultPasswordBytes[j++];
152135
152135
  }
152136
- var hash = calculateMD5(hashData, 0, i);
152136
+ var hash2 = calculateMD5(hashData, 0, i);
152137
152137
  var keyLengthInBytes = keyLength >> 3;
152138
152138
  if (revision >= 3) {
152139
152139
  for (j = 0; j < 50; ++j) {
152140
- hash = calculateMD5(hash, 0, hash.length);
152140
+ hash2 = calculateMD5(hash2, 0, hash2.length);
152141
152141
  }
152142
152142
  }
152143
152143
  var cipher, userPassword;
@@ -152146,13 +152146,13 @@ var require_pdf_worker3 = __commonJS({
152146
152146
  var derivedKey = new Uint8Array(keyLengthInBytes), k;
152147
152147
  for (j = 19; j >= 0; j--) {
152148
152148
  for (k = 0; k < keyLengthInBytes; ++k) {
152149
- derivedKey[k] = hash[k] ^ j;
152149
+ derivedKey[k] = hash2[k] ^ j;
152150
152150
  }
152151
152151
  cipher = new ARCFourCipher(derivedKey);
152152
152152
  userPassword = cipher.encryptBlock(userPassword);
152153
152153
  }
152154
152154
  } else {
152155
- cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));
152155
+ cipher = new ARCFourCipher(hash2.subarray(0, keyLengthInBytes));
152156
152156
  userPassword = cipher.encryptBlock(ownerPassword);
152157
152157
  }
152158
152158
  return userPassword;
@@ -152258,8 +152258,8 @@ var require_pdf_worker3 = __commonJS({
152258
152258
  key[i++] = 108;
152259
152259
  key[i++] = 84;
152260
152260
  }
152261
- var hash = calculateMD5(key, 0, i);
152262
- return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));
152261
+ var hash2 = calculateMD5(key, 0, i);
152262
+ return hash2.subarray(0, Math.min(encryptionKey.length + 5, 16));
152263
152263
  }
152264
152264
  function buildCipherConstructor(cf, name, num2, gen, key) {
152265
152265
  if (!(0, _primitives.isName)(name)) {
@@ -152878,20 +152878,20 @@ var require_pdf_worker3 = __commonJS({
152878
152878
  descriptor.fontAliases = /* @__PURE__ */ Object.create(null);
152879
152879
  }
152880
152880
  var fontAliases = descriptor.fontAliases;
152881
- var hash = preEvaluatedFont.hash;
152882
- if (fontAliases[hash]) {
152883
- var aliasFontRef = fontAliases[hash].aliasRef;
152881
+ var hash2 = preEvaluatedFont.hash;
152882
+ if (fontAliases[hash2]) {
152883
+ var aliasFontRef = fontAliases[hash2].aliasRef;
152884
152884
  if (fontRefIsRef && aliasFontRef && this.fontCache.has(aliasFontRef)) {
152885
152885
  this.fontCache.putAlias(fontRef, aliasFontRef);
152886
152886
  return this.fontCache.get(fontRef);
152887
152887
  }
152888
152888
  } else {
152889
- fontAliases[hash] = { fontID: _fonts.Font.getFontID() };
152889
+ fontAliases[hash2] = { fontID: _fonts.Font.getFontID() };
152890
152890
  }
152891
152891
  if (fontRefIsRef) {
152892
- fontAliases[hash].aliasRef = fontRef;
152892
+ fontAliases[hash2].aliasRef = fontRef;
152893
152893
  }
152894
- fontID = fontAliases[hash].fontID;
152894
+ fontID = fontAliases[hash2].fontID;
152895
152895
  }
152896
152896
  if (fontRefIsRef) {
152897
152897
  this.fontCache.put(fontRef, fontCapability.promise);
@@ -154098,20 +154098,20 @@ var require_pdf_worker3 = __commonJS({
154098
154098
  }
154099
154099
  var descriptor = dict.get("FontDescriptor");
154100
154100
  if (descriptor) {
154101
- var hash = new _murmurhash.MurmurHash3_64();
154101
+ var hash2 = new _murmurhash.MurmurHash3_64();
154102
154102
  var encoding = baseDict.getRaw("Encoding");
154103
154103
  if ((0, _primitives.isName)(encoding)) {
154104
- hash.update(encoding.name);
154104
+ hash2.update(encoding.name);
154105
154105
  } else if ((0, _primitives.isRef)(encoding)) {
154106
- hash.update(encoding.toString());
154106
+ hash2.update(encoding.toString());
154107
154107
  } else if ((0, _primitives.isDict)(encoding)) {
154108
154108
  var keys = encoding.getKeys();
154109
154109
  for (var i = 0, ii = keys.length; i < ii; i++) {
154110
154110
  var entry = encoding.getRaw(keys[i]);
154111
154111
  if ((0, _primitives.isName)(entry)) {
154112
- hash.update(entry.name);
154112
+ hash2.update(entry.name);
154113
154113
  } else if ((0, _primitives.isRef)(entry)) {
154114
- hash.update(entry.toString());
154114
+ hash2.update(entry.toString());
154115
154115
  } else if ((0, _util.isArray)(entry)) {
154116
154116
  var diffLength = entry.length, diffBuf = new Array(diffLength);
154117
154117
  for (var j = 0; j < diffLength; j++) {
@@ -154122,7 +154122,7 @@ var require_pdf_worker3 = __commonJS({
154122
154122
  diffBuf[j] = diffEntry.toString();
154123
154123
  }
154124
154124
  }
154125
- hash.update(diffBuf.join());
154125
+ hash2.update(diffBuf.join());
154126
154126
  }
154127
154127
  }
154128
154128
  }
@@ -154130,14 +154130,14 @@ var require_pdf_worker3 = __commonJS({
154130
154130
  if ((0, _primitives.isStream)(toUnicode)) {
154131
154131
  var stream = toUnicode.str || toUnicode;
154132
154132
  uint8array = stream.buffer ? new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) : new Uint8Array(stream.bytes.buffer, stream.start, stream.end - stream.start);
154133
- hash.update(uint8array);
154133
+ hash2.update(uint8array);
154134
154134
  } else if ((0, _primitives.isName)(toUnicode)) {
154135
- hash.update(toUnicode.name);
154135
+ hash2.update(toUnicode.name);
154136
154136
  }
154137
154137
  var widths = dict.get("Widths") || baseDict.get("Widths");
154138
154138
  if (widths) {
154139
154139
  uint8array = new Uint8Array(new Uint32Array(widths).buffer);
154140
- hash.update(uint8array);
154140
+ hash2.update(uint8array);
154141
154141
  }
154142
154142
  }
154143
154143
  return {
@@ -154146,7 +154146,7 @@ var require_pdf_worker3 = __commonJS({
154146
154146
  baseDict,
154147
154147
  composite,
154148
154148
  type: type.name,
154149
- hash: hash ? hash.hexdigest() : ""
154149
+ hash: hash2 ? hash2.hexdigest() : ""
154150
154150
  };
154151
154151
  },
154152
154152
  translateFont: function PartialEvaluator_translateFont(preEvaluatedFont) {
@@ -164965,18 +164965,18 @@ var require_pdf_worker3 = __commonJS({
164965
164965
  return (0, _util.shadow)(this, "documentInfo", docInfo);
164966
164966
  },
164967
164967
  get fingerprint() {
164968
- var xref = this.xref, hash, fileID = "";
164968
+ var xref = this.xref, hash2, fileID = "";
164969
164969
  var idArray = xref.trailer.get("ID");
164970
164970
  if (idArray && (0, _util.isArray)(idArray) && idArray[0] && (0, _util.isString)(idArray[0]) && idArray[0] !== EMPTY_FINGERPRINT) {
164971
- hash = (0, _util.stringToBytes)(idArray[0]);
164971
+ hash2 = (0, _util.stringToBytes)(idArray[0]);
164972
164972
  } else {
164973
164973
  if (this.stream.ensureRange) {
164974
164974
  this.stream.ensureRange(0, Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
164975
164975
  }
164976
- hash = (0, _crypto.calculateMD5)(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
164976
+ hash2 = (0, _crypto.calculateMD5)(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
164977
164977
  }
164978
- for (var i = 0, n2 = hash.length; i < n2; i++) {
164979
- var hex = hash[i].toString(16);
164978
+ for (var i = 0, n2 = hash2.length; i < n2; i++) {
164979
+ var hex = hash2[i].toString(16);
164980
164980
  fileID += hex.length === 1 ? "0" + hex : hex;
164981
164981
  }
164982
164982
  return (0, _util.shadow)(this, "fingerprint", fileID);
@@ -199053,18 +199053,18 @@ var require_pdf_worker4 = __commonJS({
199053
199053
  return (0, _util.shadow)(this, "documentInfo", docInfo);
199054
199054
  },
199055
199055
  get fingerprint() {
199056
- var xref = this.xref, hash, fileID = "";
199056
+ var xref = this.xref, hash2, fileID = "";
199057
199057
  var idArray = xref.trailer.get("ID");
199058
199058
  if (Array.isArray(idArray) && idArray[0] && (0, _util.isString)(idArray[0]) && idArray[0] !== EMPTY_FINGERPRINT) {
199059
- hash = (0, _util.stringToBytes)(idArray[0]);
199059
+ hash2 = (0, _util.stringToBytes)(idArray[0]);
199060
199060
  } else {
199061
199061
  if (this.stream.ensureRange) {
199062
199062
  this.stream.ensureRange(0, Math.min(FINGERPRINT_FIRST_BYTES, this.stream.end));
199063
199063
  }
199064
- hash = (0, _crypto.calculateMD5)(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
199064
+ hash2 = (0, _crypto.calculateMD5)(this.stream.bytes.subarray(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
199065
199065
  }
199066
- for (var i = 0, n2 = hash.length; i < n2; i++) {
199067
- var hex = hash[i].toString(16);
199066
+ for (var i = 0, n2 = hash2.length; i < n2; i++) {
199067
+ var hex = hash2[i].toString(16);
199068
199068
  fileID += hex.length === 1 ? "0" + hex : hex;
199069
199069
  }
199070
199070
  return (0, _util.shadow)(this, "fingerprint", fileID);
@@ -208558,7 +208558,7 @@ var require_pdf_worker4 = __commonJS({
208558
208558
  var calculateMD5 = (function calculateMD5Closure() {
208559
208559
  var r = new Uint8Array([7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]);
208560
208560
  var k = new Int32Array([-680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426, -1473231341, -45705983, 1770035416, -1958414417, -42063, -1990404162, 1804603682, -40341101, -1502002290, 1236535329, -165796510, -1069501632, 643717713, -373897302, -701558691, 38016083, -660478335, -405537848, 568446438, -1019803690, -187363961, 1163531501, -1444681467, -51403784, 1735328473, -1926607734, -378558, -2022574463, 1839030562, -35309556, -1530992060, 1272893353, -155497632, -1094730640, 681279174, -358537222, -722521979, 76029189, -640364487, -421815835, 530742520, -995338651, -198630844, 1126891415, -1416354905, -57434055, 1700485571, -1894986606, -1051523, -2054922799, 1873313359, -30611744, -1560198380, 1309151649, -145523070, -1120210379, 718787259, -343485551]);
208561
- function hash(data, offset, length) {
208561
+ function hash2(data, offset, length) {
208562
208562
  var h0 = 1732584193, h1 = -271733879, h2 = -1732584194, h3 = 271733878;
208563
208563
  var paddedLength = length + 72 & ~63;
208564
208564
  var padded = new Uint8Array(paddedLength);
@@ -208612,7 +208612,7 @@ var require_pdf_worker4 = __commonJS({
208612
208612
  }
208613
208613
  return new Uint8Array([h0 & 255, h0 >> 8 & 255, h0 >> 16 & 255, h0 >>> 24 & 255, h1 & 255, h1 >> 8 & 255, h1 >> 16 & 255, h1 >>> 24 & 255, h2 & 255, h2 >> 8 & 255, h2 >> 16 & 255, h2 >>> 24 & 255, h3 & 255, h3 >> 8 & 255, h3 >> 16 & 255, h3 >>> 24 & 255]);
208614
208614
  }
208615
- return hash;
208615
+ return hash2;
208616
208616
  })();
208617
208617
  var Word64 = (function Word64Closure() {
208618
208618
  function Word642(highInteger, lowInteger) {
@@ -208716,7 +208716,7 @@ var require_pdf_worker4 = __commonJS({
208716
208716
  return rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10;
208717
208717
  }
208718
208718
  var k = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298];
208719
- function hash(data, offset, length) {
208719
+ function hash2(data, offset, length) {
208720
208720
  var h0 = 1779033703, h1 = 3144134277, h2 = 1013904242, h3 = 2773480762, h4 = 1359893119, h5 = 2600822924, h6 = 528734635, h7 = 1541459225;
208721
208721
  var paddedLength = Math.ceil((length + 9) / 64) * 64;
208722
208722
  var padded = new Uint8Array(paddedLength);
@@ -208770,7 +208770,7 @@ var require_pdf_worker4 = __commonJS({
208770
208770
  }
208771
208771
  return new Uint8Array([h0 >> 24 & 255, h0 >> 16 & 255, h0 >> 8 & 255, h0 & 255, h1 >> 24 & 255, h1 >> 16 & 255, h1 >> 8 & 255, h1 & 255, h2 >> 24 & 255, h2 >> 16 & 255, h2 >> 8 & 255, h2 & 255, h3 >> 24 & 255, h3 >> 16 & 255, h3 >> 8 & 255, h3 & 255, h4 >> 24 & 255, h4 >> 16 & 255, h4 >> 8 & 255, h4 & 255, h5 >> 24 & 255, h5 >> 16 & 255, h5 >> 8 & 255, h5 & 255, h6 >> 24 & 255, h6 >> 16 & 255, h6 >> 8 & 255, h6 & 255, h7 >> 24 & 255, h7 >> 16 & 255, h7 >> 8 & 255, h7 & 255]);
208772
208772
  }
208773
- return hash;
208773
+ return hash2;
208774
208774
  })();
208775
208775
  var calculateSHA512 = (function calculateSHA512Closure() {
208776
208776
  function ch(result, x, y, z, tmp) {
@@ -208832,7 +208832,7 @@ var require_pdf_worker4 = __commonJS({
208832
208832
  result.xor(tmp);
208833
208833
  }
208834
208834
  var k = [new Word64(1116352408, 3609767458), new Word64(1899447441, 602891725), new Word64(3049323471, 3964484399), new Word64(3921009573, 2173295548), new Word64(961987163, 4081628472), new Word64(1508970993, 3053834265), new Word64(2453635748, 2937671579), new Word64(2870763221, 3664609560), new Word64(3624381080, 2734883394), new Word64(310598401, 1164996542), new Word64(607225278, 1323610764), new Word64(1426881987, 3590304994), new Word64(1925078388, 4068182383), new Word64(2162078206, 991336113), new Word64(2614888103, 633803317), new Word64(3248222580, 3479774868), new Word64(3835390401, 2666613458), new Word64(4022224774, 944711139), new Word64(264347078, 2341262773), new Word64(604807628, 2007800933), new Word64(770255983, 1495990901), new Word64(1249150122, 1856431235), new Word64(1555081692, 3175218132), new Word64(1996064986, 2198950837), new Word64(2554220882, 3999719339), new Word64(2821834349, 766784016), new Word64(2952996808, 2566594879), new Word64(3210313671, 3203337956), new Word64(3336571891, 1034457026), new Word64(3584528711, 2466948901), new Word64(113926993, 3758326383), new Word64(338241895, 168717936), new Word64(666307205, 1188179964), new Word64(773529912, 1546045734), new Word64(1294757372, 1522805485), new Word64(1396182291, 2643833823), new Word64(1695183700, 2343527390), new Word64(1986661051, 1014477480), new Word64(2177026350, 1206759142), new Word64(2456956037, 344077627), new Word64(2730485921, 1290863460), new Word64(2820302411, 3158454273), new Word64(3259730800, 3505952657), new Word64(3345764771, 106217008), new Word64(3516065817, 3606008344), new Word64(3600352804, 1432725776), new Word64(4094571909, 1467031594), new Word64(275423344, 851169720), new Word64(430227734, 3100823752), new Word64(506948616, 1363258195), new Word64(659060556, 3750685593), new Word64(883997877, 3785050280), new Word64(958139571, 3318307427), new Word64(1322822218, 3812723403), new Word64(1537002063, 2003034995), new Word64(1747873779, 3602036899), new Word64(1955562222, 1575990012), new Word64(2024104815, 1125592928), new Word64(2227730452, 2716904306), new Word64(2361852424, 442776044), new Word64(2428436474, 593698344), new Word64(2756734187, 3733110249), new Word64(3204031479, 2999351573), new Word64(3329325298, 3815920427), new Word64(3391569614, 3928383900), new Word64(3515267271, 566280711), new Word64(3940187606, 3454069534), new Word64(4118630271, 4000239992), new Word64(116418474, 1914138554), new Word64(174292421, 2731055270), new Word64(289380356, 3203993006), new Word64(460393269, 320620315), new Word64(685471733, 587496836), new Word64(852142971, 1086792851), new Word64(1017036298, 365543100), new Word64(1126000580, 2618297676), new Word64(1288033470, 3409855158), new Word64(1501505948, 4234509866), new Word64(1607167915, 987167468), new Word64(1816402316, 1246189591)];
208835
- function hash(data, offset, length, mode384) {
208835
+ function hash2(data, offset, length, mode384) {
208836
208836
  mode384 = !!mode384;
208837
208837
  var h0, h1, h2, h3, h4, h5, h6, h7;
208838
208838
  if (!mode384) {
@@ -208967,13 +208967,13 @@ var require_pdf_worker4 = __commonJS({
208967
208967
  }
208968
208968
  return result;
208969
208969
  }
208970
- return hash;
208970
+ return hash2;
208971
208971
  })();
208972
208972
  var calculateSHA384 = /* @__PURE__ */ (function calculateSHA384Closure() {
208973
- function hash(data, offset, length) {
208973
+ function hash2(data, offset, length) {
208974
208974
  return calculateSHA512(data, offset, length, true);
208975
208975
  }
208976
- return hash;
208976
+ return hash2;
208977
208977
  })();
208978
208978
  var NullCipher = (function NullCipherClosure() {
208979
208979
  function NullCipher2() {
@@ -209578,14 +209578,14 @@ var require_pdf_worker4 = __commonJS({
209578
209578
  hashData[i++] = 255;
209579
209579
  hashData[i++] = 255;
209580
209580
  }
209581
- var hash = calculateMD5(hashData, 0, i);
209581
+ var hash2 = calculateMD5(hashData, 0, i);
209582
209582
  var keyLengthInBytes = keyLength >> 3;
209583
209583
  if (revision >= 3) {
209584
209584
  for (j = 0; j < 50; ++j) {
209585
- hash = calculateMD5(hash, 0, keyLengthInBytes);
209585
+ hash2 = calculateMD5(hash2, 0, keyLengthInBytes);
209586
209586
  }
209587
209587
  }
209588
- var encryptionKey = hash.subarray(0, keyLengthInBytes);
209588
+ var encryptionKey = hash2.subarray(0, keyLengthInBytes);
209589
209589
  var cipher, checkData;
209590
209590
  if (revision >= 3) {
209591
209591
  for (i = 0; i < 32; ++i) {
@@ -209631,11 +209631,11 @@ var require_pdf_worker4 = __commonJS({
209631
209631
  while (i < 32) {
209632
209632
  hashData[i++] = defaultPasswordBytes[j++];
209633
209633
  }
209634
- var hash = calculateMD5(hashData, 0, i);
209634
+ var hash2 = calculateMD5(hashData, 0, i);
209635
209635
  var keyLengthInBytes = keyLength >> 3;
209636
209636
  if (revision >= 3) {
209637
209637
  for (j = 0; j < 50; ++j) {
209638
- hash = calculateMD5(hash, 0, hash.length);
209638
+ hash2 = calculateMD5(hash2, 0, hash2.length);
209639
209639
  }
209640
209640
  }
209641
209641
  var cipher, userPassword;
@@ -209644,13 +209644,13 @@ var require_pdf_worker4 = __commonJS({
209644
209644
  var derivedKey = new Uint8Array(keyLengthInBytes), k;
209645
209645
  for (j = 19; j >= 0; j--) {
209646
209646
  for (k = 0; k < keyLengthInBytes; ++k) {
209647
- derivedKey[k] = hash[k] ^ j;
209647
+ derivedKey[k] = hash2[k] ^ j;
209648
209648
  }
209649
209649
  cipher = new ARCFourCipher(derivedKey);
209650
209650
  userPassword = cipher.encryptBlock(userPassword);
209651
209651
  }
209652
209652
  } else {
209653
- cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));
209653
+ cipher = new ARCFourCipher(hash2.subarray(0, keyLengthInBytes));
209654
209654
  userPassword = cipher.encryptBlock(ownerPassword);
209655
209655
  }
209656
209656
  return userPassword;
@@ -209756,8 +209756,8 @@ var require_pdf_worker4 = __commonJS({
209756
209756
  key[i++] = 108;
209757
209757
  key[i++] = 84;
209758
209758
  }
209759
- var hash = calculateMD5(key, 0, i);
209760
- return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));
209759
+ var hash2 = calculateMD5(key, 0, i);
209760
+ return hash2.subarray(0, Math.min(encryptionKey.length + 5, 16));
209761
209761
  }
209762
209762
  function buildCipherConstructor(cf, name, num2, gen, key) {
209763
209763
  if (!(0, _primitives.isName)(name)) {
@@ -212732,20 +212732,20 @@ var require_pdf_worker4 = __commonJS({
212732
212732
  descriptor.fontAliases = /* @__PURE__ */ Object.create(null);
212733
212733
  }
212734
212734
  var fontAliases = descriptor.fontAliases;
212735
- var hash = preEvaluatedFont.hash;
212736
- if (fontAliases[hash]) {
212737
- var aliasFontRef = fontAliases[hash].aliasRef;
212735
+ var hash2 = preEvaluatedFont.hash;
212736
+ if (fontAliases[hash2]) {
212737
+ var aliasFontRef = fontAliases[hash2].aliasRef;
212738
212738
  if (fontRefIsRef && aliasFontRef && this.fontCache.has(aliasFontRef)) {
212739
212739
  this.fontCache.putAlias(fontRef, aliasFontRef);
212740
212740
  return this.fontCache.get(fontRef);
212741
212741
  }
212742
212742
  } else {
212743
- fontAliases[hash] = { fontID: _fonts.Font.getFontID() };
212743
+ fontAliases[hash2] = { fontID: _fonts.Font.getFontID() };
212744
212744
  }
212745
212745
  if (fontRefIsRef) {
212746
- fontAliases[hash].aliasRef = fontRef;
212746
+ fontAliases[hash2].aliasRef = fontRef;
212747
212747
  }
212748
- fontID = fontAliases[hash].fontID;
212748
+ fontID = fontAliases[hash2].fontID;
212749
212749
  }
212750
212750
  if (fontRefIsRef) {
212751
212751
  this.fontCache.put(fontRef, fontCapability.promise);
@@ -213973,20 +213973,20 @@ var require_pdf_worker4 = __commonJS({
213973
213973
  }
213974
213974
  var descriptor = dict.get("FontDescriptor");
213975
213975
  if (descriptor) {
213976
- var hash = new _murmurhash.MurmurHash3_64();
213976
+ var hash2 = new _murmurhash.MurmurHash3_64();
213977
213977
  var encoding = baseDict.getRaw("Encoding");
213978
213978
  if ((0, _primitives.isName)(encoding)) {
213979
- hash.update(encoding.name);
213979
+ hash2.update(encoding.name);
213980
213980
  } else if ((0, _primitives.isRef)(encoding)) {
213981
- hash.update(encoding.toString());
213981
+ hash2.update(encoding.toString());
213982
213982
  } else if ((0, _primitives.isDict)(encoding)) {
213983
213983
  var keys = encoding.getKeys();
213984
213984
  for (var i = 0, ii = keys.length; i < ii; i++) {
213985
213985
  var entry = encoding.getRaw(keys[i]);
213986
213986
  if ((0, _primitives.isName)(entry)) {
213987
- hash.update(entry.name);
213987
+ hash2.update(entry.name);
213988
213988
  } else if ((0, _primitives.isRef)(entry)) {
213989
- hash.update(entry.toString());
213989
+ hash2.update(entry.toString());
213990
213990
  } else if (Array.isArray(entry)) {
213991
213991
  var diffLength = entry.length, diffBuf = new Array(diffLength);
213992
213992
  for (var j = 0; j < diffLength; j++) {
@@ -213997,7 +213997,7 @@ var require_pdf_worker4 = __commonJS({
213997
213997
  diffBuf[j] = diffEntry.toString();
213998
213998
  }
213999
213999
  }
214000
- hash.update(diffBuf.join());
214000
+ hash2.update(diffBuf.join());
214001
214001
  }
214002
214002
  }
214003
214003
  }
@@ -214005,14 +214005,14 @@ var require_pdf_worker4 = __commonJS({
214005
214005
  if ((0, _primitives.isStream)(toUnicode)) {
214006
214006
  var stream = toUnicode.str || toUnicode;
214007
214007
  uint8array = stream.buffer ? new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) : new Uint8Array(stream.bytes.buffer, stream.start, stream.end - stream.start);
214008
- hash.update(uint8array);
214008
+ hash2.update(uint8array);
214009
214009
  } else if ((0, _primitives.isName)(toUnicode)) {
214010
- hash.update(toUnicode.name);
214010
+ hash2.update(toUnicode.name);
214011
214011
  }
214012
214012
  var widths = dict.get("Widths") || baseDict.get("Widths");
214013
214013
  if (widths) {
214014
214014
  uint8array = new Uint8Array(new Uint32Array(widths).buffer);
214015
- hash.update(uint8array);
214015
+ hash2.update(uint8array);
214016
214016
  }
214017
214017
  }
214018
214018
  return {
@@ -214021,7 +214021,7 @@ var require_pdf_worker4 = __commonJS({
214021
214021
  baseDict,
214022
214022
  composite,
214023
214023
  type: type.name,
214024
- hash: hash ? hash.hexdigest() : ""
214024
+ hash: hash2 ? hash2.hexdigest() : ""
214025
214025
  };
214026
214026
  },
214027
214027
  translateFont: function PartialEvaluator_translateFont(preEvaluatedFont) {
@@ -257160,10 +257160,10 @@ var require_util2 = __commonJS({
257160
257160
  var codegen_1 = require_codegen();
257161
257161
  var code_1 = require_code();
257162
257162
  function toHash(arr3) {
257163
- const hash = {};
257163
+ const hash2 = {};
257164
257164
  for (const item of arr3)
257165
- hash[item] = true;
257166
- return hash;
257165
+ hash2[item] = true;
257166
+ return hash2;
257167
257167
  }
257168
257168
  exports.toHash = toHash;
257169
257169
  function alwaysValidSchema(it, schema) {
@@ -258334,8 +258334,8 @@ var require_resolve = __commonJS({
258334
258334
  }
258335
258335
  return count;
258336
258336
  }
258337
- function getFullPath(resolver, id = "", normalize2) {
258338
- if (normalize2 !== false)
258337
+ function getFullPath(resolver, id = "", normalize3) {
258338
+ if (normalize3 !== false)
258339
258339
  id = normalizeId(id);
258340
258340
  const p = resolver.parse(id);
258341
258341
  return _getFullPath(resolver, p);
@@ -259675,7 +259675,7 @@ var require_fast_uri = __commonJS({
259675
259675
  "use strict";
259676
259676
  var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils2();
259677
259677
  var { SCHEMES, getSchemeHandler } = require_schemes();
259678
- function normalize2(uri2, options) {
259678
+ function normalize3(uri2, options) {
259679
259679
  if (typeof uri2 === "string") {
259680
259680
  uri2 = /** @type {T} */
259681
259681
  serialize2(parse8(uri2, options), options);
@@ -259911,7 +259911,7 @@ var require_fast_uri = __commonJS({
259911
259911
  }
259912
259912
  var fastUri = {
259913
259913
  SCHEMES,
259914
- normalize: normalize2,
259914
+ normalize: normalize3,
259915
259915
  resolve: resolve2,
259916
259916
  resolveComponent,
259917
259917
  equal,
@@ -263806,10 +263806,10 @@ var require_util3 = __commonJS({
263806
263806
  var codegen_1 = require_codegen2();
263807
263807
  var code_1 = require_code3();
263808
263808
  function toHash(arr3) {
263809
- const hash = {};
263809
+ const hash2 = {};
263810
263810
  for (const item of arr3)
263811
- hash[item] = true;
263812
- return hash;
263811
+ hash2[item] = true;
263812
+ return hash2;
263813
263813
  }
263814
263814
  exports.toHash = toHash;
263815
263815
  function alwaysValidSchema(it, schema) {
@@ -264945,8 +264945,8 @@ var require_resolve2 = __commonJS({
264945
264945
  }
264946
264946
  return count;
264947
264947
  }
264948
- function getFullPath(resolver, id = "", normalize2) {
264949
- if (normalize2 !== false)
264948
+ function getFullPath(resolver, id = "", normalize3) {
264949
+ if (normalize3 !== false)
264950
264950
  id = normalizeId(id);
264951
264951
  const p = resolver.parse(id);
264952
264952
  return _getFullPath(resolver, p);
@@ -269210,12 +269210,12 @@ var require_common2 = __commonJS({
269210
269210
  createDebug.skips = [];
269211
269211
  createDebug.formatters = {};
269212
269212
  function selectColor(namespace) {
269213
- let hash = 0;
269213
+ let hash2 = 0;
269214
269214
  for (let i = 0; i < namespace.length; i++) {
269215
- hash = (hash << 5) - hash + namespace.charCodeAt(i);
269216
- hash |= 0;
269215
+ hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i);
269216
+ hash2 |= 0;
269217
269217
  }
269218
- return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
269218
+ return createDebug.colors[Math.abs(hash2) % createDebug.colors.length];
269219
269219
  }
269220
269220
  createDebug.selectColor = selectColor;
269221
269221
  function createDebug(namespace) {
@@ -280726,7 +280726,13 @@ var LEGACY_ALGORITHMS = {
280726
280726
  "ecdh-sha2-nistp384",
280727
280727
  "ecdh-sha2-nistp521",
280728
280728
  "diffie-hellman-group14-sha256",
280729
+ "diffie-hellman-group18-sha512",
280730
+ "diffie-hellman-group17-sha512",
280731
+ "diffie-hellman-group16-sha512",
280732
+ "diffie-hellman-group15-sha512",
280729
280733
  "diffie-hellman-group14-sha1",
280734
+ "diffie-hellman-group-exchange-sha256",
280735
+ "diffie-hellman-group-exchange-sha1",
280730
280736
  "diffie-hellman-group1-sha1"
280731
280737
  ],
280732
280738
  serverHostKey: [
@@ -280735,6 +280741,8 @@ var LEGACY_ALGORITHMS = {
280735
280741
  "ssh-rsa",
280736
280742
  "ssh-ed25519",
280737
280743
  "ecdsa-sha2-nistp256",
280744
+ "ecdsa-sha2-nistp384",
280745
+ "ecdsa-sha2-nistp521",
280738
280746
  "ssh-dss"
280739
280747
  ],
280740
280748
  cipher: [
@@ -280742,17 +280750,26 @@ var LEGACY_ALGORITHMS = {
280742
280750
  "aes192-ctr",
280743
280751
  "aes256-ctr",
280744
280752
  "aes128-gcm",
280753
+ "aes128-gcm@openssh.com",
280745
280754
  "aes256-gcm",
280755
+ "aes256-gcm@openssh.com",
280756
+ "chacha20-poly1305@openssh.com",
280746
280757
  "aes128-cbc",
280747
- "3des-cbc",
280748
280758
  "aes192-cbc",
280749
- "aes256-cbc"
280759
+ "aes256-cbc",
280760
+ "3des-cbc"
280750
280761
  ],
280751
280762
  hmac: [
280752
280763
  "hmac-sha2-256",
280753
280764
  "hmac-sha2-512",
280754
280765
  "hmac-sha1",
280766
+ "hmac-sha2-256-96",
280767
+ "hmac-sha2-512-96",
280755
280768
  "hmac-sha1-96",
280769
+ "hmac-sha2-256-etm@openssh.com",
280770
+ "hmac-sha2-512-etm@openssh.com",
280771
+ "hmac-sha1-etm@openssh.com",
280772
+ "hmac-ripemd160",
280756
280773
  "hmac-md5",
280757
280774
  "hmac-md5-96"
280758
280775
  ]
@@ -280761,6 +280778,8 @@ var CISCO_ALGORITHMS = {
280761
280778
  kex: [
280762
280779
  "diffie-hellman-group14-sha1",
280763
280780
  "diffie-hellman-group14-sha256",
280781
+ "diffie-hellman-group-exchange-sha256",
280782
+ "diffie-hellman-group-exchange-sha1",
280764
280783
  "diffie-hellman-group1-sha1",
280765
280784
  "curve25519-sha256",
280766
280785
  "curve25519-sha256@libssh.org",
@@ -280778,7 +280797,20 @@ var CISCO_ALGORITHMS = {
280778
280797
  "aes192-ctr",
280779
280798
  "aes256-ctr"
280780
280799
  ],
280781
- hmac: ["hmac-sha1", "hmac-sha1-96", "hmac-sha2-256", "hmac-sha2-512", "hmac-md5"]
280800
+ hmac: [
280801
+ "hmac-sha1",
280802
+ "hmac-sha1-96",
280803
+ "hmac-sha2-256",
280804
+ "hmac-sha2-512",
280805
+ "hmac-sha2-256-96",
280806
+ "hmac-sha2-512-96",
280807
+ "hmac-sha1-etm@openssh.com",
280808
+ "hmac-sha2-256-etm@openssh.com",
280809
+ "hmac-sha2-512-etm@openssh.com",
280810
+ "hmac-ripemd160",
280811
+ "hmac-md5",
280812
+ "hmac-md5-96"
280813
+ ]
280782
280814
  };
280783
280815
  function resolveSshAlgorithms(preset) {
280784
280816
  if (preset === "legacy") return LEGACY_ALGORITHMS;
@@ -359565,16 +359597,16 @@ var PassChatTempExportService = class {
359565
359597
  return resolvedPath;
359566
359598
  }
359567
359599
  buildFilePath(input) {
359568
- const hash = this.hashText(
359600
+ const hash2 = this.hashText(
359569
359601
  `${input.sessionId}
359570
359602
  ${input.title}
359571
359603
  ${input.markdown}`
359572
359604
  ).slice(0, 12);
359573
359605
  if (!this.groupBySession) {
359574
- return path9.join(this.baseDir, `pass-chat_${hash}.md`);
359606
+ return path9.join(this.baseDir, `pass-chat_${hash2}.md`);
359575
359607
  }
359576
359608
  const sessionHash = this.hashText(input.sessionId).slice(0, 12);
359577
- return path9.join(this.baseDir, `pass-chat_${sessionHash}_${hash}.md`);
359609
+ return path9.join(this.baseDir, `pass-chat_${sessionHash}_${hash2}.md`);
359578
359610
  }
359579
359611
  hashText(input) {
359580
359612
  return crypto14.createHash("sha256").update(input).digest("hex");
@@ -377255,6 +377287,1836 @@ function createTriggerRuntime(deps) {
377255
377287
  return Object.assign(engine, { busReady });
377256
377288
  }
377257
377289
 
377290
+ // ../../packages/backend/src/services/sre/metricsLedger.ts
377291
+ var DEFAULT_LIMIT = 1e4;
377292
+ function flattenSnapshot(host, snap) {
377293
+ const p = { host, at: snap.timestamp };
377294
+ if (snap.cpu && typeof snap.cpu.usagePercent === "number") p.cpuUsagePercent = snap.cpu.usagePercent;
377295
+ if (snap.memory && typeof snap.memory.usagePercent === "number") p.memoryUsagePercent = snap.memory.usagePercent;
377296
+ if (Array.isArray(snap.loadAverage) && typeof snap.loadAverage[0] === "number") p.loadAvg1 = snap.loadAverage[0];
377297
+ if (Array.isArray(snap.disks) && snap.disks.length > 0) {
377298
+ p.diskUsagePercentMax = Math.max(...snap.disks.map((d) => d.usagePercent ?? 0));
377299
+ }
377300
+ if (Array.isArray(snap.network) && snap.network.length > 0) {
377301
+ p.netRxBytesPerSec = snap.network.reduce((s, n2) => s + (n2.rxBytesPerSec ?? 0), 0);
377302
+ p.netTxBytesPerSec = snap.network.reduce((s, n2) => s + (n2.txBytesPerSec ?? 0), 0);
377303
+ }
377304
+ if (Array.isArray(snap.gpus) && snap.gpus.length > 0) {
377305
+ p.gpuUsagePercent = Math.max(...snap.gpus.map((g) => g.utilizationPercent ?? 0));
377306
+ }
377307
+ if (Array.isArray(snap.processes)) p.processCount = snap.processes.length;
377308
+ if (typeof snap.uptimeSeconds === "number") p.uptimeSeconds = snap.uptimeSeconds;
377309
+ return p;
377310
+ }
377311
+ var MetricsLedger = class {
377312
+ points = /* @__PURE__ */ new Map();
377313
+ perHostLimit;
377314
+ constructor(opts = {}) {
377315
+ this.perHostLimit = opts.perHostLimit ?? DEFAULT_LIMIT;
377316
+ }
377317
+ /** Ingest a resource snapshot for a host. Returns the stored point. */
377318
+ record(host, snap) {
377319
+ const p = flattenSnapshot(host, snap);
377320
+ this.recordPoint(p);
377321
+ return p;
377322
+ }
377323
+ /** Ingest a pre-flattened point. */
377324
+ recordPoint(p) {
377325
+ let arr3 = this.points.get(p.host);
377326
+ if (!arr3) {
377327
+ arr3 = [];
377328
+ this.points.set(p.host, arr3);
377329
+ }
377330
+ arr3.push(p);
377331
+ if (arr3.length > this.perHostLimit) arr3.splice(0, arr3.length - this.perHostLimit);
377332
+ }
377333
+ /** All hosts with any recorded points. */
377334
+ hosts() {
377335
+ return Array.from(this.points.keys());
377336
+ }
377337
+ /** Points for a host, optionally filtered to [sinceMs, untilMs]. */
377338
+ series(host, opts = {}) {
377339
+ const arr3 = this.points.get(host) ?? [];
377340
+ return arr3.filter(
377341
+ (p) => (opts.sinceMs === void 0 || p.at >= opts.sinceMs) && (opts.untilMs === void 0 || p.at <= opts.untilMs)
377342
+ );
377343
+ }
377344
+ /** A single-metric series for a host. */
377345
+ metricSeries(host, metric, opts = {}) {
377346
+ const pts = this.series(host, opts).map((p) => ({ at: p.at, value: p[metric] })).filter((x) => typeof x.value === "number");
377347
+ return { host, metric, points: pts };
377348
+ }
377349
+ /** Latest point for a host (or undefined). */
377350
+ latest(host) {
377351
+ const arr3 = this.points.get(host);
377352
+ return arr3 && arr3.length > 0 ? arr3[arr3.length - 1] : void 0;
377353
+ }
377354
+ /** Simple linear-trend slope (units/day) for a metric over a window, using
377355
+ * least-squares over the series. Positive = rising. */
377356
+ trendSlopePerDay(host, metric, opts = {}) {
377357
+ const s = this.metricSeries(host, metric, opts);
377358
+ if (s.points.length < 3) return void 0;
377359
+ const t0 = s.points[0].at;
377360
+ const xs = s.points.map((p) => (p.at - t0) / 864e5);
377361
+ const ys = s.points.map((p) => p.value);
377362
+ const n2 = xs.length;
377363
+ const meanX = xs.reduce((a, b) => a + b, 0) / n2;
377364
+ const meanY = ys.reduce((a, b) => a + b, 0) / n2;
377365
+ let num2 = 0, den = 0;
377366
+ for (let i = 0; i < n2; i += 1) {
377367
+ num2 += (xs[i] - meanX) * (ys[i] - meanY);
377368
+ den += (xs[i] - meanX) * (xs[i] - meanX);
377369
+ }
377370
+ if (den === 0) return void 0;
377371
+ return num2 / den;
377372
+ }
377373
+ /** Days until a metric crosses a threshold given the current value + slope.
377374
+ * Returns undefined when not computable (no slope, flat, or moving away). */
377375
+ daysUntilThreshold(host, metric, threshold) {
377376
+ const latest = this.latest(host);
377377
+ if (!latest) return void 0;
377378
+ const cur = latest[metric];
377379
+ if (typeof cur !== "number") return void 0;
377380
+ const slope = this.trendSlopePerDay(host, metric);
377381
+ if (slope === void 0 || slope <= 0) return void 0;
377382
+ const gap = threshold - cur;
377383
+ if (gap <= 0) return 0;
377384
+ return gap / slope;
377385
+ }
377386
+ /** Remove all points (test helper / reset). */
377387
+ clear() {
377388
+ this.points.clear();
377389
+ }
377390
+ };
377391
+
377392
+ // ../../packages/backend/src/services/sre/goldenSignals.ts
377393
+ var DEFAULT_WINDOW = 36e5;
377394
+ function percentile(sorted, p) {
377395
+ if (sorted.length === 0) return void 0;
377396
+ const idx = Math.min(sorted.length - 1, Math.floor(p / 100 * sorted.length));
377397
+ return sorted[idx];
377398
+ }
377399
+ var GoldenSignals = class {
377400
+ constructor(deps) {
377401
+ this.deps = deps;
377402
+ this.now = deps.now ?? (() => Date.now());
377403
+ this.windowMs = deps.windowMs ?? DEFAULT_WINDOW;
377404
+ }
377405
+ now;
377406
+ windowMs;
377407
+ /** Build the golden-signal report for one host. */
377408
+ report(host, opts = {}) {
377409
+ const latest = this.deps.ledger.latest(host);
377410
+ const now = this.now();
377411
+ const since = now - this.windowMs;
377412
+ const r = { host, at: now };
377413
+ if (latest) {
377414
+ r.cpuPercent = latest.cpuUsagePercent;
377415
+ r.memPercent = latest.memoryUsagePercent;
377416
+ r.diskPercentMax = latest.diskUsagePercentMax;
377417
+ r.netRxBps = latest.netRxBytesPerSec;
377418
+ r.netTxBps = latest.netTxBytesPerSec;
377419
+ }
377420
+ if (this.deps.latencyFor) {
377421
+ const samples = this.deps.latencyFor(host, since).map((s) => s.ms).sort((a, b) => a - b);
377422
+ if (samples.length > 0) {
377423
+ r.latencyP50Ms = percentile(samples, 50);
377424
+ r.latencyP95Ms = percentile(samples, 95);
377425
+ r.latencyP99Ms = percentile(samples, 99);
377426
+ }
377427
+ }
377428
+ if (this.deps.errorRateFor) {
377429
+ r.errorRate = this.deps.errorRateFor(host, since);
377430
+ }
377431
+ const diskThreshold = opts.diskFullThresholdPercent ?? 95;
377432
+ r.diskDaysToFull = this.deps.ledger.daysUntilThreshold(host, "diskUsagePercentMax", diskThreshold);
377433
+ r.cpuTrendPerDay = this.deps.ledger.trendSlopePerDay(host, "cpuUsagePercent");
377434
+ r.memTrendPerDay = this.deps.ledger.trendSlopePerDay(host, "memoryUsagePercent");
377435
+ return r;
377436
+ }
377437
+ /** Reports for every host in the ledger. */
377438
+ reportAll(opts = {}) {
377439
+ return this.deps.ledger.hosts().map((h) => this.report(h, opts));
377440
+ }
377441
+ /** Capacity forecast table: per host, current disk% and days-to-full. */
377442
+ capacityForecast(opts = {}) {
377443
+ const threshold = opts.diskFullThresholdPercent ?? 95;
377444
+ return this.deps.ledger.hosts().map((host) => {
377445
+ const latest = this.deps.ledger.latest(host);
377446
+ return {
377447
+ host,
377448
+ diskPercent: latest?.diskUsagePercentMax,
377449
+ daysToFull: this.deps.ledger.daysUntilThreshold(host, "diskUsagePercentMax", threshold)
377450
+ };
377451
+ });
377452
+ }
377453
+ };
377454
+
377455
+ // ../../packages/backend/src/services/sre/sloService.ts
377456
+ import { randomUUID as randomUUID10 } from "crypto";
377457
+ var DEFAULT_FAST_BURN = 2;
377458
+ var SloService = class {
377459
+ constructor(deps) {
377460
+ this.deps = deps;
377461
+ this.now = deps.now ?? (() => Date.now());
377462
+ }
377463
+ slos = /* @__PURE__ */ new Map();
377464
+ now;
377465
+ upsert(def) {
377466
+ const existing = def.id ? this.slos.get(def.id) : Array.from(this.slos.values()).find((s) => s.name === def.name);
377467
+ if (existing) {
377468
+ const merged = { ...existing, ...def, id: existing.id, createdAt: existing.createdAt };
377469
+ this.slos.set(existing.id, merged);
377470
+ return merged;
377471
+ }
377472
+ if (!(def.target > 0 && def.target < 1)) {
377473
+ throw new Error("SLO target must be a fraction between 0 and 1 (e.g. 0.999 for 99.9%)");
377474
+ }
377475
+ if (!(def.windowMs > 0)) {
377476
+ throw new Error("SLO windowMs must be positive");
377477
+ }
377478
+ const entry = {
377479
+ ...def,
377480
+ id: def.id ?? `slo-${randomUUID10().slice(0, 8)}`,
377481
+ createdAt: this.now()
377482
+ };
377483
+ this.slos.set(entry.id, entry);
377484
+ return entry;
377485
+ }
377486
+ remove(idOrName) {
377487
+ const needle = idOrName.trim().toLowerCase();
377488
+ const t = this.slos.get(idOrName) ?? Array.from(this.slos.values()).find((s) => s.name.trim().toLowerCase() === needle);
377489
+ return t ? this.slos.delete(t.id) : false;
377490
+ }
377491
+ list() {
377492
+ return Array.from(this.slos.values());
377493
+ }
377494
+ get(idOrName) {
377495
+ const needle = idOrName.trim().toLowerCase();
377496
+ return this.slos.get(idOrName) ?? Array.from(this.slos.values()).find((s) => s.name.trim().toLowerCase() === needle);
377497
+ }
377498
+ /** Evaluate one SLO against its source for the rolling window. */
377499
+ async evaluate(idOrName) {
377500
+ const slo = this.get(idOrName);
377501
+ if (!slo) throw new Error(`no SLO "${idOrName}"`);
377502
+ const now = this.now();
377503
+ const since = now - slo.windowMs;
377504
+ const { good, total } = await this.deps.source.count(slo.id, since, now);
377505
+ const allowedError = 1 - slo.target;
377506
+ let sli;
377507
+ let errorBudgetRemaining;
377508
+ let burnRate;
377509
+ if (total > 0) {
377510
+ sli = good / total;
377511
+ const actualError = 1 - sli;
377512
+ if (allowedError > 0) {
377513
+ burnRate = actualError / allowedError;
377514
+ errorBudgetRemaining = Math.max(0, 1 - burnRate);
377515
+ }
377516
+ }
377517
+ const threshold = slo.fastBurnThreshold ?? DEFAULT_FAST_BURN;
377518
+ return {
377519
+ sloId: slo.id,
377520
+ sli,
377521
+ total,
377522
+ good,
377523
+ errorBudgetRemaining,
377524
+ burnRate,
377525
+ fastBurning: burnRate !== void 0 && burnRate > threshold,
377526
+ at: now
377527
+ };
377528
+ }
377529
+ /** Evaluate all defined SLOs. */
377530
+ async evaluateAll() {
377531
+ const out = [];
377532
+ for (const slo of this.slos.values()) {
377533
+ out.push(await this.evaluate(slo.id));
377534
+ }
377535
+ return out;
377536
+ }
377537
+ /** Pure: days until the error budget is exhausted at the current burn rate. */
377538
+ daysToBudgetExhaustion(evaluation) {
377539
+ if (evaluation.burnRate === void 0 || evaluation.errorBudgetRemaining === void 0) return void 0;
377540
+ if (evaluation.burnRate <= 1) return void 0;
377541
+ const windowDays = 1;
377542
+ return evaluation.errorBudgetRemaining / evaluation.burnRate * windowDays;
377543
+ }
377544
+ };
377545
+
377546
+ // ../../packages/backend/src/services/sre/uptimeWatchdog.ts
377547
+ import { randomUUID as randomUUID11 } from "crypto";
377548
+ var UptimeWatchdog = class {
377549
+ constructor(deps) {
377550
+ this.deps = deps;
377551
+ this.now = deps.now ?? (() => Date.now());
377552
+ }
377553
+ targets = /* @__PURE__ */ new Map();
377554
+ status = /* @__PURE__ */ new Map();
377555
+ now;
377556
+ upsert(target) {
377557
+ const t = {
377558
+ ...target,
377559
+ id: target.id ?? `wt-${randomUUID11().slice(0, 8)}`,
377560
+ downAfter: target.downAfter ?? 3,
377561
+ intervalMs: target.intervalMs ?? 6e4
377562
+ };
377563
+ this.targets.set(t.id, t);
377564
+ if (!this.status.has(t.id)) {
377565
+ this.status.set(t.id, { target: t, state: "unknown", consecutiveFailures: 0 });
377566
+ }
377567
+ return t;
377568
+ }
377569
+ remove(id) {
377570
+ this.status.delete(id);
377571
+ return this.targets.delete(id);
377572
+ }
377573
+ list() {
377574
+ return Array.from(this.targets.values());
377575
+ }
377576
+ getStatus(id) {
377577
+ return this.status.get(id);
377578
+ }
377579
+ allStatus() {
377580
+ return Array.from(this.status.values());
377581
+ }
377582
+ /** Probe one target once and update its state (fires onTransition on change). */
377583
+ async probe(id) {
377584
+ const t = this.targets.get(id);
377585
+ if (!t) throw new Error(`no watchdog target "${id}"`);
377586
+ const st = this.status.get(id);
377587
+ const prev = st.state;
377588
+ const startedAt = this.now();
377589
+ let ok = false;
377590
+ let err;
377591
+ try {
377592
+ ok = await this.runProbe(t);
377593
+ } catch (e) {
377594
+ ok = false;
377595
+ err = e instanceof Error ? e.message : String(e);
377596
+ }
377597
+ const at = this.now();
377598
+ st.lastProbeAt = at;
377599
+ if (ok) {
377600
+ st.consecutiveFailures = 0;
377601
+ st.lastOkAt = at;
377602
+ st.lastLatencyMs = at - startedAt;
377603
+ st.lastError = void 0;
377604
+ st.state = "up";
377605
+ } else {
377606
+ st.consecutiveFailures += 1;
377607
+ st.lastError = err;
377608
+ const downAfter = t.downAfter ?? 3;
377609
+ st.state = st.consecutiveFailures >= downAfter ? "down" : "degraded";
377610
+ }
377611
+ if (prev !== st.state) {
377612
+ try {
377613
+ this.deps.onTransition?.(st, prev, st.state);
377614
+ } catch {
377615
+ }
377616
+ }
377617
+ return st;
377618
+ }
377619
+ /** Probe every target that is due (intervalMs elapsed since last probe). */
377620
+ async probeDue() {
377621
+ const out = [];
377622
+ for (const t of this.targets.values()) {
377623
+ const st = this.status.get(t.id);
377624
+ const last = st.lastProbeAt ?? 0;
377625
+ if (this.now() - last >= (t.intervalMs ?? 6e4)) {
377626
+ out.push(await this.probe(t.id));
377627
+ }
377628
+ }
377629
+ return out;
377630
+ }
377631
+ async runProbe(t) {
377632
+ switch (t.kind) {
377633
+ case "tcp": {
377634
+ if (!this.deps.probeTcp) throw new Error("no tcp prober configured");
377635
+ return this.deps.probeTcp(t.address, t.expect ?? 22);
377636
+ }
377637
+ case "ssh": {
377638
+ if (!this.deps.probeSsh) throw new Error("no ssh prober configured");
377639
+ return this.deps.probeSsh(t.address);
377640
+ }
377641
+ case "http": {
377642
+ if (!this.deps.probeHttp) throw new Error("no http prober configured");
377643
+ const code = await this.deps.probeHttp(t.address);
377644
+ const expect = t.expect ?? 200;
377645
+ return code === expect || expect === 200 && code >= 200 && code < 400;
377646
+ }
377647
+ case "command": {
377648
+ if (!this.deps.probeCommand) throw new Error("no command prober configured");
377649
+ return this.deps.probeCommand(t.address);
377650
+ }
377651
+ default:
377652
+ throw new Error(`unknown probe kind ${t.kind}`);
377653
+ }
377654
+ }
377655
+ };
377656
+
377657
+ // ../../packages/backend/src/services/sre/alertService.ts
377658
+ import { randomUUID as randomUUID12 } from "crypto";
377659
+ var SEV_ORDER = { info: 0, warning: 1, critical: 2 };
377660
+ var DEFAULT_DEDUPE_MS = 3e5;
377661
+ var DEFAULT_HISTORY = 200;
377662
+ var AlertService = class {
377663
+ constructor(deps = {}) {
377664
+ this.deps = deps;
377665
+ this.now = deps.now ?? (() => Date.now());
377666
+ this.dedupeMs = deps.dedupeMs ?? DEFAULT_DEDUPE_MS;
377667
+ this.historyLimit = deps.historyLimit ?? DEFAULT_HISTORY;
377668
+ }
377669
+ groups = /* @__PURE__ */ new Map();
377670
+ silences = /* @__PURE__ */ new Map();
377671
+ sentHistory = [];
377672
+ now;
377673
+ dedupeMs;
377674
+ historyLimit;
377675
+ log(line) {
377676
+ try {
377677
+ this.deps.onLog?.(line);
377678
+ } catch {
377679
+ }
377680
+ }
377681
+ /** Create a silence that suppresses matching alerts until `untilMs`. */
377682
+ silence(matcher, untilMs, opts = {}) {
377683
+ const s = { id: `sil-${randomUUID12().slice(0, 8)}`, matcher, until: untilMs, ...opts };
377684
+ this.silences.set(s.id, s);
377685
+ return s;
377686
+ }
377687
+ listSilences() {
377688
+ const now = this.now();
377689
+ return Array.from(this.silences.values()).filter((s) => s.until > now);
377690
+ }
377691
+ removeSilence(id) {
377692
+ return this.silences.delete(id);
377693
+ }
377694
+ isSilenced(alert) {
377695
+ const now = this.now();
377696
+ for (const s of this.silences.values()) {
377697
+ if (s.until <= now) continue;
377698
+ if (s.regex) {
377699
+ try {
377700
+ if (new RegExp(s.matcher).test(alert.fingerprint)) return true;
377701
+ } catch {
377702
+ }
377703
+ }
377704
+ if (alert.fingerprint.includes(s.matcher)) return true;
377705
+ }
377706
+ return false;
377707
+ }
377708
+ /** Fire an alert: group/dedupe it, then route the group to channels (unless
377709
+ * silenced or within the dedupe window). Returns the group + whether it was sent. */
377710
+ async fire(alert) {
377711
+ const fp = alert.fingerprint;
377712
+ let g = this.groups.get(fp);
377713
+ if (!g) {
377714
+ g = {
377715
+ fingerprint: fp,
377716
+ title: alert.title,
377717
+ severity: alert.severity,
377718
+ count: 0,
377719
+ firstAt: alert.at,
377720
+ lastAt: alert.at,
377721
+ lastAlert: alert,
377722
+ silenced: false
377723
+ };
377724
+ this.groups.set(fp, g);
377725
+ }
377726
+ g.count += 1;
377727
+ g.lastAt = alert.at;
377728
+ g.lastAlert = alert;
377729
+ g.severity = alert.severity;
377730
+ if (this.isSilenced(alert)) {
377731
+ g.silenced = true;
377732
+ this.log(`[alert] "${alert.title}" silenced (fingerprint ${fp})`);
377733
+ return { group: g, sent: false, reason: "silenced" };
377734
+ }
377735
+ g.silenced = false;
377736
+ const lastSentAt = g._lastSentAt ?? 0;
377737
+ if (this.now() - lastSentAt < this.dedupeMs && g.count > 1) {
377738
+ return { group: g, sent: false, reason: "deduped" };
377739
+ }
377740
+ await this.route(g);
377741
+ g._lastSentAt = this.now();
377742
+ return { group: g, sent: true };
377743
+ }
377744
+ async route(group) {
377745
+ const channels = this.deps.channels ?? [];
377746
+ for (const ch of channels) {
377747
+ const min = ch.minSeverity ? SEV_ORDER[ch.minSeverity] : 0;
377748
+ if (SEV_ORDER[group.severity] < min) continue;
377749
+ try {
377750
+ await ch.send(group);
377751
+ this.log(`[alert] routed "${group.title}" -> ${ch.name}`);
377752
+ } catch (e) {
377753
+ this.log(`[alert] channel ${ch.name} failed: ${e instanceof Error ? e.message : String(e)}`);
377754
+ }
377755
+ }
377756
+ this.sentHistory.unshift(`${new Date(this.now()).toISOString()} ${group.severity} ${group.title} (x${group.count})`);
377757
+ if (this.sentHistory.length > this.historyLimit) this.sentHistory.length = this.historyLimit;
377758
+ }
377759
+ groups_() {
377760
+ return Array.from(this.groups.values());
377761
+ }
377762
+ history() {
377763
+ return this.sentHistory;
377764
+ }
377765
+ /** Acknowledge an alert group (stop re-sending until a new severity escalation). */
377766
+ ack(fingerprint) {
377767
+ const g = this.groups.get(fingerprint);
377768
+ if (!g) return false;
377769
+ g._lastSentAt = this.now();
377770
+ return true;
377771
+ }
377772
+ clear() {
377773
+ this.groups.clear();
377774
+ this.silences.clear();
377775
+ this.sentHistory.length = 0;
377776
+ }
377777
+ };
377778
+
377779
+ // ../../packages/backend/src/services/sre/incidentLedger.ts
377780
+ import { randomUUID as randomUUID13 } from "crypto";
377781
+ var DEFAULT_LIMIT2 = 500;
377782
+ var IncidentLedger = class {
377783
+ incidents = /* @__PURE__ */ new Map();
377784
+ order = [];
377785
+ now;
377786
+ historyLimit;
377787
+ constructor(opts = {}) {
377788
+ this.now = opts.now ?? (() => Date.now());
377789
+ this.historyLimit = opts.historyLimit ?? DEFAULT_LIMIT2;
377790
+ }
377791
+ /** Create (or return the existing open incident for the same title+source). */
377792
+ create(input) {
377793
+ const existing = Array.from(this.incidents.values()).find(
377794
+ (i) => i.status !== "resolved" && i.title === input.title && i.source === input.source
377795
+ );
377796
+ if (existing) {
377797
+ this.addEvent(existing.id, "detected", input.detectText ?? "repeat detection");
377798
+ return { incident: existing, isNew: false };
377799
+ }
377800
+ const at = this.now();
377801
+ const inc = {
377802
+ id: `inc-${randomUUID13().slice(0, 8)}`,
377803
+ title: input.title,
377804
+ severity: input.severity ?? "sev3",
377805
+ status: "open",
377806
+ affected: input.affected ?? [],
377807
+ source: input.source,
377808
+ ...input.runbookPlaybookId ? { runbookPlaybookId: input.runbookPlaybookId } : {},
377809
+ createdAt: at,
377810
+ timeline: [{ at, kind: "detected", text: input.detectText ?? input.title }]
377811
+ };
377812
+ this.incidents.set(inc.id, inc);
377813
+ this.order.push(inc.id);
377814
+ while (this.order.length > this.historyLimit) {
377815
+ const oldest = this.order[0];
377816
+ const o = this.incidents.get(oldest);
377817
+ if (o && o.status === "resolved") {
377818
+ this.order.shift();
377819
+ this.incidents.delete(oldest);
377820
+ } else break;
377821
+ }
377822
+ return { incident: inc, isNew: true };
377823
+ }
377824
+ get(id) {
377825
+ return this.incidents.get(id);
377826
+ }
377827
+ list(filter = {}) {
377828
+ const all = this.order.map((id) => this.incidents.get(id)).filter(Boolean);
377829
+ return filter.status ? all.filter((i) => i.status === filter.status) : all;
377830
+ }
377831
+ addEvent(id, kind, text, actor) {
377832
+ const inc = this.incidents.get(id);
377833
+ if (!inc) return false;
377834
+ inc.timeline.push({ at: this.now(), kind, text, ...actor ? { actor } : {} });
377835
+ return true;
377836
+ }
377837
+ linkRunbook(id, playbookId) {
377838
+ const inc = this.incidents.get(id);
377839
+ if (!inc) return false;
377840
+ inc.runbookPlaybookId = playbookId;
377841
+ this.addEvent(id, "action", `linked runbook ${playbookId}`);
377842
+ return true;
377843
+ }
377844
+ setRca(id, rca, actor) {
377845
+ const inc = this.incidents.get(id);
377846
+ if (!inc) return false;
377847
+ inc.rca = rca;
377848
+ this.addEvent(id, "rca", rca, actor);
377849
+ return true;
377850
+ }
377851
+ addEvidence(id, evidence) {
377852
+ return this.addEvent(id, "evidence", evidence);
377853
+ }
377854
+ mitigate(id, actor) {
377855
+ const inc = this.incidents.get(id);
377856
+ if (!inc || inc.status !== "open") return false;
377857
+ inc.status = "mitigated";
377858
+ inc.mitigatedAt = this.now();
377859
+ this.addEvent(id, "mitigated", "incident mitigated", actor);
377860
+ return true;
377861
+ }
377862
+ resolve(id, actor) {
377863
+ const inc = this.incidents.get(id);
377864
+ if (!inc || inc.status === "resolved") return false;
377865
+ inc.status = "resolved";
377866
+ inc.resolvedAt = this.now();
377867
+ this.addEvent(id, "resolved", "incident resolved", actor);
377868
+ return true;
377869
+ }
377870
+ /** Auto-generate a postmortem doc from the incident's timeline + RCA. */
377871
+ postmortem(id) {
377872
+ const inc = this.incidents.get(id);
377873
+ if (!inc) return void 0;
377874
+ const dur = (a, b) => a && b ? `${Math.round((b - a) / 1e3)}s` : "\u2014";
377875
+ const lines = [
377876
+ `# Postmortem: ${inc.title}`,
377877
+ ``,
377878
+ `**Severity:** ${inc.severity} **Status:** ${inc.status} **Source:** ${inc.source}`,
377879
+ `**Affected:** ${inc.affected.join(", ") || "\u2014"}`,
377880
+ `**Opened:** ${new Date(inc.createdAt).toISOString()}`,
377881
+ inc.mitigatedAt ? `**Mitigated:** ${new Date(inc.mitigatedAt).toISOString()} (after ${dur(inc.createdAt, inc.mitigatedAt)})` : "",
377882
+ inc.resolvedAt ? `**Resolved:** ${new Date(inc.resolvedAt).toISOString()} (after ${dur(inc.createdAt, inc.resolvedAt)})` : "",
377883
+ ``,
377884
+ `## Root cause`,
377885
+ inc.rca ?? "Not yet determined.",
377886
+ ``,
377887
+ `## Timeline`,
377888
+ ...inc.timeline.map((e) => `- ${new Date(e.at).toISOString()} [${e.kind}] ${e.text}${e.actor ? ` (${e.actor})` : ""}`),
377889
+ ``,
377890
+ inc.runbookPlaybookId ? `## Runbook
377891
+ Linked playbook: ${inc.runbookPlaybookId}` : ""
377892
+ ];
377893
+ return lines.filter((l) => l !== "").join("\n");
377894
+ }
377895
+ clear() {
377896
+ this.incidents.clear();
377897
+ this.order.length = 0;
377898
+ }
377899
+ };
377900
+
377901
+ // ../../packages/backend/src/services/sre/syntheticChecks.ts
377902
+ var DEFAULT_LIMIT3 = 1e3;
377903
+ var SyntheticChecks = class {
377904
+ constructor(deps) {
377905
+ this.deps = deps;
377906
+ this.now = deps.now ?? (() => Date.now());
377907
+ this.perCheckLimit = deps.perCheckLimit ?? DEFAULT_LIMIT3;
377908
+ }
377909
+ checks = /* @__PURE__ */ new Map();
377910
+ results = /* @__PURE__ */ new Map();
377911
+ now;
377912
+ perCheckLimit;
377913
+ add(check2) {
377914
+ this.checks.set(check2.id, check2);
377915
+ return check2;
377916
+ }
377917
+ remove(id) {
377918
+ this.results.delete(id);
377919
+ return this.checks.delete(id);
377920
+ }
377921
+ list() {
377922
+ return Array.from(this.checks.values());
377923
+ }
377924
+ /** Run one check, record the result, return it. */
377925
+ async run(id) {
377926
+ const c = this.checks.get(id);
377927
+ if (!c) throw new Error(`no synthetic check "${id}"`);
377928
+ const startedAt = this.now();
377929
+ let ok = false;
377930
+ let err;
377931
+ try {
377932
+ ok = await this.exec(c);
377933
+ } catch (e) {
377934
+ err = e instanceof Error ? e.message : String(e);
377935
+ }
377936
+ const res = { checkId: id, at: this.now(), ok, latencyMs: this.now() - startedAt, ...err ? { error: err } : {} };
377937
+ let arr3 = this.results.get(id);
377938
+ if (!arr3) {
377939
+ arr3 = [];
377940
+ this.results.set(id, arr3);
377941
+ }
377942
+ arr3.push(res);
377943
+ if (arr3.length > this.perCheckLimit) arr3.splice(0, arr3.length - this.perCheckLimit);
377944
+ return res;
377945
+ }
377946
+ /** Run all checks that are due (intervalMs elapsed since last result). */
377947
+ async runDue() {
377948
+ const out = [];
377949
+ for (const c of this.checks.values()) {
377950
+ const arr3 = this.results.get(c.id);
377951
+ const last = arr3 && arr3.length > 0 ? arr3[arr3.length - 1].at : 0;
377952
+ if (this.now() - last >= (c.intervalMs ?? 6e4)) {
377953
+ out.push(await this.run(c.id));
377954
+ }
377955
+ }
377956
+ return out;
377957
+ }
377958
+ async exec(c) {
377959
+ switch (c.kind) {
377960
+ case "http": {
377961
+ if (!this.deps.probeHttp) throw new Error("no http prober");
377962
+ const code = await this.deps.probeHttp(c.address);
377963
+ const expect = c.expect ?? 200;
377964
+ return code === expect || expect === 200 && code >= 200 && code < 400;
377965
+ }
377966
+ case "tcp": {
377967
+ if (!this.deps.probeTcp) throw new Error("no tcp prober");
377968
+ return this.deps.probeTcp(c.address, c.expect ?? 22);
377969
+ }
377970
+ case "ssh": {
377971
+ if (!this.deps.probeSsh) throw new Error("no ssh prober");
377972
+ return this.deps.probeSsh(c.address);
377973
+ }
377974
+ case "command": {
377975
+ if (!this.deps.probeCommand) throw new Error("no command prober");
377976
+ return this.deps.probeCommand(c.address);
377977
+ }
377978
+ default:
377979
+ throw new Error(`unknown check kind ${c.kind}`);
377980
+ }
377981
+ }
377982
+ /** SLI event counts for a host over a window (good/total). */
377983
+ sliCounts(host, sinceMs) {
377984
+ let good = 0;
377985
+ let total = 0;
377986
+ for (const c of this.checks.values()) {
377987
+ if (c.host !== host) continue;
377988
+ for (const r of this.results.get(c.id) ?? []) {
377989
+ if (r.at < sinceMs) continue;
377990
+ total += 1;
377991
+ if (r.ok) good += 1;
377992
+ }
377993
+ }
377994
+ return { good, total };
377995
+ }
377996
+ /** Latency series for a host over a window (for golden signals). */
377997
+ latencySeries(host, sinceMs) {
377998
+ const out = [];
377999
+ for (const c of this.checks.values()) {
378000
+ if (c.host !== host) continue;
378001
+ for (const r of this.results.get(c.id) ?? []) {
378002
+ if (r.at < sinceMs) continue;
378003
+ out.push({ at: r.at, ms: r.latencyMs });
378004
+ }
378005
+ }
378006
+ return out.sort((a, b) => a.at - b.at);
378007
+ }
378008
+ /** Error rate (fraction of failed results) for a host over a window. */
378009
+ errorRate(host, sinceMs) {
378010
+ const { good, total } = this.sliCounts(host, sinceMs);
378011
+ return total > 0 ? 1 - good / total : void 0;
378012
+ }
378013
+ /** Latest result for a check. */
378014
+ latest(id) {
378015
+ const arr3 = this.results.get(id);
378016
+ return arr3 && arr3.length > 0 ? arr3[arr3.length - 1] : void 0;
378017
+ }
378018
+ clear() {
378019
+ this.checks.clear();
378020
+ this.results.clear();
378021
+ }
378022
+ };
378023
+
378024
+ // ../../packages/backend/src/services/sre/driftDetector.ts
378025
+ import { randomUUID as randomUUID14 } from "crypto";
378026
+ function normalize2(text, ignorePatterns = []) {
378027
+ const lines = text.split(/\r?\n/).map((l) => l.trimEnd()).filter((l) => l.trim() !== "");
378028
+ const regexes = ignorePatterns.map((p) => {
378029
+ try {
378030
+ return new RegExp(p);
378031
+ } catch {
378032
+ return null;
378033
+ }
378034
+ }).filter(Boolean);
378035
+ return lines.filter((l) => !regexes.some((re) => re.test(l)));
378036
+ }
378037
+ function hash(lines) {
378038
+ let h = 0;
378039
+ const s = lines.join("\n");
378040
+ for (let i = 0; i < s.length; i += 1) {
378041
+ h = Math.imul(h, 31) + s.charCodeAt(i) | 0;
378042
+ }
378043
+ return (h >>> 0).toString(36);
378044
+ }
378045
+ function diffConfigs(expected, actual) {
378046
+ const actualSet = new Set(actual);
378047
+ const expectedSet = new Set(expected);
378048
+ const removed = expected.filter((l) => !actualSet.has(l)).map((line) => ({ line, kind: "removed" }));
378049
+ const added = actual.filter((l) => !expectedSet.has(l)).map((line) => ({ line, kind: "added" }));
378050
+ return { added, removed };
378051
+ }
378052
+ var DriftDetector = class {
378053
+ constructor(deps) {
378054
+ this.deps = deps;
378055
+ this.now = deps.now ?? (() => Date.now());
378056
+ }
378057
+ targets = /* @__PURE__ */ new Map();
378058
+ lastResults = /* @__PURE__ */ new Map();
378059
+ now;
378060
+ upsert(target) {
378061
+ const t = { ...target, id: target.id ?? `drift-${randomUUID14().slice(0, 8)}` };
378062
+ this.targets.set(t.id, t);
378063
+ return t;
378064
+ }
378065
+ remove(id) {
378066
+ this.lastResults.delete(id);
378067
+ return this.targets.delete(id);
378068
+ }
378069
+ list() {
378070
+ return Array.from(this.targets.values());
378071
+ }
378072
+ lastResult(id) {
378073
+ return this.lastResults.get(id);
378074
+ }
378075
+ /** Check one target for drift. Fires onDrift + optional proposeChange when drifted. */
378076
+ async check(id) {
378077
+ const t = this.targets.get(id);
378078
+ if (!t) throw new Error(`no drift target "${id}"`);
378079
+ const [expectedText, actualText] = await Promise.all([this.deps.render(t), this.deps.getActual(t)]);
378080
+ const expected = normalize2(expectedText, t.ignorePatterns);
378081
+ const actual = normalize2(actualText, t.ignorePatterns);
378082
+ const { added, removed } = diffConfigs(expected, actual);
378083
+ const result = {
378084
+ targetId: id,
378085
+ at: this.now(),
378086
+ drifted: added.length > 0 || removed.length > 0,
378087
+ added,
378088
+ removed,
378089
+ expectedHash: hash(expected),
378090
+ actualHash: hash(actual)
378091
+ };
378092
+ this.lastResults.set(id, result);
378093
+ if (result.drifted) {
378094
+ try {
378095
+ this.deps.onDrift?.(result);
378096
+ } catch {
378097
+ }
378098
+ if (this.deps.proposeChange) {
378099
+ try {
378100
+ await this.deps.proposeChange(t, result);
378101
+ } catch {
378102
+ }
378103
+ }
378104
+ }
378105
+ return result;
378106
+ }
378107
+ /** Check every target. */
378108
+ async checkAll() {
378109
+ const out = [];
378110
+ for (const id of this.targets.keys()) {
378111
+ out.push(await this.check(id));
378112
+ }
378113
+ return out;
378114
+ }
378115
+ clear() {
378116
+ this.targets.clear();
378117
+ this.lastResults.clear();
378118
+ }
378119
+ };
378120
+
378121
+ // ../../packages/backend/src/services/apm/spanLedger.ts
378122
+ var DEFAULT_LIMIT4 = 5e4;
378123
+ function percentile2(sorted, p) {
378124
+ if (sorted.length === 0) return void 0;
378125
+ return sorted[Math.min(sorted.length - 1, Math.floor(p / 100 * sorted.length))];
378126
+ }
378127
+ var SpanLedger = class {
378128
+ spans = /* @__PURE__ */ new Map();
378129
+ // traceId -> spans
378130
+ order = [];
378131
+ // traceIds in insert order
378132
+ spanLimit;
378133
+ totalSpans = 0;
378134
+ constructor(opts = {}) {
378135
+ this.spanLimit = opts.spanLimit ?? DEFAULT_LIMIT4;
378136
+ }
378137
+ /** Ingest one span. */
378138
+ ingest(span) {
378139
+ let arr3 = this.spans.get(span.traceId);
378140
+ if (!arr3) {
378141
+ arr3 = [];
378142
+ this.spans.set(span.traceId, arr3);
378143
+ this.order.push(span.traceId);
378144
+ }
378145
+ arr3.push(span);
378146
+ this.totalSpans += 1;
378147
+ while (this.totalSpans > this.spanLimit && this.order.length > 0) {
378148
+ const oldest = this.order.shift();
378149
+ const old = this.spans.get(oldest) ?? [];
378150
+ this.totalSpans -= old.length;
378151
+ this.spans.delete(oldest);
378152
+ }
378153
+ }
378154
+ /** Ingest many spans. */
378155
+ ingestBatch(spans) {
378156
+ for (const s of spans) this.ingest(s);
378157
+ return spans.length;
378158
+ }
378159
+ /** All spans for a trace. */
378160
+ trace(traceId) {
378161
+ return this.spans.get(traceId) ?? [];
378162
+ }
378163
+ traceIds() {
378164
+ return this.order;
378165
+ }
378166
+ /** Summarize a trace (root service, span count, total duration, error). */
378167
+ summarize(traceId) {
378168
+ const spans = this.spans.get(traceId);
378169
+ if (!spans || spans.length === 0) return void 0;
378170
+ const root = spans.find((s) => !s.parentSpanId) ?? spans[0];
378171
+ const services = Array.from(new Set(spans.map((s) => s.service)));
378172
+ const hasError = spans.some((s) => s.status === "error");
378173
+ const start = Math.min(...spans.map((s) => s.startMs));
378174
+ const end = Math.max(...spans.map((s) => s.startMs + s.durationMs));
378175
+ return {
378176
+ traceId,
378177
+ rootService: root.service,
378178
+ spanCount: spans.length,
378179
+ totalDurationMs: end - start,
378180
+ hasError,
378181
+ services,
378182
+ at: start
378183
+ };
378184
+ }
378185
+ /** Per-service stats over a window. */
378186
+ serviceStats(opts = {}) {
378187
+ const byService = /* @__PURE__ */ new Map();
378188
+ for (const arr3 of this.spans.values()) {
378189
+ for (const s of arr3) {
378190
+ if (opts.sinceMs !== void 0 && s.startMs < opts.sinceMs) continue;
378191
+ if (opts.service && s.service !== opts.service) continue;
378192
+ let e = byService.get(s.service);
378193
+ if (!e) {
378194
+ e = { durations: [], errors: 0 };
378195
+ byService.set(s.service, e);
378196
+ }
378197
+ e.durations.push(s.durationMs);
378198
+ if (s.status === "error") e.errors += 1;
378199
+ }
378200
+ }
378201
+ const out = [];
378202
+ for (const [service, e] of byService) {
378203
+ const durations = e.durations.slice().sort((a, b) => a - b);
378204
+ out.push({
378205
+ service,
378206
+ spanCount: durations.length,
378207
+ errorCount: e.errors,
378208
+ errorRate: durations.length > 0 ? e.errors / durations.length : 0,
378209
+ p50Ms: percentile2(durations, 50),
378210
+ p95Ms: percentile2(durations, 95),
378211
+ p99Ms: percentile2(durations, 99),
378212
+ maxMs: durations.length > 0 ? durations[durations.length - 1] : void 0
378213
+ });
378214
+ }
378215
+ return out.sort((a, b) => (b.p95Ms ?? 0) - (a.p95Ms ?? 0));
378216
+ }
378217
+ /** Slowest traces by total duration. */
378218
+ slowestTraces(limit2 = 10, opts = {}) {
378219
+ const summaries = [];
378220
+ for (const id of this.order) {
378221
+ const s = this.summarize(id);
378222
+ if (!s) continue;
378223
+ if (opts.sinceMs !== void 0 && s.at < opts.sinceMs) continue;
378224
+ summaries.push(s);
378225
+ }
378226
+ return summaries.sort((a, b) => b.totalDurationMs - a.totalDurationMs).slice(0, limit2);
378227
+ }
378228
+ /** Services ranked by total error count (bottleneck/failing services). */
378229
+ bottleneckServices(opts = {}) {
378230
+ return this.serviceStats(opts).sort((a, b) => b.errorCount - a.errorCount);
378231
+ }
378232
+ /** Total stored spans. */
378233
+ size() {
378234
+ return this.totalSpans;
378235
+ }
378236
+ clear() {
378237
+ this.spans.clear();
378238
+ this.order.length = 0;
378239
+ this.totalSpans = 0;
378240
+ }
378241
+ };
378242
+
378243
+ // ../../packages/backend/src/services/dem/rumLedger.ts
378244
+ import { randomUUID as randomUUID15 } from "crypto";
378245
+ var DEFAULT_LIMIT5 = 5e4;
378246
+ function percentile3(sorted, p) {
378247
+ if (sorted.length === 0) return void 0;
378248
+ return sorted[Math.min(sorted.length - 1, Math.floor(p / 100 * sorted.length))];
378249
+ }
378250
+ var RumLedger = class {
378251
+ sessions = [];
378252
+ now;
378253
+ sessionLimit;
378254
+ constructor(opts = {}) {
378255
+ this.now = opts.now ?? (() => Date.now());
378256
+ this.sessionLimit = opts.sessionLimit ?? DEFAULT_LIMIT5;
378257
+ }
378258
+ /** Ingest one RUM session (a page view). */
378259
+ ingest(session) {
378260
+ const s = {
378261
+ ...session,
378262
+ id: session.id ?? `rum-${randomUUID15().slice(0, 12)}`,
378263
+ at: session.at ?? this.now()
378264
+ };
378265
+ this.sessions.push(s);
378266
+ if (this.sessions.length > this.sessionLimit) this.sessions.splice(0, this.sessions.length - this.sessionLimit);
378267
+ return s;
378268
+ }
378269
+ /** Ingest a beacon payload (the JS snippet's POST body). */
378270
+ ingestBeacon(payload) {
378271
+ const p = payload;
378272
+ if (!p || typeof p.page !== "string") return void 0;
378273
+ return this.ingest({
378274
+ page: p.page,
378275
+ ...p.route ? { route: p.route } : {},
378276
+ ...p.region ? { region: p.region } : {},
378277
+ ...p.userAgent ? { userAgent: p.userAgent } : {},
378278
+ ...typeof p.lcpMs === "number" ? { lcpMs: p.lcpMs } : {},
378279
+ ...typeof p.inpMs === "number" ? { inpMs: p.inpMs } : {},
378280
+ ...typeof p.cls === "number" ? { cls: p.cls } : {},
378281
+ ...typeof p.ttfbMs === "number" ? { ttfbMs: p.ttfbMs } : {},
378282
+ ...typeof p.jsErrors === "number" ? { jsErrors: p.jsErrors } : {},
378283
+ ...p.at ? { at: p.at } : {}
378284
+ });
378285
+ }
378286
+ /** Sessions for a page (or all), optionally within a window. */
378287
+ sessionsFor(opts = {}) {
378288
+ return this.sessions.filter(
378289
+ (s) => (opts.page === void 0 || s.page === opts.page) && (opts.sinceMs === void 0 || s.at >= opts.sinceMs)
378290
+ );
378291
+ }
378292
+ /** Per-page UX stats over a window. */
378293
+ pageStats(opts = {}) {
378294
+ const byPage = /* @__PURE__ */ new Map();
378295
+ for (const s of this.sessions) {
378296
+ if (opts.sinceMs !== void 0 && s.at < opts.sinceMs) continue;
378297
+ if (opts.page && s.page !== opts.page) continue;
378298
+ let arr3 = byPage.get(s.page);
378299
+ if (!arr3) {
378300
+ arr3 = [];
378301
+ byPage.set(s.page, arr3);
378302
+ }
378303
+ arr3.push(s);
378304
+ }
378305
+ const out = [];
378306
+ for (const [page, arr3] of byPage) {
378307
+ const lcp = arr3.map((s) => s.lcpMs).filter((x) => typeof x === "number").sort((a, b) => a - b);
378308
+ const inp = arr3.map((s) => s.inpMs).filter((x) => typeof x === "number").sort((a, b) => a - b);
378309
+ const ttfb = arr3.map((s) => s.ttfbMs).filter((x) => typeof x === "number").sort((a, b) => a - b);
378310
+ const clsVals = arr3.map((s) => s.cls).filter((x) => typeof x === "number");
378311
+ const errCount = arr3.filter((s) => (s.jsErrors ?? 0) > 0).length;
378312
+ out.push({
378313
+ page,
378314
+ sessions: arr3.length,
378315
+ p75LcpMs: percentile3(lcp, 75),
378316
+ p75InpMs: percentile3(inp, 75),
378317
+ avgCls: clsVals.length > 0 ? clsVals.reduce((a, b) => a + b, 0) / clsVals.length : void 0,
378318
+ p75TtfbMs: percentile3(ttfb, 75),
378319
+ errorRate: arr3.length > 0 ? errCount / arr3.length : 0
378320
+ });
378321
+ }
378322
+ return out.sort((a, b) => (b.p75LcpMs ?? 0) - (a.p75LcpMs ?? 0));
378323
+ }
378324
+ /** Slowest pages by p75 LCP. */
378325
+ slowestPages(limit2 = 10, opts = {}) {
378326
+ return this.pageStats(opts).sort((a, b) => (b.p75LcpMs ?? 0) - (a.p75LcpMs ?? 0)).slice(0, limit2);
378327
+ }
378328
+ /** Pages exceeding a Core Web Vitals threshold (LCP > good threshold, default 2500ms). */
378329
+ poorPages(lcpThresholdMs = 2500, opts = {}) {
378330
+ return this.pageStats(opts).filter((p) => (p.p75LcpMs ?? 0) > lcpThresholdMs);
378331
+ }
378332
+ size() {
378333
+ return this.sessions.length;
378334
+ }
378335
+ clear() {
378336
+ this.sessions.length = 0;
378337
+ }
378338
+ };
378339
+
378340
+ // ../../packages/backend/src/services/infra/infraMonitor.ts
378341
+ function clusterHealth(context2, pods, nodes) {
378342
+ const running = pods.filter((p) => p.phase === "Running");
378343
+ const notReady = pods.filter((p) => !p.ready).length;
378344
+ const crashLoop = pods.filter((p) => p.restarts >= 5 || p.phase === "Unknown" && p.restarts > 0).length;
378345
+ const totalRestarts = pods.reduce((s, p) => s + p.restarts, 0);
378346
+ const nodesReady = nodes.filter((n2) => n2.ready).length;
378347
+ let cpuPct;
378348
+ let memPct;
378349
+ const withCpu = pods.filter((p) => typeof p.cpuMillicores === "number" && typeof p.cpuLimitMillicores === "number" && p.cpuLimitMillicores > 0);
378350
+ if (withCpu.length > 0) {
378351
+ const used = withCpu.reduce((s, p) => s + (p.cpuMillicores ?? 0), 0);
378352
+ const limit2 = withCpu.reduce((s, p) => s + (p.cpuLimitMillicores ?? 0), 0);
378353
+ cpuPct = limit2 > 0 ? used / limit2 * 100 : void 0;
378354
+ }
378355
+ const withMem = pods.filter((p) => typeof p.memMiB === "number" && typeof p.memLimitMiB === "number" && p.memLimitMiB > 0);
378356
+ if (withMem.length > 0) {
378357
+ const used = withMem.reduce((s, p) => s + (p.memMiB ?? 0), 0);
378358
+ const limit2 = withMem.reduce((s, p) => s + (p.memLimitMiB ?? 0), 0);
378359
+ memPct = limit2 > 0 ? used / limit2 * 100 : void 0;
378360
+ }
378361
+ return {
378362
+ context: context2,
378363
+ totalPods: pods.length,
378364
+ runningPods: running.length,
378365
+ notReadyPods: notReady,
378366
+ crashLoopPods: crashLoop,
378367
+ totalRestarts,
378368
+ nodesReady,
378369
+ nodesTotal: nodes.length,
378370
+ ...cpuPct !== void 0 ? { cpuUsagePercentOfLimit: cpuPct } : {},
378371
+ ...memPct !== void 0 ? { memUsagePercentOfLimit: memPct } : {}
378372
+ };
378373
+ }
378374
+ function podUnhealthy(p) {
378375
+ return !p.ready || p.phase === "Failed" || p.phase === "Unknown" || p.restarts >= 5;
378376
+ }
378377
+ var InfraMonitor = class {
378378
+ clusters = /* @__PURE__ */ new Map();
378379
+ instances = /* @__PURE__ */ new Map();
378380
+ constructor(_deps = {}) {
378381
+ }
378382
+ /** Record a cluster health snapshot. */
378383
+ recordCluster(context2, pods, nodes) {
378384
+ const h = clusterHealth(context2, pods, nodes);
378385
+ this.clusters.set(context2, h);
378386
+ return h;
378387
+ }
378388
+ cluster(context2) {
378389
+ return this.clusters.get(context2);
378390
+ }
378391
+ clusters_() {
378392
+ return Array.from(this.clusters.values());
378393
+ }
378394
+ /** Unhealthy pods for a cluster (for alerting). */
378395
+ unhealthyPods(pods) {
378396
+ return pods.filter(podUnhealthy);
378397
+ }
378398
+ /** Record a cloud instance state. */
378399
+ recordInstance(inst) {
378400
+ this.instances.set(inst.id, inst);
378401
+ }
378402
+ instance(id) {
378403
+ return this.instances.get(id);
378404
+ }
378405
+ /** Instances that are not healthy (stopped/failed). */
378406
+ unhealthyInstances() {
378407
+ return Array.from(this.instances.values()).filter((i) => i.statusOk === false || /stopped|terminated|failed/i.test(i.state));
378408
+ }
378409
+ clear() {
378410
+ this.clusters.clear();
378411
+ this.instances.clear();
378412
+ }
378413
+ };
378414
+
378415
+ // ../../packages/backend/src/services/etw/etwService.ts
378416
+ import { randomUUID as randomUUID16 } from "crypto";
378417
+ var now0 = () => Date.now();
378418
+ var EtwService = class {
378419
+ sessions = /* @__PURE__ */ new Map();
378420
+ now;
378421
+ constructor(deps = {}) {
378422
+ this.now = deps.now ?? now0;
378423
+ }
378424
+ /** Create a session descriptor (commands are built from it by buildStartCommands). */
378425
+ createSession(name, providers, outDir = "C:\\temp") {
378426
+ const clean = name.replace(/[^A-Za-z0-9_-]/g, "");
378427
+ const s = {
378428
+ id: `etw-${randomUUID16().slice(0, 8)}`,
378429
+ name: clean,
378430
+ providers,
378431
+ outFile: `${outDir}\\${clean}`,
378432
+ createdAt: this.now()
378433
+ };
378434
+ this.sessions.set(s.id, s);
378435
+ return s;
378436
+ }
378437
+ session(id) {
378438
+ return this.sessions.get(id);
378439
+ }
378440
+ sessions_() {
378441
+ return Array.from(this.sessions.values());
378442
+ }
378443
+ removeSession(id) {
378444
+ return this.sessions.delete(id);
378445
+ }
378446
+ clear() {
378447
+ this.sessions.clear();
378448
+ }
378449
+ };
378450
+
378451
+ // ../../packages/backend/src/services/dashboard/dashboardService.ts
378452
+ var DEFAULT_LIMIT6 = 10;
378453
+ var DashboardService = class {
378454
+ constructor(deps) {
378455
+ this.deps = deps;
378456
+ this.now = deps.now ?? (() => Date.now());
378457
+ this.limit = deps.sectionLimit ?? DEFAULT_LIMIT6;
378458
+ }
378459
+ now;
378460
+ limit;
378461
+ /** Build the unified dashboard state. */
378462
+ async state(opts = {}) {
378463
+ const d = this.deps;
378464
+ const golden = d.goldenSignals.reportAll();
378465
+ const uptime = d.uptimeWatchdog.allStatus();
378466
+ const goldenByHost = new Map(golden.map((g) => [g.host, g]));
378467
+ const uptimeByHost = new Map(uptime.map((u) => [u.target.name, u]));
378468
+ const allHosts = /* @__PURE__ */ new Set([...goldenByHost.keys(), ...uptimeByHost.keys()]);
378469
+ const hosts = Array.from(allHosts).map((host) => ({
378470
+ host,
378471
+ ...goldenByHost.get(host) ? { golden: goldenByHost.get(host) } : {},
378472
+ ...uptimeByHost.get(host) ? { uptime: uptimeByHost.get(host) } : {}
378473
+ }));
378474
+ const slos = await d.sloService.evaluateAll();
378475
+ const incidents = d.incidentLedger.list(opts.incidentStatus ? { status: opts.incidentStatus } : { status: "open" }).slice(0, this.limit);
378476
+ const apm = d.spanLedger ? {
378477
+ bottleneckServices: d.spanLedger.bottleneckServices().slice(0, this.limit),
378478
+ slowestTraces: d.spanLedger.slowestTraces(this.limit)
378479
+ } : { bottleneckServices: [], slowestTraces: [] };
378480
+ const dem = d.rumLedger ? {
378481
+ slowestPages: d.rumLedger.slowestPages(this.limit),
378482
+ poorPages: d.rumLedger.poorPages(2500).slice(0, this.limit)
378483
+ } : { slowestPages: [], poorPages: [] };
378484
+ const clusters = d.infraMonitor ? d.infraMonitor.clusters_().slice(0, this.limit) : [];
378485
+ const capacity = d.goldenSignals.capacityForecast();
378486
+ return {
378487
+ at: this.now(),
378488
+ hosts,
378489
+ slos,
378490
+ uptime,
378491
+ incidents,
378492
+ apm,
378493
+ dem,
378494
+ clusters,
378495
+ capacity
378496
+ };
378497
+ }
378498
+ /** A compact summary line for the gateway/agent (e.g. "3 hosts, 1 degraded, 2 open incidents, 1 SLO fast-burning"). */
378499
+ async summary() {
378500
+ const s = await this.state();
378501
+ const down = s.uptime.filter((u) => u.state === "down").length;
378502
+ const degraded = s.uptime.filter((u) => u.state === "degraded").length;
378503
+ const fastBurn = s.slos.filter((e) => e.fastBurning).length;
378504
+ const openInc = s.incidents.length;
378505
+ const parts = [
378506
+ `${s.hosts.length} hosts`,
378507
+ down > 0 ? `${down} down` : null,
378508
+ degraded > 0 ? `${degraded} degraded` : null,
378509
+ openInc > 0 ? `${openInc} open incident${openInc === 1 ? "" : "s"}` : "no open incidents",
378510
+ fastBurn > 0 ? `${fastBurn} SLO fast-burning` : "SLOs healthy"
378511
+ ];
378512
+ return parts.filter(Boolean).join(" \xB7 ");
378513
+ }
378514
+ };
378515
+
378516
+ // ../../packages/backend/src/services/notify/notifyService.ts
378517
+ var SEV_COLOR = {
378518
+ info: "#0b7285",
378519
+ warning: "#b45309",
378520
+ critical: "#c92a2a"
378521
+ };
378522
+ var SEV_EMOJI = {
378523
+ info: "\u2139\uFE0F",
378524
+ warning: "\u26A0\uFE0F",
378525
+ critical: "\u{1F525}"
378526
+ };
378527
+ function sevColor(sev) {
378528
+ return SEV_COLOR[sev];
378529
+ }
378530
+ function sevEmoji(sev) {
378531
+ return SEV_EMOJI[sev];
378532
+ }
378533
+ function groupFacts(group) {
378534
+ const a = group.lastAlert;
378535
+ const facts = [
378536
+ { name: "Severity", value: group.severity.toUpperCase() },
378537
+ { name: "Source", value: a.source },
378538
+ { name: "Count", value: `x${group.count}` }
378539
+ ];
378540
+ if (a.detail) facts.push({ name: "Detail", value: a.detail.slice(0, 400) });
378541
+ if (a.labels) {
378542
+ for (const [k, v] of Object.entries(a.labels)) facts.push({ name: k, value: v });
378543
+ }
378544
+ facts.push({ name: "Time", value: new Date(group.lastAt).toISOString() });
378545
+ return facts;
378546
+ }
378547
+ function buildSlackPayload(group) {
378548
+ const a = group.lastAlert;
378549
+ return {
378550
+ username: "RTerm",
378551
+ attachments: [
378552
+ {
378553
+ color: sevColor(group.severity),
378554
+ title: `${sevEmoji(group.severity)} ${group.title}`,
378555
+ title_link: void 0,
378556
+ text: a.detail ? a.detail.slice(0, 500) : void 0,
378557
+ fields: groupFacts(group).map((f) => ({ title: f.name, value: f.value, short: f.value.length < 40 })),
378558
+ footer: `RTerm AlertService \u2022 fingerprint ${group.fingerprint}`,
378559
+ ts: Math.floor(group.lastAt / 1e3)
378560
+ }
378561
+ ]
378562
+ };
378563
+ }
378564
+ function slackChannel(opts, fetchFn) {
378565
+ return {
378566
+ name: "slack",
378567
+ ...opts.minSeverity ? { minSeverity: opts.minSeverity } : {},
378568
+ send: async (group) => {
378569
+ const payload = buildSlackPayload(group);
378570
+ if (opts.username) payload.username = opts.username;
378571
+ const res = await fetchFn(opts.webhookUrl, {
378572
+ method: "POST",
378573
+ headers: { "content-type": "application/json" },
378574
+ body: JSON.stringify(payload)
378575
+ });
378576
+ if (!res.ok) throw new Error(`slack webhook ${res.status}: ${await res.text()}`);
378577
+ return `slack ${res.status}`;
378578
+ }
378579
+ };
378580
+ }
378581
+ function buildTeamsPayload(group) {
378582
+ return {
378583
+ "@type": "MessageCard",
378584
+ "@context": "https://schema.org/extensions",
378585
+ themeColor: sevColor(group.severity).replace("#", ""),
378586
+ summary: group.title,
378587
+ sections: [
378588
+ {
378589
+ activityTitle: `${sevEmoji(group.severity)} ${group.title}`,
378590
+ activitySubtitle: `RTerm AlertService \u2014 ${group.lastAlert.source}`,
378591
+ activityImage: void 0,
378592
+ facts: groupFacts(group).map((f) => ({ name: f.name, value: f.value })),
378593
+ markdown: true
378594
+ }
378595
+ ]
378596
+ };
378597
+ }
378598
+ function teamsChannel(opts, fetchFn) {
378599
+ return {
378600
+ name: "teams",
378601
+ ...opts.minSeverity ? { minSeverity: opts.minSeverity } : {},
378602
+ send: async (group) => {
378603
+ const payload = buildTeamsPayload(group);
378604
+ const res = await fetchFn(opts.webhookUrl, {
378605
+ method: "POST",
378606
+ headers: { "content-type": "application/json" },
378607
+ body: JSON.stringify(payload)
378608
+ });
378609
+ if (!res.ok) throw new Error(`teams webhook ${res.status}: ${await res.text()}`);
378610
+ return `teams ${res.status}`;
378611
+ }
378612
+ };
378613
+ }
378614
+ function buildEmail(group, from, to) {
378615
+ const a = group.lastAlert;
378616
+ const factsRows = groupFacts(group).map((f) => `<tr><td style="padding:2px 12px 2px 0;color:#66727d">${f.name}</td><td>${escapeHtml2(f.value)}</td></tr>`).join("");
378617
+ const html = `<div style="font-family:sans-serif;max-width:560px"><div style="border-left:4px solid ${sevColor(group.severity)};padding:8px 12px;background:#f6f8fa"><b>${sevEmoji(group.severity)} ${escapeHtml2(group.title)}</b></div>` + (a.detail ? `<p>${escapeHtml2(a.detail)}</p>` : "") + `<table style="font-size:13px;margin-top:8px">${factsRows}</table><p style="color:#98a4ae;font-size:11px">RTerm AlertService \u2022 ${escapeHtml2(group.fingerprint)}</p></div>`;
378618
+ const text = `${sevEmoji(group.severity)} ${group.title}
378619
+
378620
+ ` + (a.detail ? `${a.detail}
378621
+
378622
+ ` : "") + groupFacts(group).map((f) => `${f.name}: ${f.value}`).join("\n") + `
378623
+
378624
+ RTerm AlertService \u2022 ${group.fingerprint}`;
378625
+ return {
378626
+ from,
378627
+ to,
378628
+ subject: `[${group.severity.toUpperCase()}] ${group.title}`,
378629
+ text,
378630
+ html
378631
+ };
378632
+ }
378633
+ function escapeHtml2(s) {
378634
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
378635
+ }
378636
+ function smtpChannel(opts, smtpFn) {
378637
+ return {
378638
+ name: opts.name ?? "email",
378639
+ ...opts.minSeverity ? { minSeverity: opts.minSeverity } : {},
378640
+ send: async (group) => {
378641
+ const mail = buildEmail(group, opts.from, opts.to);
378642
+ return smtpFn(mail);
378643
+ }
378644
+ };
378645
+ }
378646
+ function buildTelegramPayload(chatId, group) {
378647
+ const a = group.lastAlert;
378648
+ const lines = [
378649
+ `${sevEmoji(group.severity)} *${escapeMd(group.title)}*`,
378650
+ ``,
378651
+ `*Severity:* ${group.severity.toUpperCase()}`,
378652
+ `*Source:* ${escapeMd(a.source)}`,
378653
+ `*Count:* x${group.count}`
378654
+ ];
378655
+ if (a.detail) lines.push(`*Detail:* ${escapeMd(a.detail.slice(0, 400))}`);
378656
+ if (a.labels) for (const [k, v] of Object.entries(a.labels)) lines.push(`*${escapeMd(k)}:* ${escapeMd(v)}`);
378657
+ lines.push(`_RTerm AlertService_`);
378658
+ return { chat_id: chatId, text: lines.join("\n"), parse_mode: "Markdown" };
378659
+ }
378660
+ function escapeMd(s) {
378661
+ return s.replace(/[_*[\]()~`>#+=|{}.!-]/g, (c) => `\\${c}`);
378662
+ }
378663
+ function telegramChannel(opts, fetchFn) {
378664
+ return {
378665
+ name: "telegram",
378666
+ ...opts.minSeverity ? { minSeverity: opts.minSeverity } : {},
378667
+ send: async (group) => {
378668
+ const url2 = `https://api.telegram.org/bot${opts.botToken}/sendMessage`;
378669
+ const payload = buildTelegramPayload(opts.chatId, group);
378670
+ const res = await fetchFn(url2, {
378671
+ method: "POST",
378672
+ headers: { "content-type": "application/json" },
378673
+ body: JSON.stringify(payload)
378674
+ });
378675
+ if (!res.ok) throw new Error(`telegram ${res.status}: ${await res.text()}`);
378676
+ return `telegram ${res.status}`;
378677
+ }
378678
+ };
378679
+ }
378680
+
378681
+ // ../../packages/backend/src/services/evals/evalHarness.ts
378682
+ import { randomUUID as randomUUID17 } from "crypto";
378683
+ function subset(needles, haystack) {
378684
+ return needles.every((n2) => haystack.includes(n2));
378685
+ }
378686
+ var EvalHarness = class {
378687
+ constructor(deps) {
378688
+ this.deps = deps;
378689
+ this.now = deps.now ?? (() => Date.now());
378690
+ }
378691
+ now;
378692
+ /** Run one eval case. */
378693
+ async runCase(c) {
378694
+ const startedAt = this.now();
378695
+ try {
378696
+ switch (c.kind) {
378697
+ case "accuracy":
378698
+ case "tool-selection": {
378699
+ const out = await this.deps.runAgent(c.prompt);
378700
+ const tokens = out.tokens;
378701
+ const latencyMs = this.now() - startedAt;
378702
+ if (c.kind === "accuracy") {
378703
+ const need = c.expectAnswerContains ?? "";
378704
+ const pass2 = need === "" ? true : out.answer.toLowerCase().includes(need.toLowerCase());
378705
+ return { caseId: c.id, kind: c.kind, pass: pass2, reason: pass2 ? "answer matched" : `answer missing "${need}"`, ...tokens !== void 0 ? { tokens } : {}, latencyMs };
378706
+ }
378707
+ const tools2 = c.expectTools ?? [];
378708
+ const pass = subset(tools2, out.toolsCalled);
378709
+ return { caseId: c.id, kind: c.kind, pass, reason: pass ? "tools matched" : `expected tools ${JSON.stringify(tools2)}, got ${JSON.stringify(out.toolsCalled)}`, ...tokens !== void 0 ? { tokens } : {}, latencyMs };
378710
+ }
378711
+ case "safety": {
378712
+ const cmd = c.expectBlockedCommand ?? "";
378713
+ if (!cmd) return { caseId: c.id, kind: c.kind, pass: false, reason: "no expectBlockedCommand provided", latencyMs: 0 };
378714
+ if (!this.deps.isCommandBlocked) {
378715
+ return { caseId: c.id, kind: c.kind, pass: false, reason: "no policy checker injected", latencyMs: 0 };
378716
+ }
378717
+ const blocked = this.deps.isCommandBlocked(cmd);
378718
+ return { caseId: c.id, kind: c.kind, pass: blocked, reason: blocked ? "blocked as required" : `command NOT blocked: ${cmd}`, latencyMs: this.now() - startedAt };
378719
+ }
378720
+ case "replay": {
378721
+ const out = await this.deps.runAgent(c.prompt);
378722
+ const expected = c.expectToolSequence ?? [];
378723
+ const pass = JSON.stringify(out.toolsCalled) === JSON.stringify(expected);
378724
+ return { caseId: c.id, kind: c.kind, pass, reason: pass ? "sequence matched" : `expected ${JSON.stringify(expected)}, got ${JSON.stringify(out.toolsCalled)}`, latencyMs: this.now() - startedAt };
378725
+ }
378726
+ default:
378727
+ return { caseId: c.id, kind: c.kind, pass: false, reason: `unknown eval kind ${c.kind}`, latencyMs: 0 };
378728
+ }
378729
+ } catch (e) {
378730
+ return { caseId: c.id, kind: c.kind, pass: false, reason: `error: ${e instanceof Error ? e.message : String(e)}`, latencyMs: this.now() - startedAt };
378731
+ }
378732
+ }
378733
+ /** Run a golden set and produce the aggregate report. */
378734
+ async runEval(cases) {
378735
+ const results = [];
378736
+ for (const c of cases) {
378737
+ results.push(await this.runCase(c));
378738
+ }
378739
+ const passed = results.filter((r) => r.pass).length;
378740
+ const byKind = (kind) => {
378741
+ const arr3 = results.filter((r) => r.kind === kind);
378742
+ return arr3.length > 0 ? arr3.filter((r) => r.pass).length / arr3.length * 100 : void 0;
378743
+ };
378744
+ return {
378745
+ id: `eval-${randomUUID17().slice(0, 8)}`,
378746
+ at: this.now(),
378747
+ total: results.length,
378748
+ passed,
378749
+ failed: results.length - passed,
378750
+ accuracyPct: byKind("accuracy"),
378751
+ toolSelectionPct: byKind("tool-selection"),
378752
+ safetyPct: byKind("safety"),
378753
+ replayPct: byKind("replay"),
378754
+ results
378755
+ };
378756
+ }
378757
+ };
378758
+
378759
+ // ../../packages/backend/src/services/predictive/anomalyDetector.ts
378760
+ var DEFAULT_MIN_POINTS = 5;
378761
+ function mean(xs) {
378762
+ return xs.reduce((a, b) => a + b, 0) / xs.length;
378763
+ }
378764
+ function median(xs) {
378765
+ const s = xs.slice().sort((a, b) => a - b);
378766
+ const mid = Math.floor(s.length / 2);
378767
+ return s.length % 2 === 0 ? (s[mid - 1] + s[mid]) / 2 : s[mid];
378768
+ }
378769
+ function stddev(xs) {
378770
+ if (xs.length < 2) return 0;
378771
+ const m = mean(xs);
378772
+ return Math.sqrt(xs.reduce((s, x) => s + (x - m) * (x - m), 0) / xs.length);
378773
+ }
378774
+ var AnomalyDetector = class {
378775
+ constructor(ledger) {
378776
+ this.ledger = ledger;
378777
+ }
378778
+ /** Detect anomalies in a host's metric over the recent window.
378779
+ * The baseline is all points EXCEPT the last `lookbackCount` candidates;
378780
+ * the candidates are the most recent points (default: just the latest). */
378781
+ detect(host, metric, opts = {}) {
378782
+ const method = opts.method ?? "robust";
378783
+ const threshold = opts.threshold ?? (method === "robust" ? 3.5 : 3);
378784
+ const minPoints = opts.minPoints ?? DEFAULT_MIN_POINTS;
378785
+ const lookbackCount = Math.max(1, opts.lookbackCount ?? 1);
378786
+ const series = this.ledger.metricSeries(host, metric);
378787
+ const values = series.points.map((p) => p.value);
378788
+ if (values.length < minPoints + lookbackCount) return [];
378789
+ const baseline = values.slice(0, values.length - lookbackCount);
378790
+ const candidates = series.points.slice(-lookbackCount);
378791
+ const out = [];
378792
+ for (const cand of candidates) {
378793
+ const value = cand.value;
378794
+ let center;
378795
+ let z;
378796
+ if (method === "robust") {
378797
+ center = median(baseline);
378798
+ const absDev = baseline.map((x) => Math.abs(x - center));
378799
+ const mad = median(absDev);
378800
+ const sigma = mad === 0 ? 0 : mad / 0.6745;
378801
+ if (sigma === 0) {
378802
+ z = value === center ? 0 : 1e9;
378803
+ } else {
378804
+ z = Math.abs(value - center) / sigma;
378805
+ }
378806
+ } else {
378807
+ center = mean(baseline);
378808
+ const sd = stddev(baseline);
378809
+ if (sd === 0) {
378810
+ z = value === center ? 0 : 1e9;
378811
+ } else {
378812
+ z = Math.abs(value - center) / sd;
378813
+ }
378814
+ }
378815
+ if (z > threshold) {
378816
+ out.push({ host, metric, method, value, center, zScore: z, threshold, at: Date.now(), valueAt: cand.at });
378817
+ }
378818
+ }
378819
+ return out;
378820
+ }
378821
+ /** Detect anomalies for the latest point of a host (convenience). */
378822
+ detectLatest(host, metric, opts = {}) {
378823
+ return this.detect(host, metric, { ...opts, lookbackCount: 1 })[0];
378824
+ }
378825
+ /** Detect anomalies across many metrics for a host's latest point. */
378826
+ detectLatestAll(host, metrics, opts = {}) {
378827
+ const out = [];
378828
+ for (const m of metrics) {
378829
+ const r = this.detectLatest(host, m, opts);
378830
+ if (r) out.push(r);
378831
+ }
378832
+ return out;
378833
+ }
378834
+ };
378835
+
378836
+ // ../../packages/backend/src/services/predictive/earlyWarningService.ts
378837
+ var EarlyWarningService = class {
378838
+ constructor(deps) {
378839
+ this.deps = deps;
378840
+ this.now = deps.now ?? (() => Date.now());
378841
+ }
378842
+ now;
378843
+ /** Evaluate a host+metric for a predictive breach (forecast and/or anomaly). */
378844
+ evaluate(host, metric, opts) {
378845
+ const warnings = [];
378846
+ const warnDays = opts.warnDays ?? 7;
378847
+ const days = this.deps.ledger.daysUntilThreshold(host, metric, opts.threshold);
378848
+ if (days !== void 0 && days <= warnDays) {
378849
+ const msg = days <= 0 ? `${host} ${metric} has already crossed ${opts.threshold}` : `${host} ${metric} is forecast to hit ${opts.threshold} in ~${Math.ceil(days)} day${Math.ceil(days) === 1 ? "" : "s"}`;
378850
+ warnings.push({
378851
+ kind: "forecast",
378852
+ host,
378853
+ metric: String(metric),
378854
+ value: days,
378855
+ reference: opts.threshold,
378856
+ message: msg,
378857
+ at: this.now()
378858
+ });
378859
+ }
378860
+ if (opts.includeAnomalies !== false) {
378861
+ const anomaly = this.deps.anomalyDetector.detectLatest(host, metric);
378862
+ if (anomaly) {
378863
+ warnings.push({
378864
+ kind: "anomaly",
378865
+ host,
378866
+ metric: String(metric),
378867
+ value: anomaly.zScore,
378868
+ reference: anomaly.center,
378869
+ message: `${host} ${metric} anomaly: ${anomaly.value.toFixed(1)} is ${anomaly.zScore.toFixed(1)}\u03C3 from baseline ${anomaly.center.toFixed(1)}`,
378870
+ at: this.now()
378871
+ });
378872
+ }
378873
+ }
378874
+ for (const w of warnings) {
378875
+ try {
378876
+ this.deps.onWarning?.(w);
378877
+ } catch {
378878
+ }
378879
+ if (this.deps.proposeChange) {
378880
+ void this.deps.proposeChange(w).catch(() => {
378881
+ });
378882
+ }
378883
+ }
378884
+ return warnings;
378885
+ }
378886
+ /** Evaluate a host across many metrics. */
378887
+ evaluateHost(host, metrics, opts) {
378888
+ const out = [];
378889
+ for (const m of metrics) out.push(...this.evaluate(host, m, opts));
378890
+ return out;
378891
+ }
378892
+ /** Evaluate every host in the ledger across the given metrics. */
378893
+ evaluateAll(metrics, opts) {
378894
+ const out = [];
378895
+ for (const host of this.deps.ledger.hosts()) {
378896
+ out.push(...this.evaluateHost(host, metrics, opts));
378897
+ }
378898
+ return out;
378899
+ }
378900
+ };
378901
+
378902
+ // ../../packages/backend/src/services/behavior/behaviorLedger.ts
378903
+ var DAY = 864e5;
378904
+ var BehaviorLedger = class {
378905
+ events = [];
378906
+ now;
378907
+ constructor(opts = {}) {
378908
+ this.now = opts.now ?? (() => Date.now());
378909
+ }
378910
+ /** Ingest a run event (from an AgentRunRecord). */
378911
+ ingest(event) {
378912
+ this.events.push(event);
378913
+ }
378914
+ /** Ingest an AgentRunRecord. */
378915
+ ingestRecord(record2) {
378916
+ this.ingest({
378917
+ at: record2.startedAt,
378918
+ sessionId: record2.sessionId,
378919
+ ...record2.model ? { model: record2.model } : {},
378920
+ status: record2.status,
378921
+ promptTokens: record2.promptTokens,
378922
+ completionTokens: record2.completionTokens
378923
+ });
378924
+ }
378925
+ /** Events within a window. */
378926
+ eventsIn(sinceMs) {
378927
+ return this.events.filter((e) => e.at >= sinceMs);
378928
+ }
378929
+ /** Compute the baseline over a window (default 14 days), EXCLUDING the current
378930
+ * day — so today's behavior is compared against prior behavior, not itself. */
378931
+ baseline(windowDays = 14) {
378932
+ const now = this.now();
378933
+ const since = now - windowDays * DAY;
378934
+ const dayStart = now - DAY;
378935
+ const recent = this.events.filter((e) => e.at >= since && e.at < dayStart);
378936
+ const totalRuns = recent.length;
378937
+ const errors = recent.filter((e) => /fail|error|aborted/i.test(e.status)).length;
378938
+ const tokens = recent.map((e) => e.promptTokens + e.completionTokens);
378939
+ const models = Array.from(new Set(recent.map((e) => e.model).filter((m) => Boolean(m))));
378940
+ return {
378941
+ runsPerDay: totalRuns / windowDays,
378942
+ tokensPerRun: tokens.length > 0 ? tokens.reduce((a, b) => a + b, 0) / tokens.length : 0,
378943
+ errorRate: totalRuns > 0 ? errors / totalRuns : 0,
378944
+ models,
378945
+ totalRuns,
378946
+ windowDays
378947
+ };
378948
+ }
378949
+ /** Detect behavioral deviations in the most recent day vs. the baseline. */
378950
+ detect(opts = {}) {
378951
+ const now = this.now();
378952
+ const baseline = this.baseline(14);
378953
+ const today = this.events.filter((e) => e.at >= now - DAY);
378954
+ const deviations = [];
378955
+ const runSpikeFactor = opts.runSpikeFactor ?? 3;
378956
+ const tokenBlowoutFactor = opts.tokenBlowoutFactor ?? 5;
378957
+ const errorSpikeDelta = opts.errorSpikeDelta ?? 0.3;
378958
+ const todayRunsPerDay = today.length;
378959
+ if (baseline.runsPerDay > 0 && todayRunsPerDay > baseline.runsPerDay * runSpikeFactor) {
378960
+ deviations.push({
378961
+ kind: "run-spike",
378962
+ message: `unusual activity: ${todayRunsPerDay} runs today vs baseline ${baseline.runsPerDay.toFixed(1)}/day`,
378963
+ value: todayRunsPerDay,
378964
+ baseline: baseline.runsPerDay,
378965
+ at: now
378966
+ });
378967
+ }
378968
+ for (const e of today) {
378969
+ const total = e.promptTokens + e.completionTokens;
378970
+ if (baseline.tokensPerRun > 0 && total > baseline.tokensPerRun * tokenBlowoutFactor) {
378971
+ deviations.push({
378972
+ kind: "token-blowout",
378973
+ message: `token blowout in session ${e.sessionId}: ${total} tokens vs baseline ${baseline.tokensPerRun.toFixed(0)}`,
378974
+ value: total,
378975
+ baseline: baseline.tokensPerRun,
378976
+ at: e.at
378977
+ });
378978
+ break;
378979
+ }
378980
+ }
378981
+ if (today.length > 0) {
378982
+ const todayErrors = today.filter((e) => /fail|error|aborted/i.test(e.status)).length;
378983
+ const todayErrorRate = todayErrors / today.length;
378984
+ if (todayErrorRate > baseline.errorRate + errorSpikeDelta && today.length >= 2) {
378985
+ deviations.push({
378986
+ kind: "error-spike",
378987
+ message: `error spike: ${(todayErrorRate * 100).toFixed(0)}% of runs failed today vs baseline ${(baseline.errorRate * 100).toFixed(0)}%`,
378988
+ value: todayErrorRate,
378989
+ baseline: baseline.errorRate,
378990
+ at: now
378991
+ });
378992
+ }
378993
+ }
378994
+ const todayModels = Array.from(new Set(today.map((e) => e.model).filter((m) => Boolean(m))));
378995
+ for (const m of todayModels) {
378996
+ if (baseline.models.length > 0 && !baseline.models.includes(m)) {
378997
+ deviations.push({
378998
+ kind: "unusual-model",
378999
+ message: `unusual model in use: ${m} (baseline: ${baseline.models.join(", ")})`,
379000
+ value: m,
379001
+ baseline: baseline.models.join(","),
379002
+ at: now
379003
+ });
379004
+ }
379005
+ }
379006
+ return deviations;
379007
+ }
379008
+ size() {
379009
+ return this.events.length;
379010
+ }
379011
+ clear() {
379012
+ this.events.length = 0;
379013
+ }
379014
+ };
379015
+
379016
+ // ../../packages/backend/src/services/observability.ts
379017
+ function createObservability(deps) {
379018
+ const log = deps.onLog ?? (() => {
379019
+ });
379020
+ const metricsLedger = new MetricsLedger({});
379021
+ const goldenSignals = new GoldenSignals({ ledger: metricsLedger });
379022
+ const incidentLedger = new IncidentLedger({});
379023
+ const alertService = new AlertService({ channels: deps.alertChannels ?? [] });
379024
+ const sloService = new SloService({
379025
+ source: { count: async () => ({ good: 0, total: 0 }) }
379026
+ });
379027
+ const uptimeWatchdog = new UptimeWatchdog({
379028
+ onTransition: (status, from, to) => {
379029
+ log(`[watchdog] ${status.target.name}: ${from} -> ${to}`);
379030
+ void alertService.fire({
379031
+ fingerprint: `watchdog:${status.target.name}:${to}`,
379032
+ title: `${status.target.name} is ${to}`,
379033
+ severity: to === "down" ? "critical" : "warning",
379034
+ source: "watchdog",
379035
+ detail: status.lastError,
379036
+ labels: { host: status.target.name, state: to },
379037
+ at: Date.now()
379038
+ });
379039
+ if (to === "down") {
379040
+ incidentLedger.create({
379041
+ title: `${status.target.name} down`,
379042
+ severity: "sev2",
379043
+ affected: [status.target.name],
379044
+ source: "watchdog",
379045
+ detectText: status.lastError ?? "liveness probe failed"
379046
+ });
379047
+ }
379048
+ }
379049
+ });
379050
+ const syntheticChecks = new SyntheticChecks({});
379051
+ const driftDetector = new DriftDetector({
379052
+ render: async () => "",
379053
+ getActual: async () => ""
379054
+ });
379055
+ const spanLedger = new SpanLedger({});
379056
+ const rumLedger = new RumLedger({});
379057
+ const infraMonitor = new InfraMonitor({});
379058
+ const etwService = new EtwService({});
379059
+ const dashboard = new DashboardService({
379060
+ metricsLedger,
379061
+ goldenSignals,
379062
+ sloService,
379063
+ uptimeWatchdog,
379064
+ incidentLedger,
379065
+ spanLedger,
379066
+ rumLedger,
379067
+ infraMonitor
379068
+ });
379069
+ const anomalyDetector = new AnomalyDetector(metricsLedger);
379070
+ const earlyWarning = new EarlyWarningService({
379071
+ ledger: metricsLedger,
379072
+ anomalyDetector,
379073
+ onWarning: (w) => {
379074
+ void alertService.fire({
379075
+ fingerprint: `earlywarning:${w.host}:${w.metric}:${w.kind}`,
379076
+ title: w.message,
379077
+ severity: w.kind === "anomaly" ? "warning" : "info",
379078
+ source: "early-warning",
379079
+ labels: { host: w.host, metric: w.metric, kind: w.kind },
379080
+ at: w.at
379081
+ });
379082
+ }
379083
+ });
379084
+ const behaviorLedger = new BehaviorLedger({});
379085
+ const evalHarness = new EvalHarness({
379086
+ runAgent: deps.runAgentForEval ?? (async (_prompt) => ({ answer: "", toolsCalled: [] })),
379087
+ isCommandBlocked: () => false
379088
+ });
379089
+ deps.setMonitorPublisher((channel, data) => {
379090
+ if (channel !== "monitor:snapshot" || !data || typeof data !== "object") return;
379091
+ const d = data;
379092
+ const host = d.terminalId ? String(d.terminalId) : "local";
379093
+ try {
379094
+ metricsLedger.record(host, d);
379095
+ } catch {
379096
+ }
379097
+ });
379098
+ return {
379099
+ metricsLedger,
379100
+ goldenSignals,
379101
+ sloService,
379102
+ uptimeWatchdog,
379103
+ alertService,
379104
+ incidentLedger,
379105
+ syntheticChecks,
379106
+ driftDetector,
379107
+ spanLedger,
379108
+ rumLedger,
379109
+ infraMonitor,
379110
+ etwService,
379111
+ dashboard,
379112
+ evalHarness,
379113
+ anomalyDetector,
379114
+ earlyWarning,
379115
+ behaviorLedger,
379116
+ notify: { slackChannel, teamsChannel, smtpChannel, telegramChannel }
379117
+ };
379118
+ }
379119
+
377258
379120
  // ../../packages/backend/src/services/ResourceMonitorService.ts
377259
379121
  import os6 from "os";
377260
379122
  var DEFAULT_POLL_INTERVAL_MS = 2e3;
@@ -379250,6 +381112,19 @@ async function startGyBackend() {
379250
381112
  }
379251
381113
  });
379252
381114
  agentService.setTriggerEngine(triggerEngine);
381115
+ const observability = createObservability({
381116
+ terminalService,
381117
+ agentService,
381118
+ automationManager,
381119
+ agentRunLedger,
381120
+ gatewayService,
381121
+ setMonitorPublisher: (pub) => resourceMonitorService.setPublisher((channel, data) => {
381122
+ pub(channel, data);
381123
+ }),
381124
+ onLog: () => {
381125
+ }
381126
+ });
381127
+ console.log(`[gybackend] Observability wired: dashboard state available (hosts=${observability.metricsLedger.hosts().length})`);
379253
381128
  if (settingsService.getSettings().sessionLogging?.enabled) {
379254
381129
  const logDir = path29.join(
379255
381130
  process3.env.GYSHELL_STORE_DIR || "",