mtok-relay 0.2.6 → 0.2.8

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 (3) hide show
  1. package/README.md +167 -2
  2. package/dist/mtok-relay.mjs +2517 -174
  3. package/package.json +2 -1
@@ -13,11 +13,11 @@ function anumber(n) {
13
13
  if (!Number.isSafeInteger(n) || n < 0)
14
14
  throw new Error("positive integer expected, got " + n);
15
15
  }
16
- function abytes(b, ...lengths) {
17
- if (!isBytes(b))
16
+ function abytes(b2, ...lengths) {
17
+ if (!isBytes(b2))
18
18
  throw new Error("Uint8Array expected");
19
- if (lengths.length > 0 && !lengths.includes(b.length))
20
- throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
19
+ if (lengths.length > 0 && !lengths.includes(b2.length))
20
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b2.length);
21
21
  }
22
22
  function ahash(h) {
23
23
  if (typeof h !== "function" || typeof h.create !== "function")
@@ -251,12 +251,12 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
251
251
  let v = u8n(hashLen);
252
252
  let k = u8n(hashLen);
253
253
  let i = 0;
254
- const reset = () => {
254
+ const reset2 = () => {
255
255
  v.fill(1);
256
256
  k.fill(0);
257
257
  i = 0;
258
258
  };
259
- const h = (...b) => hmacFn(k, v, ...b);
259
+ const h = (...b2) => hmacFn(k, v, ...b2);
260
260
  const reseed = (seed = u8n(0)) => {
261
261
  k = h(u8fr([0]), seed);
262
262
  v = h();
@@ -279,12 +279,12 @@ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
279
279
  return concatBytes2(...out);
280
280
  };
281
281
  const genUntil = (seed, pred) => {
282
- reset();
282
+ reset2();
283
283
  reseed(seed);
284
284
  let res = void 0;
285
285
  while (!(res = pred(gen2())))
286
286
  reseed();
287
- reset();
287
+ reset2();
288
288
  return res;
289
289
  };
290
290
  return genUntil;
@@ -338,9 +338,9 @@ var _3n = /* @__PURE__ */ BigInt(3);
338
338
  var _4n = /* @__PURE__ */ BigInt(4);
339
339
  var _5n = /* @__PURE__ */ BigInt(5);
340
340
  var _8n = /* @__PURE__ */ BigInt(8);
341
- function mod(a, b) {
342
- const result = a % b;
343
- return result >= _0n2 ? result : b + result;
341
+ function mod(a, b2) {
342
+ const result = a % b2;
343
+ return result >= _0n2 ? result : b2 + result;
344
344
  }
345
345
  function pow2(x, power, modulo) {
346
346
  let res = x;
@@ -356,16 +356,16 @@ function invert(number, modulo) {
356
356
  if (modulo <= _0n2)
357
357
  throw new Error("invert: expected positive modulus, got " + modulo);
358
358
  let a = mod(number, modulo);
359
- let b = modulo;
359
+ let b2 = modulo;
360
360
  let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
361
361
  while (a !== _0n2) {
362
- const q = b / a;
363
- const r = b % a;
362
+ const q = b2 / a;
363
+ const r = b2 % a;
364
364
  const m = x - u * q;
365
365
  const n = y - v * q;
366
- b = a, a = r, x = u, y = v, u = m, v = n;
366
+ b2 = a, a = r, x = u, y = v, u = m, v = n;
367
367
  }
368
- const gcd = b;
368
+ const gcd = b2;
369
369
  if (gcd !== _1n2)
370
370
  throw new Error("invert: does not exist");
371
371
  return mod(x, modulo);
@@ -428,11 +428,11 @@ function tonelliShanks(P) {
428
428
  throw new Error("Cannot find square root");
429
429
  }
430
430
  const exponent = _1n2 << BigInt(M - i - 1);
431
- const b = Fp.pow(c, exponent);
431
+ const b2 = Fp.pow(c, exponent);
432
432
  M = i;
433
- c = Fp.sqr(b);
433
+ c = Fp.sqr(b2);
434
434
  t = Fp.mul(t, c);
435
- R = Fp.mul(R, b);
435
+ R = Fp.mul(R, b2);
436
436
  }
437
437
  return R;
438
438
  };
@@ -579,7 +579,7 @@ function Field(ORDER, bitLen2, isLE2 = false, redef = {}) {
579
579
  invertBatch: (lst) => FpInvertBatch(f, lst),
580
580
  // We can't move this out because Fp6, Fp12 implement it
581
581
  // and it's unclear what to return in there.
582
- cmov: (a, b, c) => c ? b : a
582
+ cmov: (a, b2, c) => c ? b2 : a
583
583
  });
584
584
  return Object.freeze(f);
585
585
  }
@@ -617,11 +617,11 @@ function setBigUint64(view, byteOffset, value, isLE2) {
617
617
  view.setUint32(byteOffset + h, wh, isLE2);
618
618
  view.setUint32(byteOffset + l, wl, isLE2);
619
619
  }
620
- function Chi(a, b, c) {
621
- return a & b ^ ~a & c;
620
+ function Chi(a, b2, c) {
621
+ return a & b2 ^ ~a & c;
622
622
  }
623
- function Maj(a, b, c) {
624
- return a & b ^ a & c ^ b & c;
623
+ function Maj(a, b2, c) {
624
+ return a & b2 ^ a & c ^ b2 & c;
625
625
  }
626
626
  var HashMD = class extends Hash {
627
627
  constructor(blockLen, outputLen, padOffset, isLE2) {
@@ -641,7 +641,7 @@ var HashMD = class extends Hash {
641
641
  aexists(this);
642
642
  data = toBytes(data);
643
643
  abytes(data);
644
- const { view, buffer, blockLen } = this;
644
+ const { view, buffer: buffer2, blockLen } = this;
645
645
  const len = data.length;
646
646
  for (let pos = 0; pos < len; ) {
647
647
  const take = Math.min(blockLen - this.pos, len - pos);
@@ -651,7 +651,7 @@ var HashMD = class extends Hash {
651
651
  this.process(dataView, pos);
652
652
  continue;
653
653
  }
654
- buffer.set(data.subarray(pos, pos + take), this.pos);
654
+ buffer2.set(data.subarray(pos, pos + take), this.pos);
655
655
  this.pos += take;
656
656
  pos += take;
657
657
  if (this.pos === blockLen) {
@@ -667,16 +667,16 @@ var HashMD = class extends Hash {
667
667
  aexists(this);
668
668
  aoutput(out, this);
669
669
  this.finished = true;
670
- const { buffer, view, blockLen, isLE: isLE2 } = this;
670
+ const { buffer: buffer2, view, blockLen, isLE: isLE2 } = this;
671
671
  let { pos } = this;
672
- buffer[pos++] = 128;
672
+ buffer2[pos++] = 128;
673
673
  clean(this.buffer.subarray(pos));
674
674
  if (this.padOffset > blockLen - pos) {
675
675
  this.process(view, 0);
676
676
  pos = 0;
677
677
  }
678
678
  for (let i = pos; i < blockLen; i++)
679
- buffer[i] = 0;
679
+ buffer2[i] = 0;
680
680
  setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2);
681
681
  this.process(view, 0);
682
682
  const oview = createView(out);
@@ -691,22 +691,22 @@ var HashMD = class extends Hash {
691
691
  oview.setUint32(4 * i, state[i], isLE2);
692
692
  }
693
693
  digest() {
694
- const { buffer, outputLen } = this;
695
- this.digestInto(buffer);
696
- const res = buffer.slice(0, outputLen);
694
+ const { buffer: buffer2, outputLen } = this;
695
+ this.digestInto(buffer2);
696
+ const res = buffer2.slice(0, outputLen);
697
697
  this.destroy();
698
698
  return res;
699
699
  }
700
700
  _cloneInto(to) {
701
701
  to || (to = new this.constructor());
702
702
  to.set(...this.get());
703
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
703
+ const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this;
704
704
  to.destroyed = destroyed;
705
705
  to.finished = finished;
706
706
  to.length = length;
707
707
  to.pos = pos;
708
708
  if (length % blockLen)
709
- to.buffer.set(buffer);
709
+ to.buffer.set(buffer2);
710
710
  return to;
711
711
  }
712
712
  clone() {
@@ -1269,8 +1269,8 @@ var DER = {
1269
1269
  throw new E("tlv.decode: length bytes not complete");
1270
1270
  if (lengthBytes[0] === 0)
1271
1271
  throw new E("tlv.decode(long): zero leftmost byte");
1272
- for (const b of lengthBytes)
1273
- length = length << 8 | b;
1272
+ for (const b2 of lengthBytes)
1273
+ length = length << 8 | b2;
1274
1274
  pos += lenLen;
1275
1275
  if (length < 128)
1276
1276
  throw new E("tlv.decode(long): not minimal encoding");
@@ -1326,8 +1326,8 @@ var DER = {
1326
1326
  return tlv.encode(48, seq);
1327
1327
  }
1328
1328
  };
1329
- function numToSizedHex(num, size2) {
1330
- return bytesToHex(numberToBytesBE(num, size2));
1329
+ function numToSizedHex(num, size3) {
1330
+ return bytesToHex(numberToBytesBE(num, size3));
1331
1331
  }
1332
1332
  var _0n4 = BigInt(0);
1333
1333
  var _1n4 = BigInt(1);
@@ -1349,10 +1349,10 @@ function weierstrassPoints(opts) {
1349
1349
  return { x, y };
1350
1350
  });
1351
1351
  function weierstrassEquation(x) {
1352
- const { a, b } = CURVE;
1352
+ const { a, b: b2 } = CURVE;
1353
1353
  const x2 = Fp.sqr(x);
1354
1354
  const x3 = Fp.mul(x2, x);
1355
- return Fp.add(Fp.add(x3, Fp.mul(x, a)), b);
1355
+ return Fp.add(Fp.add(x3, Fp.mul(x, a)), b2);
1356
1356
  }
1357
1357
  function isValidXY(x, y) {
1358
1358
  const left = Fp.sqr(y);
@@ -1518,8 +1518,8 @@ function weierstrassPoints(opts) {
1518
1518
  // https://eprint.iacr.org/2015/1060, algorithm 3
1519
1519
  // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
1520
1520
  double() {
1521
- const { a, b } = CURVE;
1522
- const b3 = Fp.mul(b, _3n2);
1521
+ const { a, b: b2 } = CURVE;
1522
+ const b3 = Fp.mul(b2, _3n2);
1523
1523
  const { px: X1, py: Y1, pz: Z1 } = this;
1524
1524
  let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
1525
1525
  let t0 = Fp.mul(X1, X1);
@@ -1687,10 +1687,10 @@ function weierstrassPoints(opts) {
1687
1687
  * The trick could be useful if both P and Q are not G (not in our case).
1688
1688
  * @returns non-zero affine point
1689
1689
  */
1690
- multiplyAndAddUnsafe(Q, a, b) {
1690
+ multiplyAndAddUnsafe(Q, a, b2) {
1691
1691
  const G = Point.BASE;
1692
1692
  const mul = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2);
1693
- const sum = mul(this, a).add(mul(Q, b));
1693
+ const sum = mul(this, a).add(mul(Q, b2));
1694
1694
  return sum.is0() ? void 0 : sum;
1695
1695
  }
1696
1696
  // Converts Projective point to affine (x, y) coordinates.
@@ -1813,7 +1813,7 @@ function weierstrass(curveDef) {
1813
1813
  function normalizeS(s) {
1814
1814
  return isBiggerThanHalfOrder(s) ? modN(-s) : s;
1815
1815
  }
1816
- const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
1816
+ const slcNum = (b2, from, to) => bytesToNumberBE(b2.slice(from, to));
1817
1817
  class Signature {
1818
1818
  constructor(r, s, recovery) {
1819
1819
  aInRange("r", r, _1n4, CURVE_ORDER);
@@ -1943,8 +1943,8 @@ function weierstrass(curveDef) {
1943
1943
  throw new Error("first arg must be private key");
1944
1944
  if (isProbPub(publicB) === false)
1945
1945
  throw new Error("second arg must be public key");
1946
- const b = Point.fromHex(publicB);
1947
- return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
1946
+ const b2 = Point.fromHex(publicB);
1947
+ return b2.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
1948
1948
  }
1949
1949
  const bits2int = CURVE.bits2int || function(bytes) {
1950
1950
  if (bytes.length > 8192)
@@ -2094,7 +2094,7 @@ var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25
2094
2094
  var _0n5 = BigInt(0);
2095
2095
  var _1n5 = BigInt(1);
2096
2096
  var _2n3 = BigInt(2);
2097
- var divNearest = (a, b) => (a + b / _2n3) / b;
2097
+ var divNearest = (a, b2) => (a + b2 / _2n3) / b2;
2098
2098
  function sqrtMod(y) {
2099
2099
  const P = secp256k1P;
2100
2100
  const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
@@ -2245,8 +2245,8 @@ function walk(err, fn) {
2245
2245
 
2246
2246
  // node_modules/viem/_esm/errors/encoding.js
2247
2247
  var IntegerOutOfRangeError = class extends BaseError {
2248
- constructor({ max, min, signed, size: size2, value }) {
2249
- super(`Number "${value}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" });
2248
+ constructor({ max, min, signed, size: size3, value }) {
2249
+ super(`Number "${value}" is not in safe ${size3 ? `${size3 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" });
2250
2250
  }
2251
2251
  };
2252
2252
  var SizeOverflowError = class extends BaseError {
@@ -2257,47 +2257,47 @@ var SizeOverflowError = class extends BaseError {
2257
2257
 
2258
2258
  // node_modules/viem/_esm/errors/data.js
2259
2259
  var SliceOffsetOutOfBoundsError = class extends BaseError {
2260
- constructor({ offset, position, size: size2 }) {
2261
- super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size2}).`, { name: "SliceOffsetOutOfBoundsError" });
2260
+ constructor({ offset, position, size: size3 }) {
2261
+ super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size3}).`, { name: "SliceOffsetOutOfBoundsError" });
2262
2262
  }
2263
2263
  };
2264
2264
  var SizeExceedsPaddingSizeError = class extends BaseError {
2265
- constructor({ size: size2, targetSize, type }) {
2266
- super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" });
2265
+ constructor({ size: size3, targetSize, type }) {
2266
+ super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size3}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" });
2267
2267
  }
2268
2268
  };
2269
2269
 
2270
2270
  // node_modules/viem/_esm/utils/data/pad.js
2271
- function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) {
2271
+ function pad(hexOrBytes, { dir, size: size3 = 32 } = {}) {
2272
2272
  if (typeof hexOrBytes === "string")
2273
- return padHex(hexOrBytes, { dir, size: size2 });
2274
- return padBytes(hexOrBytes, { dir, size: size2 });
2273
+ return padHex(hexOrBytes, { dir, size: size3 });
2274
+ return padBytes(hexOrBytes, { dir, size: size3 });
2275
2275
  }
2276
- function padHex(hex_, { dir, size: size2 = 32 } = {}) {
2277
- if (size2 === null)
2276
+ function padHex(hex_, { dir, size: size3 = 32 } = {}) {
2277
+ if (size3 === null)
2278
2278
  return hex_;
2279
2279
  const hex = hex_.replace("0x", "");
2280
- if (hex.length > size2 * 2)
2280
+ if (hex.length > size3 * 2)
2281
2281
  throw new SizeExceedsPaddingSizeError({
2282
2282
  size: Math.ceil(hex.length / 2),
2283
- targetSize: size2,
2283
+ targetSize: size3,
2284
2284
  type: "hex"
2285
2285
  });
2286
- return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0")}`;
2286
+ return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size3 * 2, "0")}`;
2287
2287
  }
2288
- function padBytes(bytes, { dir, size: size2 = 32 } = {}) {
2289
- if (size2 === null)
2288
+ function padBytes(bytes, { dir, size: size3 = 32 } = {}) {
2289
+ if (size3 === null)
2290
2290
  return bytes;
2291
- if (bytes.length > size2)
2291
+ if (bytes.length > size3)
2292
2292
  throw new SizeExceedsPaddingSizeError({
2293
2293
  size: bytes.length,
2294
- targetSize: size2,
2294
+ targetSize: size3,
2295
2295
  type: "bytes"
2296
2296
  });
2297
- const paddedBytes = new Uint8Array(size2);
2298
- for (let i = 0; i < size2; i++) {
2297
+ const paddedBytes = new Uint8Array(size3);
2298
+ for (let i = 0; i < size3; i++) {
2299
2299
  const padEnd = dir === "right";
2300
- paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
2300
+ paddedBytes[padEnd ? i : size3 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
2301
2301
  }
2302
2302
  return paddedBytes;
2303
2303
  }
@@ -2409,11 +2409,11 @@ function stringToBytes(value, opts = {}) {
2409
2409
  }
2410
2410
 
2411
2411
  // node_modules/viem/_esm/utils/encoding/fromHex.js
2412
- function assertSize(hexOrBytes, { size: size2 }) {
2413
- if (size(hexOrBytes) > size2)
2412
+ function assertSize(hexOrBytes, { size: size3 }) {
2413
+ if (size(hexOrBytes) > size3)
2414
2414
  throw new SizeOverflowError({
2415
2415
  givenSize: size(hexOrBytes),
2416
- maxSize: size2
2416
+ maxSize: size3
2417
2417
  });
2418
2418
  }
2419
2419
  function hexToBigInt(hex, opts = {}) {
@@ -2423,11 +2423,11 @@ function hexToBigInt(hex, opts = {}) {
2423
2423
  const value = BigInt(hex);
2424
2424
  if (!signed)
2425
2425
  return value;
2426
- const size2 = Math.ceil((hex.length - 2) / 2);
2427
- const max = (1n << BigInt(size2) * 8n - 1n) - 1n;
2426
+ const size3 = Math.ceil((hex.length - 2) / 2);
2427
+ const max = (1n << BigInt(size3) * 8n - 1n) - 1n;
2428
2428
  if (value <= max)
2429
2429
  return value;
2430
- return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n;
2430
+ return value - BigInt(`0x${"f".padStart(size3 * 2, "f")}`) - 1n;
2431
2431
  }
2432
2432
  function hexToNumber2(hex, opts = {}) {
2433
2433
  const value = hexToBigInt(hex, opts);
@@ -2476,14 +2476,14 @@ function bytesToHex2(value, opts = {}) {
2476
2476
  return hex;
2477
2477
  }
2478
2478
  function numberToHex(value_, opts = {}) {
2479
- const { signed, size: size2 } = opts;
2479
+ const { signed, size: size3 } = opts;
2480
2480
  const value = BigInt(value_);
2481
2481
  let maxValue;
2482
- if (size2) {
2482
+ if (size3) {
2483
2483
  if (signed)
2484
- maxValue = (1n << BigInt(size2) * 8n - 1n) - 1n;
2484
+ maxValue = (1n << BigInt(size3) * 8n - 1n) - 1n;
2485
2485
  else
2486
- maxValue = 2n ** (BigInt(size2) * 8n) - 1n;
2486
+ maxValue = 2n ** (BigInt(size3) * 8n) - 1n;
2487
2487
  } else if (typeof value_ === "number") {
2488
2488
  maxValue = BigInt(Number.MAX_SAFE_INTEGER);
2489
2489
  }
@@ -2494,13 +2494,13 @@ function numberToHex(value_, opts = {}) {
2494
2494
  max: maxValue ? `${maxValue}${suffix}` : void 0,
2495
2495
  min: `${minValue}${suffix}`,
2496
2496
  signed,
2497
- size: size2,
2497
+ size: size3,
2498
2498
  value: `${value_}${suffix}`
2499
2499
  });
2500
2500
  }
2501
- const hex = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`;
2502
- if (size2)
2503
- return pad(hex, { size: size2 });
2501
+ const hex = `0x${(signed && value < 0 ? (1n << BigInt(size3 * 8)) + BigInt(value) : value).toString(16)}`;
2502
+ if (size3)
2503
+ return pad(hex, { size: size3 });
2504
2504
  return hex;
2505
2505
  }
2506
2506
  var encoder2 = /* @__PURE__ */ new TextEncoder();
@@ -2511,7 +2511,7 @@ function stringToHex(value_, opts = {}) {
2511
2511
 
2512
2512
  // node_modules/viem/_esm/utils/lru.js
2513
2513
  var LruMap = class extends Map {
2514
- constructor(size2) {
2514
+ constructor(size3) {
2515
2515
  super();
2516
2516
  Object.defineProperty(this, "maxSize", {
2517
2517
  enumerable: true,
@@ -2519,7 +2519,7 @@ var LruMap = class extends Map {
2519
2519
  writable: true,
2520
2520
  value: void 0
2521
2521
  });
2522
- this.maxSize = size2;
2522
+ this.maxSize = size3;
2523
2523
  }
2524
2524
  get(key) {
2525
2525
  const value = super.get(key);
@@ -2854,26 +2854,26 @@ async function sign({ hash, privateKey, to = "object" }) {
2854
2854
  }
2855
2855
 
2856
2856
  // node_modules/viem/_esm/utils/data/concat.js
2857
- function concat(values) {
2858
- if (typeof values[0] === "string")
2859
- return concatHex(values);
2860
- return concatBytes3(values);
2857
+ function concat(values2) {
2858
+ if (typeof values2[0] === "string")
2859
+ return concatHex(values2);
2860
+ return concatBytes3(values2);
2861
2861
  }
2862
- function concatBytes3(values) {
2862
+ function concatBytes3(values2) {
2863
2863
  let length = 0;
2864
- for (const arr of values) {
2864
+ for (const arr of values2) {
2865
2865
  length += arr.length;
2866
2866
  }
2867
2867
  const result = new Uint8Array(length);
2868
2868
  let offset = 0;
2869
- for (const arr of values) {
2869
+ for (const arr of values2) {
2870
2870
  result.set(arr, offset);
2871
2871
  offset += arr.length;
2872
2872
  }
2873
2873
  return result;
2874
2874
  }
2875
- function concatHex(values) {
2876
- return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`;
2875
+ function concatHex(values2) {
2876
+ return `0x${values2.reduce((acc, x) => acc + x.replace("0x", ""), "")}`;
2877
2877
  }
2878
2878
 
2879
2879
  // node_modules/viem/_esm/errors/cursor.js
@@ -3002,11 +3002,11 @@ var staticCursor = {
3002
3002
  this.position++;
3003
3003
  return value;
3004
3004
  },
3005
- readBytes(length, size2) {
3005
+ readBytes(length, size3) {
3006
3006
  this.assertReadLimit();
3007
3007
  this._touch();
3008
3008
  const value = this.inspectBytes(length);
3009
- this.position += size2 ?? length;
3009
+ this.position += size3 ?? length;
3010
3010
  return value;
3011
3011
  },
3012
3012
  readUint8() {
@@ -3396,9 +3396,9 @@ var versionedHashVersionKzg = 1;
3396
3396
 
3397
3397
  // node_modules/viem/_esm/errors/blob.js
3398
3398
  var BlobSizeTooLargeError = class extends BaseError {
3399
- constructor({ maxSize, size: size2 }) {
3399
+ constructor({ maxSize, size: size3 }) {
3400
3400
  super("Blob size is too large.", {
3401
- metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size2} bytes`],
3401
+ metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size3} bytes`],
3402
3402
  name: "BlobSizeTooLargeError"
3403
3403
  });
3404
3404
  }
@@ -3409,9 +3409,9 @@ var EmptyBlobError = class extends BaseError {
3409
3409
  }
3410
3410
  };
3411
3411
  var InvalidVersionedHashSizeError = class extends BaseError {
3412
- constructor({ hash, size: size2 }) {
3412
+ constructor({ hash, size: size3 }) {
3413
3413
  super(`Versioned hash "${hash}" size is invalid.`, {
3414
- metaMessages: ["Expected: 32", `Received: ${size2}`],
3414
+ metaMessages: ["Expected: 32", `Received: ${size3}`],
3415
3415
  name: "InvalidVersionedHashSizeError"
3416
3416
  });
3417
3417
  }
@@ -3445,8 +3445,8 @@ function toBlobs(parameters) {
3445
3445
  let position = 0;
3446
3446
  while (active) {
3447
3447
  const blob = createCursor(new Uint8Array(bytesPerBlob));
3448
- let size2 = 0;
3449
- while (size2 < fieldElementsPerBlob) {
3448
+ let size3 = 0;
3449
+ while (size3 < fieldElementsPerBlob) {
3450
3450
  const bytes = data.slice(position, position + (bytesPerFieldElement - 1));
3451
3451
  blob.pushByte(0);
3452
3452
  blob.pushBytes(bytes);
@@ -3455,7 +3455,7 @@ function toBlobs(parameters) {
3455
3455
  active = false;
3456
3456
  break;
3457
3457
  }
3458
- size2++;
3458
+ size3++;
3459
3459
  position += 31;
3460
3460
  }
3461
3461
  blobs.push(blob);
@@ -4174,22 +4174,22 @@ var bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;
4174
4174
  var integerRegex = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;
4175
4175
 
4176
4176
  // node_modules/viem/_esm/utils/abi/encodeAbiParameters.js
4177
- function encodeAbiParameters(params, values) {
4178
- if (params.length !== values.length)
4177
+ function encodeAbiParameters(params, values2) {
4178
+ if (params.length !== values2.length)
4179
4179
  throw new AbiEncodingLengthMismatchError({
4180
4180
  expectedLength: params.length,
4181
- givenLength: values.length
4181
+ givenLength: values2.length
4182
4182
  });
4183
4183
  const preparedParams = prepareParams({
4184
4184
  params,
4185
- values
4185
+ values: values2
4186
4186
  });
4187
4187
  return encodeParams(preparedParams);
4188
4188
  }
4189
- function prepareParams({ params, values }) {
4189
+ function prepareParams({ params, values: values2 }) {
4190
4190
  const preparedParams = [];
4191
4191
  for (let i = 0; i < params.length; i++) {
4192
- preparedParams.push(prepareParam({ param: params[i], value: values[i] }));
4192
+ preparedParams.push(prepareParam({ param: params[i], value: values2[i] }));
4193
4193
  }
4194
4194
  return preparedParams;
4195
4195
  }
@@ -4212,10 +4212,10 @@ function prepareParam({ param, value }) {
4212
4212
  }
4213
4213
  if (param.type.startsWith("uint") || param.type.startsWith("int")) {
4214
4214
  const signed = param.type.startsWith("int");
4215
- const [, , size2 = "256"] = integerRegex.exec(param.type) ?? [];
4215
+ const [, , size3 = "256"] = integerRegex.exec(param.type) ?? [];
4216
4216
  return encodeNumber(value, {
4217
4217
  signed,
4218
- size: Number(size2)
4218
+ size: Number(size3)
4219
4219
  });
4220
4220
  }
4221
4221
  if (param.type.startsWith("bytes")) {
@@ -4322,16 +4322,16 @@ function encodeBool(value) {
4322
4322
  throw new BaseError(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`);
4323
4323
  return { dynamic: false, encoded: padHex(boolToHex(value)) };
4324
4324
  }
4325
- function encodeNumber(value, { signed, size: size2 = 256 }) {
4326
- if (typeof size2 === "number") {
4327
- const max = 2n ** (BigInt(size2) - (signed ? 1n : 0n)) - 1n;
4325
+ function encodeNumber(value, { signed, size: size3 = 256 }) {
4326
+ if (typeof size3 === "number") {
4327
+ const max = 2n ** (BigInt(size3) - (signed ? 1n : 0n)) - 1n;
4328
4328
  const min = signed ? -max - 1n : 0n;
4329
4329
  if (value > max || value < min)
4330
4330
  throw new IntegerOutOfRangeError({
4331
4331
  max: max.toString(),
4332
4332
  min: min.toString(),
4333
4333
  signed,
4334
- size: size2 / 8,
4334
+ size: size3 / 8,
4335
4335
  value: value.toString()
4336
4336
  });
4337
4337
  }
@@ -4417,8 +4417,8 @@ var InvalidDomainError = class extends BaseError {
4417
4417
  }
4418
4418
  };
4419
4419
  var InvalidPrimaryTypeError = class extends BaseError {
4420
- constructor({ primaryType, types }) {
4421
- super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, {
4420
+ constructor({ primaryType, types: types2 }) {
4421
+ super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types2))}\`.`, {
4422
4422
  docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror",
4423
4423
  metaMessages: ["Check that the primary type is a key in `types`."]
4424
4424
  });
@@ -4444,7 +4444,7 @@ var InvalidTypedDataTypeError = class extends BaseError {
4444
4444
 
4445
4445
  // node_modules/viem/_esm/utils/typedData.js
4446
4446
  function validateTypedData(parameters) {
4447
- const { domain, message, primaryType, types } = parameters;
4447
+ const { domain, message, primaryType, types: types2 } = parameters;
4448
4448
  const validateData = (struct, data) => {
4449
4449
  for (const param of struct) {
4450
4450
  const { name, type } = param;
@@ -4471,23 +4471,23 @@ function validateTypedData(parameters) {
4471
4471
  givenSize: size(value)
4472
4472
  });
4473
4473
  }
4474
- const struct2 = types[type];
4474
+ const struct2 = types2[type];
4475
4475
  if (struct2) {
4476
4476
  validateReference(type);
4477
4477
  validateData(struct2, value);
4478
4478
  }
4479
4479
  }
4480
4480
  };
4481
- if (types.EIP712Domain && domain) {
4481
+ if (types2.EIP712Domain && domain) {
4482
4482
  if (typeof domain !== "object")
4483
4483
  throw new InvalidDomainError({ domain });
4484
- validateData(types.EIP712Domain, domain);
4484
+ validateData(types2.EIP712Domain, domain);
4485
4485
  }
4486
4486
  if (primaryType !== "EIP712Domain") {
4487
- if (types[primaryType])
4488
- validateData(types[primaryType], message);
4487
+ if (types2[primaryType])
4488
+ validateData(types2[primaryType], message);
4489
4489
  else
4490
- throw new InvalidPrimaryTypeError({ primaryType, types });
4490
+ throw new InvalidPrimaryTypeError({ primaryType, types: types2 });
4491
4491
  }
4492
4492
  }
4493
4493
  function getTypesForEIP712Domain({ domain }) {
@@ -4513,7 +4513,7 @@ function validateReference(type) {
4513
4513
  // node_modules/viem/_esm/utils/signature/hashTypedData.js
4514
4514
  function hashTypedData(parameters) {
4515
4515
  const { domain = {}, message, primaryType } = parameters;
4516
- const types = {
4516
+ const types2 = {
4517
4517
  EIP712Domain: getTypesForEIP712Domain({ domain }),
4518
4518
  ...parameters.types
4519
4519
  };
@@ -4521,43 +4521,43 @@ function hashTypedData(parameters) {
4521
4521
  domain,
4522
4522
  message,
4523
4523
  primaryType,
4524
- types
4524
+ types: types2
4525
4525
  });
4526
4526
  const parts = ["0x1901"];
4527
4527
  if (domain)
4528
4528
  parts.push(hashDomain({
4529
4529
  domain,
4530
- types
4530
+ types: types2
4531
4531
  }));
4532
4532
  if (primaryType !== "EIP712Domain")
4533
4533
  parts.push(hashStruct({
4534
4534
  data: message,
4535
4535
  primaryType,
4536
- types
4536
+ types: types2
4537
4537
  }));
4538
4538
  return keccak256(concat(parts));
4539
4539
  }
4540
- function hashDomain({ domain, types }) {
4540
+ function hashDomain({ domain, types: types2 }) {
4541
4541
  return hashStruct({
4542
4542
  data: domain,
4543
4543
  primaryType: "EIP712Domain",
4544
- types
4544
+ types: types2
4545
4545
  });
4546
4546
  }
4547
- function hashStruct({ data, primaryType, types }) {
4547
+ function hashStruct({ data, primaryType, types: types2 }) {
4548
4548
  const encoded = encodeData({
4549
4549
  data,
4550
4550
  primaryType,
4551
- types
4551
+ types: types2
4552
4552
  });
4553
4553
  return keccak256(encoded);
4554
4554
  }
4555
- function encodeData({ data, primaryType, types }) {
4555
+ function encodeData({ data, primaryType, types: types2 }) {
4556
4556
  const encodedTypes = [{ type: "bytes32" }];
4557
- const encodedValues = [hashType({ primaryType, types })];
4558
- for (const field of types[primaryType]) {
4557
+ const encodedValues = [hashType({ primaryType, types: types2 })];
4558
+ for (const field of types2[primaryType]) {
4559
4559
  const [type, value] = encodeField({
4560
- types,
4560
+ types: types2,
4561
4561
  name: field.name,
4562
4562
  type: field.type,
4563
4563
  value: data[field.name]
@@ -4567,37 +4567,37 @@ function encodeData({ data, primaryType, types }) {
4567
4567
  }
4568
4568
  return encodeAbiParameters(encodedTypes, encodedValues);
4569
4569
  }
4570
- function hashType({ primaryType, types }) {
4571
- const encodedHashType = toHex(encodeType({ primaryType, types }));
4570
+ function hashType({ primaryType, types: types2 }) {
4571
+ const encodedHashType = toHex(encodeType({ primaryType, types: types2 }));
4572
4572
  return keccak256(encodedHashType);
4573
4573
  }
4574
- function encodeType({ primaryType, types }) {
4574
+ function encodeType({ primaryType, types: types2 }) {
4575
4575
  let result = "";
4576
- const unsortedDeps = findTypeDependencies({ primaryType, types });
4576
+ const unsortedDeps = findTypeDependencies({ primaryType, types: types2 });
4577
4577
  unsortedDeps.delete(primaryType);
4578
4578
  const deps = [primaryType, ...Array.from(unsortedDeps).sort()];
4579
4579
  for (const type of deps) {
4580
- result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`;
4580
+ result += `${type}(${types2[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`;
4581
4581
  }
4582
4582
  return result;
4583
4583
  }
4584
- function findTypeDependencies({ primaryType: primaryType_, types }, results = /* @__PURE__ */ new Set()) {
4584
+ function findTypeDependencies({ primaryType: primaryType_, types: types2 }, results = /* @__PURE__ */ new Set()) {
4585
4585
  const match = primaryType_.match(/^\w*/u);
4586
4586
  const primaryType = match?.[0];
4587
- if (results.has(primaryType) || types[primaryType] === void 0) {
4587
+ if (results.has(primaryType) || types2[primaryType] === void 0) {
4588
4588
  return results;
4589
4589
  }
4590
4590
  results.add(primaryType);
4591
- for (const field of types[primaryType]) {
4592
- findTypeDependencies({ primaryType: field.type, types }, results);
4591
+ for (const field of types2[primaryType]) {
4592
+ findTypeDependencies({ primaryType: field.type, types: types2 }, results);
4593
4593
  }
4594
4594
  return results;
4595
4595
  }
4596
- function encodeField({ types, name, type, value }) {
4597
- if (types[type] !== void 0) {
4596
+ function encodeField({ types: types2, name, type, value }) {
4597
+ if (types2[type] !== void 0) {
4598
4598
  return [
4599
4599
  { type: "bytes32" },
4600
- keccak256(encodeData({ data: value, primaryType: type, types }))
4600
+ keccak256(encodeData({ data: value, primaryType: type, types: types2 }))
4601
4601
  ];
4602
4602
  }
4603
4603
  if (type === "bytes")
@@ -4609,7 +4609,7 @@ function encodeField({ types, name, type, value }) {
4609
4609
  const typeValuePairs = value.map((item) => encodeField({
4610
4610
  name,
4611
4611
  type: parsedType,
4612
- types,
4612
+ types: types2,
4613
4613
  value: item
4614
4614
  }));
4615
4615
  return [
@@ -4681,6 +4681,13 @@ function readRelayConfig({ argv = process.argv.slice(2), env = process.env } = {
4681
4681
  const redemptionFlag = flag(argv, "--redemption-file") ?? env.RELAY_REDEMPTION_FILE;
4682
4682
  if (redemptionFlag === "") throw new Error("--redemption-file cannot be empty; paid serves require durable redemption");
4683
4683
  const redemptionFile = redemptionFlag === void 0 ? "./.mtok-redemption.jsonl" : redemptionFlag;
4684
+ const redemptionDatabaseUrl = env.RELAY_REDEMPTION_DATABASE_URL;
4685
+ if (redemptionDatabaseUrl !== void 0) {
4686
+ if (!["postgres:", "postgresql:"].includes(new URL(redemptionDatabaseUrl).protocol)) {
4687
+ throw new Error("RELAY_REDEMPTION_DATABASE_URL must use PostgreSQL");
4688
+ }
4689
+ if (redemptionFlag !== void 0) throw new Error("choose PostgreSQL or a redemption file, not both");
4690
+ }
4684
4691
  const denylistRaw = flag(argv, "--payer-denylist") ?? env.RELAY_PAYER_DENYLIST ?? "";
4685
4692
  const payerDenylist = String(denylistRaw).split(",").map((a) => a.trim().toLowerCase()).filter(Boolean);
4686
4693
  const maxOutputRaw = flag(argv, "--max-output-tokens") ?? env.RELAY_MAX_OUTPUT_TOKENS;
@@ -4732,6 +4739,7 @@ function readRelayConfig({ argv = process.argv.slice(2), env = process.env } = {
4732
4739
  outPrice,
4733
4740
  inPrice,
4734
4741
  redemptionFile,
4742
+ redemptionDatabaseUrl,
4735
4743
  mtokApiKey,
4736
4744
  upstreamKey,
4737
4745
  settlementAddr,
@@ -4793,11 +4801,11 @@ function readBody(req, { maxBytes = MAX_BODY_BYTES, timeoutMs = 1e4 } = {}) {
4793
4801
  const fail = (error) => {
4794
4802
  if (settled) return;
4795
4803
  settled = true;
4796
- clearTimeout(timer);
4804
+ clearTimeout(timer2);
4797
4805
  chunks.length = 0;
4798
4806
  reject(error);
4799
4807
  };
4800
- const timer = setTimeout(() => fail(Object.assign(new Error("body_timeout"), { code: "body_timeout" })), timeoutMs);
4808
+ const timer2 = setTimeout(() => fail(Object.assign(new Error("body_timeout"), { code: "body_timeout" })), timeoutMs);
4801
4809
  req.on("data", (d) => {
4802
4810
  bytes += d.length;
4803
4811
  if (bytes > maxBytes && !settled) {
@@ -4811,7 +4819,7 @@ function readBody(req, { maxBytes = MAX_BODY_BYTES, timeoutMs = 1e4 } = {}) {
4811
4819
  req.on("end", () => {
4812
4820
  if (settled) return;
4813
4821
  settled = true;
4814
- clearTimeout(timer);
4822
+ clearTimeout(timer2);
4815
4823
  const raw = Buffer.concat(chunks).toString("utf8");
4816
4824
  try {
4817
4825
  resolve(JSON.parse(raw || "{}"));
@@ -5065,6 +5073,2289 @@ function createRedemptionStore({ file = null, retentionMs = DEFAULT_RETENTION_MS
5065
5073
  };
5066
5074
  }
5067
5075
 
5076
+ // src/postgres-redemption.mjs
5077
+ import { createHash } from "node:crypto";
5078
+
5079
+ // node_modules/postgres/src/index.js
5080
+ import os from "os";
5081
+ import fs2 from "fs";
5082
+
5083
+ // node_modules/postgres/src/query.js
5084
+ var originCache = /* @__PURE__ */ new Map();
5085
+ var originStackCache = /* @__PURE__ */ new Map();
5086
+ var originError = /* @__PURE__ */ Symbol("OriginError");
5087
+ var CLOSE = {};
5088
+ var Query = class extends Promise {
5089
+ constructor(strings, args, handler, canceller, options = {}) {
5090
+ let resolve, reject;
5091
+ super((a, b2) => {
5092
+ resolve = a;
5093
+ reject = b2;
5094
+ });
5095
+ this.tagged = Array.isArray(strings.raw);
5096
+ this.strings = strings;
5097
+ this.args = args;
5098
+ this.handler = handler;
5099
+ this.canceller = canceller;
5100
+ this.options = options;
5101
+ this.state = null;
5102
+ this.statement = null;
5103
+ this.resolve = (x) => (this.active = false, resolve(x));
5104
+ this.reject = (x) => (this.active = false, reject(x));
5105
+ this.active = false;
5106
+ this.cancelled = null;
5107
+ this.executed = false;
5108
+ this.signature = "";
5109
+ this[originError] = this.handler.debug ? new Error() : this.tagged && cachedError(this.strings);
5110
+ }
5111
+ get origin() {
5112
+ return (this.handler.debug ? this[originError].stack : this.tagged && originStackCache.has(this.strings) ? originStackCache.get(this.strings) : originStackCache.set(this.strings, this[originError].stack).get(this.strings)) || "";
5113
+ }
5114
+ static get [Symbol.species]() {
5115
+ return Promise;
5116
+ }
5117
+ cancel() {
5118
+ return this.canceller && (this.canceller(this), this.canceller = null);
5119
+ }
5120
+ simple() {
5121
+ this.options.simple = true;
5122
+ this.options.prepare = false;
5123
+ return this;
5124
+ }
5125
+ async readable() {
5126
+ this.simple();
5127
+ this.streaming = true;
5128
+ return this;
5129
+ }
5130
+ async writable() {
5131
+ this.simple();
5132
+ this.streaming = true;
5133
+ return this;
5134
+ }
5135
+ cursor(rows = 1, fn) {
5136
+ this.options.simple = false;
5137
+ if (typeof rows === "function") {
5138
+ fn = rows;
5139
+ rows = 1;
5140
+ }
5141
+ this.cursorRows = rows;
5142
+ if (typeof fn === "function")
5143
+ return this.cursorFn = fn, this;
5144
+ let prev;
5145
+ return {
5146
+ [Symbol.asyncIterator]: () => ({
5147
+ next: () => {
5148
+ if (this.executed && !this.active)
5149
+ return { done: true };
5150
+ prev && prev();
5151
+ const promise = new Promise((resolve, reject) => {
5152
+ this.cursorFn = (value) => {
5153
+ resolve({ value, done: false });
5154
+ return new Promise((r) => prev = r);
5155
+ };
5156
+ this.resolve = () => (this.active = false, resolve({ done: true }));
5157
+ this.reject = (x) => (this.active = false, reject(x));
5158
+ });
5159
+ this.execute();
5160
+ return promise;
5161
+ },
5162
+ return() {
5163
+ prev && prev(CLOSE);
5164
+ return { done: true };
5165
+ }
5166
+ })
5167
+ };
5168
+ }
5169
+ describe() {
5170
+ this.options.simple = false;
5171
+ this.onlyDescribe = this.options.prepare = true;
5172
+ return this;
5173
+ }
5174
+ stream() {
5175
+ throw new Error(".stream has been renamed to .forEach");
5176
+ }
5177
+ forEach(fn) {
5178
+ this.forEachFn = fn;
5179
+ this.handle();
5180
+ return this;
5181
+ }
5182
+ raw() {
5183
+ this.isRaw = true;
5184
+ return this;
5185
+ }
5186
+ values() {
5187
+ this.isRaw = "values";
5188
+ return this;
5189
+ }
5190
+ async handle() {
5191
+ !this.executed && (this.executed = true) && await 1 && this.handler(this);
5192
+ }
5193
+ execute() {
5194
+ this.handle();
5195
+ return this;
5196
+ }
5197
+ then() {
5198
+ this.handle();
5199
+ return super.then.apply(this, arguments);
5200
+ }
5201
+ catch() {
5202
+ this.handle();
5203
+ return super.catch.apply(this, arguments);
5204
+ }
5205
+ finally() {
5206
+ this.handle();
5207
+ return super.finally.apply(this, arguments);
5208
+ }
5209
+ };
5210
+ function cachedError(xs) {
5211
+ if (originCache.has(xs))
5212
+ return originCache.get(xs);
5213
+ const x = Error.stackTraceLimit;
5214
+ Error.stackTraceLimit = 4;
5215
+ originCache.set(xs, new Error());
5216
+ Error.stackTraceLimit = x;
5217
+ return originCache.get(xs);
5218
+ }
5219
+
5220
+ // node_modules/postgres/src/errors.js
5221
+ var PostgresError = class extends Error {
5222
+ constructor(x) {
5223
+ super(x.message);
5224
+ this.name = this.constructor.name;
5225
+ Object.assign(this, x);
5226
+ }
5227
+ };
5228
+ var Errors = {
5229
+ connection,
5230
+ postgres,
5231
+ generic,
5232
+ notSupported
5233
+ };
5234
+ function connection(x, options, socket) {
5235
+ const { host, port } = socket || options;
5236
+ const error = Object.assign(
5237
+ new Error("write " + x + " " + (options.path || host + ":" + port)),
5238
+ {
5239
+ code: x,
5240
+ errno: x,
5241
+ address: options.path || host
5242
+ },
5243
+ options.path ? {} : { port }
5244
+ );
5245
+ Error.captureStackTrace(error, connection);
5246
+ return error;
5247
+ }
5248
+ function postgres(x) {
5249
+ const error = new PostgresError(x);
5250
+ Error.captureStackTrace(error, postgres);
5251
+ return error;
5252
+ }
5253
+ function generic(code, message) {
5254
+ const error = Object.assign(new Error(code + ": " + message), { code });
5255
+ Error.captureStackTrace(error, generic);
5256
+ return error;
5257
+ }
5258
+ function notSupported(x) {
5259
+ const error = Object.assign(
5260
+ new Error(x + " (B) is not supported"),
5261
+ {
5262
+ code: "MESSAGE_NOT_SUPPORTED",
5263
+ name: x
5264
+ }
5265
+ );
5266
+ Error.captureStackTrace(error, notSupported);
5267
+ return error;
5268
+ }
5269
+
5270
+ // node_modules/postgres/src/types.js
5271
+ var types = {
5272
+ string: {
5273
+ to: 25,
5274
+ from: null,
5275
+ // defaults to string
5276
+ serialize: (x) => "" + x
5277
+ },
5278
+ number: {
5279
+ to: 0,
5280
+ from: [21, 23, 26, 700, 701],
5281
+ serialize: (x) => "" + x,
5282
+ parse: (x) => +x
5283
+ },
5284
+ json: {
5285
+ to: 114,
5286
+ from: [114, 3802],
5287
+ serialize: (x) => JSON.stringify(x),
5288
+ parse: (x) => JSON.parse(x)
5289
+ },
5290
+ boolean: {
5291
+ to: 16,
5292
+ from: 16,
5293
+ serialize: (x) => x === true ? "t" : "f",
5294
+ parse: (x) => x === "t"
5295
+ },
5296
+ date: {
5297
+ to: 1184,
5298
+ from: [1082, 1114, 1184],
5299
+ serialize: (x) => (x instanceof Date ? x : new Date(x)).toISOString(),
5300
+ parse: (x) => new Date(x)
5301
+ },
5302
+ bytea: {
5303
+ to: 17,
5304
+ from: 17,
5305
+ serialize: (x) => "\\x" + Buffer.from(x).toString("hex"),
5306
+ parse: (x) => Buffer.from(x.slice(2), "hex")
5307
+ }
5308
+ };
5309
+ var NotTagged = class {
5310
+ then() {
5311
+ notTagged();
5312
+ }
5313
+ catch() {
5314
+ notTagged();
5315
+ }
5316
+ finally() {
5317
+ notTagged();
5318
+ }
5319
+ };
5320
+ var Identifier = class extends NotTagged {
5321
+ constructor(value) {
5322
+ super();
5323
+ this.value = escapeIdentifier(value);
5324
+ }
5325
+ };
5326
+ var Parameter = class extends NotTagged {
5327
+ constructor(value, type, array) {
5328
+ super();
5329
+ this.value = value;
5330
+ this.type = type;
5331
+ this.array = array;
5332
+ }
5333
+ };
5334
+ var Builder = class extends NotTagged {
5335
+ constructor(first, rest) {
5336
+ super();
5337
+ this.first = first;
5338
+ this.rest = rest;
5339
+ }
5340
+ build(before, parameters, types2, options) {
5341
+ const keyword = builders.map(([x, fn]) => ({ fn, i: before.search(x) })).sort((a, b2) => a.i - b2.i).pop();
5342
+ return keyword.i === -1 ? escapeIdentifiers(this.first, options) : keyword.fn(this.first, this.rest, parameters, types2, options);
5343
+ }
5344
+ };
5345
+ function handleValue(x, parameters, types2, options) {
5346
+ let value = x instanceof Parameter ? x.value : x;
5347
+ if (value === void 0) {
5348
+ x instanceof Parameter ? x.value = options.transform.undefined : value = x = options.transform.undefined;
5349
+ if (value === void 0)
5350
+ throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed");
5351
+ }
5352
+ return "$" + types2.push(
5353
+ x instanceof Parameter ? (parameters.push(x.value), x.array ? x.array[x.type || inferType(x.value)] || x.type || firstIsString(x.value) : x.type) : (parameters.push(x), inferType(x))
5354
+ );
5355
+ }
5356
+ var defaultHandlers = typeHandlers(types);
5357
+ function stringify2(q, string, value, parameters, types2, options) {
5358
+ for (let i = 1; i < q.strings.length; i++) {
5359
+ string += stringifyValue(string, value, parameters, types2, options) + q.strings[i];
5360
+ value = q.args[i];
5361
+ }
5362
+ return string;
5363
+ }
5364
+ function stringifyValue(string, value, parameters, types2, o) {
5365
+ return value instanceof Builder ? value.build(string, parameters, types2, o) : value instanceof Query ? fragment(value, parameters, types2, o) : value instanceof Identifier ? value.value : value && value[0] instanceof Query ? value.reduce((acc, x) => acc + " " + fragment(x, parameters, types2, o), "") : handleValue(value, parameters, types2, o);
5366
+ }
5367
+ function fragment(q, parameters, types2, options) {
5368
+ q.fragment = true;
5369
+ return stringify2(q, q.strings[0], q.args[0], parameters, types2, options);
5370
+ }
5371
+ function valuesBuilder(first, parameters, types2, columns, options) {
5372
+ return first.map(
5373
+ (row) => "(" + columns.map(
5374
+ (column) => stringifyValue("values", row[column], parameters, types2, options)
5375
+ ).join(",") + ")"
5376
+ ).join(",");
5377
+ }
5378
+ function values(first, rest, parameters, types2, options) {
5379
+ const multi = Array.isArray(first[0]);
5380
+ const columns = rest.length ? rest.flat() : Object.keys(multi ? first[0] : first);
5381
+ return valuesBuilder(multi ? first : [first], parameters, types2, columns, options);
5382
+ }
5383
+ function select(first, rest, parameters, types2, options) {
5384
+ typeof first === "string" && (first = [first].concat(rest));
5385
+ if (Array.isArray(first))
5386
+ return escapeIdentifiers(first, options);
5387
+ let value;
5388
+ const columns = rest.length ? rest.flat() : Object.keys(first);
5389
+ return columns.map((x) => {
5390
+ value = first[x];
5391
+ return (value instanceof Query ? fragment(value, parameters, types2, options) : value instanceof Identifier ? value.value : handleValue(value, parameters, types2, options)) + " as " + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x);
5392
+ }).join(",");
5393
+ }
5394
+ var builders = Object.entries({
5395
+ values,
5396
+ in: (...xs) => {
5397
+ const x = values(...xs);
5398
+ return x === "()" ? "(null)" : x;
5399
+ },
5400
+ select,
5401
+ as: select,
5402
+ returning: select,
5403
+ "\\(": select,
5404
+ update(first, rest, parameters, types2, options) {
5405
+ return (rest.length ? rest.flat() : Object.keys(first)).map(
5406
+ (x) => escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x) + "=" + stringifyValue("values", first[x], parameters, types2, options)
5407
+ );
5408
+ },
5409
+ insert(first, rest, parameters, types2, options) {
5410
+ const columns = rest.length ? rest.flat() : Object.keys(Array.isArray(first) ? first[0] : first);
5411
+ return "(" + escapeIdentifiers(columns, options) + ")values" + valuesBuilder(Array.isArray(first) ? first : [first], parameters, types2, columns, options);
5412
+ }
5413
+ }).map(([x, fn]) => [new RegExp("((?:^|[\\s(])" + x + "(?:$|[\\s(]))(?![\\s\\S]*\\1)", "i"), fn]);
5414
+ function notTagged() {
5415
+ throw Errors.generic("NOT_TAGGED_CALL", "Query not called as a tagged template literal");
5416
+ }
5417
+ var serializers = defaultHandlers.serializers;
5418
+ var parsers = defaultHandlers.parsers;
5419
+ function firstIsString(x) {
5420
+ if (Array.isArray(x))
5421
+ return firstIsString(x[0]);
5422
+ return typeof x === "string" ? 1009 : 0;
5423
+ }
5424
+ var mergeUserTypes = function(types2) {
5425
+ const user = typeHandlers(types2 || {});
5426
+ return {
5427
+ serializers: Object.assign({}, serializers, user.serializers),
5428
+ parsers: Object.assign({}, parsers, user.parsers)
5429
+ };
5430
+ };
5431
+ function typeHandlers(types2) {
5432
+ return Object.keys(types2).reduce((acc, k) => {
5433
+ types2[k].from && [].concat(types2[k].from).forEach((x) => acc.parsers[x] = types2[k].parse);
5434
+ if (types2[k].serialize) {
5435
+ acc.serializers[types2[k].to] = types2[k].serialize;
5436
+ types2[k].from && [].concat(types2[k].from).forEach((x) => acc.serializers[x] = types2[k].serialize);
5437
+ }
5438
+ return acc;
5439
+ }, { parsers: {}, serializers: {} });
5440
+ }
5441
+ function escapeIdentifiers(xs, { transform: { column } }) {
5442
+ return xs.map((x) => escapeIdentifier(column.to ? column.to(x) : x)).join(",");
5443
+ }
5444
+ var escapeIdentifier = function escape(str) {
5445
+ return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"';
5446
+ };
5447
+ var inferType = function inferType2(x) {
5448
+ return x instanceof Parameter ? x.type : x instanceof Date ? 1184 : x instanceof Uint8Array ? 17 : x === true || x === false ? 16 : typeof x === "bigint" ? 20 : Array.isArray(x) ? inferType2(x[0]) : 0;
5449
+ };
5450
+ var escapeBackslash = /\\/g;
5451
+ var escapeQuote = /"/g;
5452
+ function arrayEscape(x) {
5453
+ return x.replace(escapeBackslash, "\\\\").replace(escapeQuote, '\\"');
5454
+ }
5455
+ var arraySerializer = function arraySerializer2(xs, serializer, options, typarray) {
5456
+ if (Array.isArray(xs) === false)
5457
+ return xs;
5458
+ if (!xs.length)
5459
+ return "{}";
5460
+ const first = xs[0];
5461
+ const delimiter = typarray === 1020 ? ";" : ",";
5462
+ if (Array.isArray(first) && !first.type)
5463
+ return "{" + xs.map((x) => arraySerializer2(x, serializer, options, typarray)).join(delimiter) + "}";
5464
+ return "{" + xs.map((x) => {
5465
+ if (x === void 0) {
5466
+ x = options.transform.undefined;
5467
+ if (x === void 0)
5468
+ throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed");
5469
+ }
5470
+ return x === null ? "null" : '"' + arrayEscape(serializer ? serializer(x.type ? x.value : x) : "" + x) + '"';
5471
+ }).join(delimiter) + "}";
5472
+ };
5473
+ var arrayParserState = {
5474
+ i: 0,
5475
+ char: null,
5476
+ str: "",
5477
+ quoted: false,
5478
+ last: 0
5479
+ };
5480
+ var arrayParser = function arrayParser2(x, parser, typarray) {
5481
+ arrayParserState.i = arrayParserState.last = 0;
5482
+ return arrayParserLoop(arrayParserState, x, parser, typarray);
5483
+ };
5484
+ function arrayParserLoop(s, x, parser, typarray) {
5485
+ const xs = [];
5486
+ const delimiter = typarray === 1020 ? ";" : ",";
5487
+ for (; s.i < x.length; s.i++) {
5488
+ s.char = x[s.i];
5489
+ if (s.quoted) {
5490
+ if (s.char === "\\") {
5491
+ s.str += x[++s.i];
5492
+ } else if (s.char === '"') {
5493
+ xs.push(parser ? parser(s.str) : s.str);
5494
+ s.str = "";
5495
+ s.quoted = x[s.i + 1] === '"';
5496
+ s.last = s.i + 2;
5497
+ } else {
5498
+ s.str += s.char;
5499
+ }
5500
+ } else if (s.char === '"') {
5501
+ s.quoted = true;
5502
+ } else if (s.char === "{") {
5503
+ s.last = ++s.i;
5504
+ xs.push(arrayParserLoop(s, x, parser, typarray));
5505
+ } else if (s.char === "}") {
5506
+ s.quoted = false;
5507
+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i));
5508
+ s.last = s.i + 1;
5509
+ break;
5510
+ } else if (s.char === delimiter && s.p !== "}" && s.p !== '"') {
5511
+ xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i));
5512
+ s.last = s.i + 1;
5513
+ }
5514
+ s.p = s.char;
5515
+ }
5516
+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i + 1)) : x.slice(s.last, s.i + 1));
5517
+ return xs;
5518
+ }
5519
+ var toCamel = (x) => {
5520
+ let str = x[0];
5521
+ for (let i = 1; i < x.length; i++)
5522
+ str += x[i] === "_" ? x[++i].toUpperCase() : x[i];
5523
+ return str;
5524
+ };
5525
+ var toPascal = (x) => {
5526
+ let str = x[0].toUpperCase();
5527
+ for (let i = 1; i < x.length; i++)
5528
+ str += x[i] === "_" ? x[++i].toUpperCase() : x[i];
5529
+ return str;
5530
+ };
5531
+ var toKebab = (x) => x.replace(/_/g, "-");
5532
+ var fromCamel = (x) => x.replace(/([A-Z])/g, "_$1").toLowerCase();
5533
+ var fromPascal = (x) => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, "_$1")).toLowerCase();
5534
+ var fromKebab = (x) => x.replace(/-/g, "_");
5535
+ function createJsonTransform(fn) {
5536
+ return function jsonTransform(x, column) {
5537
+ return typeof x === "object" && x !== null && (column.type === 114 || column.type === 3802) ? Array.isArray(x) ? x.map((x2) => jsonTransform(x2, column)) : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: jsonTransform(v, column) }), {}) : x;
5538
+ };
5539
+ }
5540
+ toCamel.column = { from: toCamel };
5541
+ toCamel.value = { from: createJsonTransform(toCamel) };
5542
+ fromCamel.column = { to: fromCamel };
5543
+ var camel = { ...toCamel };
5544
+ camel.column.to = fromCamel;
5545
+ toPascal.column = { from: toPascal };
5546
+ toPascal.value = { from: createJsonTransform(toPascal) };
5547
+ fromPascal.column = { to: fromPascal };
5548
+ var pascal = { ...toPascal };
5549
+ pascal.column.to = fromPascal;
5550
+ toKebab.column = { from: toKebab };
5551
+ toKebab.value = { from: createJsonTransform(toKebab) };
5552
+ fromKebab.column = { to: fromKebab };
5553
+ var kebab = { ...toKebab };
5554
+ kebab.column.to = fromKebab;
5555
+
5556
+ // node_modules/postgres/src/connection.js
5557
+ import net from "net";
5558
+ import tls from "tls";
5559
+ import crypto4 from "crypto";
5560
+ import Stream from "stream";
5561
+ import { performance } from "perf_hooks";
5562
+
5563
+ // node_modules/postgres/src/result.js
5564
+ var Result = class extends Array {
5565
+ constructor() {
5566
+ super();
5567
+ Object.defineProperties(this, {
5568
+ count: { value: null, writable: true },
5569
+ state: { value: null, writable: true },
5570
+ command: { value: null, writable: true },
5571
+ columns: { value: null, writable: true },
5572
+ statement: { value: null, writable: true }
5573
+ });
5574
+ }
5575
+ static get [Symbol.species]() {
5576
+ return Array;
5577
+ }
5578
+ };
5579
+
5580
+ // node_modules/postgres/src/queue.js
5581
+ var queue_default = Queue;
5582
+ function Queue(initial = []) {
5583
+ let xs = initial.slice();
5584
+ let index = 0;
5585
+ return {
5586
+ get length() {
5587
+ return xs.length - index;
5588
+ },
5589
+ remove: (x) => {
5590
+ const index2 = xs.indexOf(x);
5591
+ return index2 === -1 ? null : (xs.splice(index2, 1), x);
5592
+ },
5593
+ push: (x) => (xs.push(x), x),
5594
+ shift: () => {
5595
+ const out = xs[index++];
5596
+ if (index === xs.length) {
5597
+ index = 0;
5598
+ xs = [];
5599
+ } else {
5600
+ xs[index - 1] = void 0;
5601
+ }
5602
+ return out;
5603
+ }
5604
+ };
5605
+ }
5606
+
5607
+ // node_modules/postgres/src/bytes.js
5608
+ var size2 = 256;
5609
+ var buffer = Buffer.allocUnsafe(size2);
5610
+ var messages = "BCcDdEFfHPpQSX".split("").reduce((acc, x) => {
5611
+ const v = x.charCodeAt(0);
5612
+ acc[x] = () => {
5613
+ buffer[0] = v;
5614
+ b.i = 5;
5615
+ return b;
5616
+ };
5617
+ return acc;
5618
+ }, {});
5619
+ var b = Object.assign(reset, messages, {
5620
+ N: String.fromCharCode(0),
5621
+ i: 0,
5622
+ inc(x) {
5623
+ b.i += x;
5624
+ return b;
5625
+ },
5626
+ str(x) {
5627
+ const length = Buffer.byteLength(x);
5628
+ fit(length);
5629
+ b.i += buffer.write(x, b.i, length, "utf8");
5630
+ return b;
5631
+ },
5632
+ i16(x) {
5633
+ fit(2);
5634
+ buffer.writeUInt16BE(x, b.i);
5635
+ b.i += 2;
5636
+ return b;
5637
+ },
5638
+ i32(x, i) {
5639
+ if (i || i === 0) {
5640
+ buffer.writeUInt32BE(x, i);
5641
+ return b;
5642
+ }
5643
+ fit(4);
5644
+ buffer.writeUInt32BE(x, b.i);
5645
+ b.i += 4;
5646
+ return b;
5647
+ },
5648
+ z(x) {
5649
+ fit(x);
5650
+ buffer.fill(0, b.i, b.i + x);
5651
+ b.i += x;
5652
+ return b;
5653
+ },
5654
+ raw(x) {
5655
+ buffer = Buffer.concat([buffer.subarray(0, b.i), x]);
5656
+ b.i = buffer.length;
5657
+ return b;
5658
+ },
5659
+ end(at = 1) {
5660
+ buffer.writeUInt32BE(b.i - at, at);
5661
+ const out = buffer.subarray(0, b.i);
5662
+ b.i = 0;
5663
+ buffer = Buffer.allocUnsafe(size2);
5664
+ return out;
5665
+ }
5666
+ });
5667
+ var bytes_default = b;
5668
+ function fit(x) {
5669
+ if (buffer.length - b.i < x) {
5670
+ const prev = buffer, length = prev.length;
5671
+ buffer = Buffer.allocUnsafe(length + (length >> 1) + x);
5672
+ prev.copy(buffer);
5673
+ }
5674
+ }
5675
+ function reset() {
5676
+ b.i = 0;
5677
+ return b;
5678
+ }
5679
+
5680
+ // node_modules/postgres/src/connection.js
5681
+ var connection_default = Connection;
5682
+ var uid = 1;
5683
+ var Sync = bytes_default().S().end();
5684
+ var Flush = bytes_default().H().end();
5685
+ var SSLRequest = bytes_default().i32(8).i32(80877103).end(8);
5686
+ var ExecuteUnnamed = Buffer.concat([bytes_default().E().str(bytes_default.N).i32(0).end(), Sync]);
5687
+ var DescribeUnnamed = bytes_default().D().str("S").str(bytes_default.N).end();
5688
+ var noop = () => {
5689
+ };
5690
+ var retryRoutines = /* @__PURE__ */ new Set([
5691
+ "FetchPreparedStatement",
5692
+ "RevalidateCachedQuery",
5693
+ "transformAssignedExpr"
5694
+ ]);
5695
+ var errorFields = {
5696
+ 83: "severity_local",
5697
+ // S
5698
+ 86: "severity",
5699
+ // V
5700
+ 67: "code",
5701
+ // C
5702
+ 77: "message",
5703
+ // M
5704
+ 68: "detail",
5705
+ // D
5706
+ 72: "hint",
5707
+ // H
5708
+ 80: "position",
5709
+ // P
5710
+ 112: "internal_position",
5711
+ // p
5712
+ 113: "internal_query",
5713
+ // q
5714
+ 87: "where",
5715
+ // W
5716
+ 115: "schema_name",
5717
+ // s
5718
+ 116: "table_name",
5719
+ // t
5720
+ 99: "column_name",
5721
+ // c
5722
+ 100: "data type_name",
5723
+ // d
5724
+ 110: "constraint_name",
5725
+ // n
5726
+ 70: "file",
5727
+ // F
5728
+ 76: "line",
5729
+ // L
5730
+ 82: "routine"
5731
+ // R
5732
+ };
5733
+ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {
5734
+ const {
5735
+ sslnegotiation,
5736
+ ssl,
5737
+ max,
5738
+ user,
5739
+ host,
5740
+ port,
5741
+ database,
5742
+ parsers: parsers2,
5743
+ transform,
5744
+ onnotice,
5745
+ onnotify,
5746
+ onparameter,
5747
+ max_pipeline,
5748
+ keep_alive,
5749
+ backoff: backoff2,
5750
+ target_session_attrs
5751
+ } = options;
5752
+ const sent = queue_default(), id = uid++, backend = { pid: null, secret: null }, idleTimer = timer(end, options.idle_timeout), lifeTimer = timer(end, options.max_lifetime), connectTimer = timer(connectTimedOut, options.connect_timeout);
5753
+ let socket = null, cancelMessage, errorResponse = null, result = new Result(), incoming = Buffer.alloc(0), needsTypes = options.fetch_types, backendParameters = {}, statements = {}, statementId = Math.random().toString(36).slice(2), statementCount = 1, closedTime = 0, remaining = 0, hostIndex = 0, retries = 0, length = 0, delay = 0, rows = 0, serverSignature = null, nextWriteTimer = null, terminated = false, incomings = null, results = null, initial = null, ending = null, stream = null, chunk = null, ended = null, nonce = null, query = null, final = null;
5754
+ const connection2 = {
5755
+ queue: queues.closed,
5756
+ idleTimer,
5757
+ connect(query2) {
5758
+ initial = query2;
5759
+ reconnect();
5760
+ },
5761
+ terminate,
5762
+ execute,
5763
+ cancel,
5764
+ end,
5765
+ count: 0,
5766
+ id
5767
+ };
5768
+ queues.closed && queues.closed.push(connection2);
5769
+ return connection2;
5770
+ async function createSocket() {
5771
+ let x;
5772
+ try {
5773
+ x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket();
5774
+ } catch (e) {
5775
+ error(e);
5776
+ return;
5777
+ }
5778
+ x.on("error", error);
5779
+ x.on("close", closed);
5780
+ x.on("drain", drain);
5781
+ return x;
5782
+ }
5783
+ async function cancel({ pid, secret }, resolve, reject) {
5784
+ try {
5785
+ cancelMessage = bytes_default().i32(16).i32(80877102).i32(pid).i32(secret).end(16);
5786
+ await connect();
5787
+ socket.once("error", reject);
5788
+ socket.once("close", resolve);
5789
+ } catch (error2) {
5790
+ reject(error2);
5791
+ }
5792
+ }
5793
+ function execute(q) {
5794
+ if (terminated)
5795
+ return queryError(q, Errors.connection("CONNECTION_DESTROYED", options));
5796
+ if (stream)
5797
+ return queryError(q, Errors.generic("COPY_IN_PROGRESS", "You cannot execute queries during copy"));
5798
+ if (q.cancelled)
5799
+ return;
5800
+ try {
5801
+ q.state = backend;
5802
+ query ? sent.push(q) : (query = q, query.active = true);
5803
+ build(q);
5804
+ return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2));
5805
+ } catch (error2) {
5806
+ sent.length === 0 && write(Sync);
5807
+ errored(error2);
5808
+ return true;
5809
+ }
5810
+ }
5811
+ function toBuffer(q) {
5812
+ if (q.parameters.length >= 65534)
5813
+ throw Errors.generic("MAX_PARAMETERS_EXCEEDED", "Max number of parameters (65534) exceeded");
5814
+ return q.options.simple ? bytes_default().Q().str(q.statement.string + bytes_default.N).end() : q.describeFirst ? Buffer.concat([describe(q), Flush]) : q.prepare ? q.prepared ? prepared(q) : Buffer.concat([describe(q), prepared(q)]) : unnamed(q);
5815
+ }
5816
+ function describe(q) {
5817
+ return Buffer.concat([
5818
+ Parse(q.statement.string, q.parameters, q.statement.types, q.statement.name),
5819
+ Describe("S", q.statement.name)
5820
+ ]);
5821
+ }
5822
+ function prepared(q) {
5823
+ return Buffer.concat([
5824
+ Bind(q.parameters, q.statement.types, q.statement.name, q.cursorName),
5825
+ q.cursorFn ? Execute("", q.cursorRows) : ExecuteUnnamed
5826
+ ]);
5827
+ }
5828
+ function unnamed(q) {
5829
+ return Buffer.concat([
5830
+ Parse(q.statement.string, q.parameters, q.statement.types),
5831
+ DescribeUnnamed,
5832
+ prepared(q)
5833
+ ]);
5834
+ }
5835
+ function build(q) {
5836
+ const parameters = [], types2 = [];
5837
+ const string = stringify2(q, q.strings[0], q.args[0], parameters, types2, options);
5838
+ !q.tagged && q.args.forEach((x) => handleValue(x, parameters, types2, options));
5839
+ q.prepare = options.prepare && ("prepare" in q.options ? q.options.prepare : true);
5840
+ q.string = string;
5841
+ q.signature = q.prepare && types2 + string;
5842
+ q.onlyDescribe && delete statements[q.signature];
5843
+ q.parameters = q.parameters || parameters;
5844
+ q.prepared = q.prepare && q.signature in statements;
5845
+ q.describeFirst = q.onlyDescribe || parameters.length && !q.prepared;
5846
+ q.statement = q.prepared ? statements[q.signature] : { string, types: types2, name: q.prepare ? statementId + statementCount++ : "" };
5847
+ typeof options.debug === "function" && options.debug(id, string, parameters, types2);
5848
+ }
5849
+ function write(x, fn) {
5850
+ chunk = chunk ? Buffer.concat([chunk, x]) : Buffer.from(x);
5851
+ if (fn || chunk.length >= 1024)
5852
+ return nextWrite(fn);
5853
+ nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite));
5854
+ return true;
5855
+ }
5856
+ function nextWrite(fn) {
5857
+ const x = socket.write(chunk, fn);
5858
+ nextWriteTimer !== null && clearImmediate(nextWriteTimer);
5859
+ chunk = nextWriteTimer = null;
5860
+ return x;
5861
+ }
5862
+ function connectTimedOut() {
5863
+ errored(Errors.connection("CONNECT_TIMEOUT", options, socket));
5864
+ socket.destroy();
5865
+ }
5866
+ async function secure() {
5867
+ if (sslnegotiation !== "direct") {
5868
+ write(SSLRequest);
5869
+ const canSSL = await new Promise((r) => socket.once("data", (x) => r(x[0] === 83)));
5870
+ if (!canSSL && ssl === "prefer")
5871
+ return connected();
5872
+ }
5873
+ const options2 = {
5874
+ socket,
5875
+ servername: net.isIP(socket.host) ? void 0 : socket.host
5876
+ };
5877
+ if (sslnegotiation === "direct")
5878
+ options2.ALPNProtocols = ["postgresql"];
5879
+ if (ssl === "require" || ssl === "allow" || ssl === "prefer")
5880
+ options2.rejectUnauthorized = false;
5881
+ else if (typeof ssl === "object")
5882
+ Object.assign(options2, ssl);
5883
+ socket.removeAllListeners();
5884
+ socket = tls.connect(options2);
5885
+ socket.on("secureConnect", connected);
5886
+ socket.on("error", error);
5887
+ socket.on("close", closed);
5888
+ socket.on("drain", drain);
5889
+ }
5890
+ function drain() {
5891
+ !query && onopen(connection2);
5892
+ }
5893
+ function data(x) {
5894
+ if (incomings) {
5895
+ incomings.push(x);
5896
+ remaining -= x.length;
5897
+ if (remaining > 0)
5898
+ return;
5899
+ }
5900
+ incoming = incomings ? Buffer.concat(incomings, length - remaining) : incoming.length === 0 ? x : Buffer.concat([incoming, x], incoming.length + x.length);
5901
+ while (incoming.length > 4) {
5902
+ length = incoming.readUInt32BE(1);
5903
+ if (length >= incoming.length) {
5904
+ remaining = length - incoming.length;
5905
+ incomings = [incoming];
5906
+ break;
5907
+ }
5908
+ try {
5909
+ handle(incoming.subarray(0, length + 1));
5910
+ } catch (e) {
5911
+ query && (query.cursorFn || query.describeFirst) && write(Sync);
5912
+ errored(e);
5913
+ }
5914
+ incoming = incoming.subarray(length + 1);
5915
+ remaining = 0;
5916
+ incomings = null;
5917
+ }
5918
+ }
5919
+ async function connect() {
5920
+ terminated = false;
5921
+ backendParameters = {};
5922
+ socket || (socket = await createSocket());
5923
+ if (!socket)
5924
+ return;
5925
+ connectTimer.start();
5926
+ if (options.socket)
5927
+ return ssl ? secure() : connected();
5928
+ socket.on("connect", ssl ? secure : connected);
5929
+ if (options.path)
5930
+ return socket.connect(options.path);
5931
+ socket.ssl = ssl;
5932
+ socket.connect(port[hostIndex], host[hostIndex]);
5933
+ socket.host = host[hostIndex];
5934
+ socket.port = port[hostIndex];
5935
+ hostIndex = (hostIndex + 1) % port.length;
5936
+ }
5937
+ function reconnect() {
5938
+ setTimeout(connect, closedTime ? Math.max(0, closedTime + delay - performance.now()) : 0);
5939
+ }
5940
+ function connected() {
5941
+ try {
5942
+ statements = {};
5943
+ needsTypes = options.fetch_types;
5944
+ statementId = Math.random().toString(36).slice(2);
5945
+ statementCount = 1;
5946
+ lifeTimer.start();
5947
+ socket.on("data", data);
5948
+ keep_alive && socket.setKeepAlive && socket.setKeepAlive(true, 1e3 * keep_alive);
5949
+ const s = StartupMessage();
5950
+ write(s);
5951
+ } catch (err) {
5952
+ error(err);
5953
+ }
5954
+ }
5955
+ function error(err) {
5956
+ if (connection2.queue === queues.connecting && options.host[retries + 1])
5957
+ return;
5958
+ errored(err);
5959
+ while (sent.length)
5960
+ queryError(sent.shift(), err);
5961
+ }
5962
+ function errored(err) {
5963
+ stream && (stream.destroy(err), stream = null);
5964
+ query && queryError(query, err);
5965
+ initial && (queryError(initial, err), initial = null);
5966
+ }
5967
+ function queryError(query2, err) {
5968
+ if (query2.reserve)
5969
+ return query2.reject(err);
5970
+ if (!err || typeof err !== "object")
5971
+ err = new Error(err);
5972
+ "query" in err || "parameters" in err || Object.defineProperties(err, {
5973
+ stack: { value: err.stack + query2.origin.replace(/.*\n/, "\n"), enumerable: options.debug },
5974
+ query: { value: query2.string, enumerable: options.debug },
5975
+ parameters: { value: query2.parameters, enumerable: options.debug },
5976
+ args: { value: query2.args, enumerable: options.debug },
5977
+ types: { value: query2.statement && query2.statement.types, enumerable: options.debug }
5978
+ });
5979
+ query2.reject(err);
5980
+ }
5981
+ function end() {
5982
+ return ending || (!connection2.reserved && onend(connection2), !connection2.reserved && !initial && !query && sent.length === 0 ? (terminate(), new Promise((r) => socket && socket.readyState !== "closed" ? socket.once("close", r) : r())) : ending = new Promise((r) => ended = r));
5983
+ }
5984
+ function terminate() {
5985
+ terminated = true;
5986
+ if (stream || query || initial || sent.length)
5987
+ error(Errors.connection("CONNECTION_DESTROYED", options));
5988
+ clearImmediate(nextWriteTimer);
5989
+ if (socket) {
5990
+ socket.removeListener("data", data);
5991
+ socket.removeListener("connect", connected);
5992
+ socket.readyState === "open" && socket.end(bytes_default().X().end());
5993
+ }
5994
+ ended && (ended(), ending = ended = null);
5995
+ }
5996
+ async function closed(hadError) {
5997
+ incoming = Buffer.alloc(0);
5998
+ remaining = 0;
5999
+ incomings = null;
6000
+ clearImmediate(nextWriteTimer);
6001
+ socket.removeListener("data", data);
6002
+ socket.removeListener("connect", connected);
6003
+ idleTimer.cancel();
6004
+ lifeTimer.cancel();
6005
+ connectTimer.cancel();
6006
+ socket.removeAllListeners();
6007
+ socket = null;
6008
+ if (initial)
6009
+ return reconnect();
6010
+ !hadError && (query || sent.length) && error(Errors.connection("CONNECTION_CLOSED", options, socket));
6011
+ closedTime = performance.now();
6012
+ hadError && options.shared.retries++;
6013
+ delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3;
6014
+ onclose(connection2, Errors.connection("CONNECTION_CLOSED", options, socket));
6015
+ }
6016
+ function handle(xs, x = xs[0]) {
6017
+ (x === 68 ? DataRow : (
6018
+ // D
6019
+ x === 100 ? CopyData : (
6020
+ // d
6021
+ x === 65 ? NotificationResponse : (
6022
+ // A
6023
+ x === 83 ? ParameterStatus : (
6024
+ // S
6025
+ x === 90 ? ReadyForQuery : (
6026
+ // Z
6027
+ x === 67 ? CommandComplete : (
6028
+ // C
6029
+ x === 50 ? BindComplete : (
6030
+ // 2
6031
+ x === 49 ? ParseComplete : (
6032
+ // 1
6033
+ x === 116 ? ParameterDescription : (
6034
+ // t
6035
+ x === 84 ? RowDescription : (
6036
+ // T
6037
+ x === 82 ? Authentication : (
6038
+ // R
6039
+ x === 110 ? NoData : (
6040
+ // n
6041
+ x === 75 ? BackendKeyData : (
6042
+ // K
6043
+ x === 69 ? ErrorResponse : (
6044
+ // E
6045
+ x === 115 ? PortalSuspended : (
6046
+ // s
6047
+ x === 51 ? CloseComplete : (
6048
+ // 3
6049
+ x === 71 ? CopyInResponse : (
6050
+ // G
6051
+ x === 78 ? NoticeResponse : (
6052
+ // N
6053
+ x === 72 ? CopyOutResponse : (
6054
+ // H
6055
+ x === 99 ? CopyDone : (
6056
+ // c
6057
+ x === 73 ? EmptyQueryResponse : (
6058
+ // I
6059
+ x === 86 ? FunctionCallResponse : (
6060
+ // V
6061
+ x === 118 ? NegotiateProtocolVersion : (
6062
+ // v
6063
+ x === 87 ? CopyBothResponse : (
6064
+ // W
6065
+ /* c8 ignore next */
6066
+ UnknownMessage
6067
+ )
6068
+ )
6069
+ )
6070
+ )
6071
+ )
6072
+ )
6073
+ )
6074
+ )
6075
+ )
6076
+ )
6077
+ )
6078
+ )
6079
+ )
6080
+ )
6081
+ )
6082
+ )
6083
+ )
6084
+ )
6085
+ )
6086
+ )
6087
+ )
6088
+ )
6089
+ )
6090
+ ))(xs);
6091
+ }
6092
+ function DataRow(x) {
6093
+ let index = 7;
6094
+ let length2;
6095
+ let column;
6096
+ let value;
6097
+ const row = query.isRaw ? new Array(query.statement.columns.length) : {};
6098
+ for (let i = 0; i < query.statement.columns.length; i++) {
6099
+ column = query.statement.columns[i];
6100
+ length2 = x.readInt32BE(index);
6101
+ index += 4;
6102
+ value = length2 === -1 ? null : query.isRaw === true ? x.subarray(index, index += length2) : column.parser === void 0 ? x.toString("utf8", index, index += length2) : column.parser.array === true ? column.parser(x.toString("utf8", index + 1, index += length2)) : column.parser(x.toString("utf8", index, index += length2));
6103
+ query.isRaw ? row[i] = query.isRaw === true ? value : transform.value.from ? transform.value.from(value, column) : value : row[column.name] = transform.value.from ? transform.value.from(value, column) : value;
6104
+ }
6105
+ query.forEachFn ? query.forEachFn(transform.row.from ? transform.row.from(row) : row, result) : result[rows++] = transform.row.from ? transform.row.from(row) : row;
6106
+ }
6107
+ function ParameterStatus(x) {
6108
+ const [k, v] = x.toString("utf8", 5, x.length - 1).split(bytes_default.N);
6109
+ backendParameters[k] = v;
6110
+ if (options.parameters[k] !== v) {
6111
+ options.parameters[k] = v;
6112
+ onparameter && onparameter(k, v);
6113
+ }
6114
+ }
6115
+ function ReadyForQuery(x) {
6116
+ if (query) {
6117
+ if (errorResponse) {
6118
+ query.retried ? errored(query.retried) : query.prepared && retryRoutines.has(errorResponse.routine) ? retry(query, errorResponse) : errored(errorResponse);
6119
+ } else {
6120
+ query.resolve(results || result);
6121
+ }
6122
+ } else if (errorResponse) {
6123
+ errored(errorResponse);
6124
+ }
6125
+ query = results = errorResponse = null;
6126
+ result = new Result();
6127
+ connectTimer.cancel();
6128
+ if (initial) {
6129
+ if (target_session_attrs) {
6130
+ if (!backendParameters.in_hot_standby || !backendParameters.default_transaction_read_only)
6131
+ return fetchState();
6132
+ else if (tryNext(target_session_attrs, backendParameters))
6133
+ return terminate();
6134
+ }
6135
+ if (needsTypes) {
6136
+ initial.reserve && (initial = null);
6137
+ return fetchArrayTypes();
6138
+ }
6139
+ initial && !initial.reserve && execute(initial);
6140
+ options.shared.retries = retries = 0;
6141
+ initial = null;
6142
+ return;
6143
+ }
6144
+ while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
6145
+ Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject);
6146
+ if (query)
6147
+ return;
6148
+ connection2.reserved ? !connection2.reserved.release && x[5] === 73 ? ending ? terminate() : (connection2.reserved = null, onopen(connection2)) : connection2.reserved() : ending ? terminate() : onopen(connection2);
6149
+ }
6150
+ function CommandComplete(x) {
6151
+ rows = 0;
6152
+ for (let i = x.length - 1; i > 0; i--) {
6153
+ if (x[i] === 32 && x[i + 1] < 58 && result.count === null)
6154
+ result.count = +x.toString("utf8", i + 1, x.length - 1);
6155
+ if (x[i - 1] >= 65) {
6156
+ result.command = x.toString("utf8", 5, i);
6157
+ result.state = backend;
6158
+ break;
6159
+ }
6160
+ }
6161
+ final && (final(), final = null);
6162
+ if (result.command === "BEGIN" && max !== 1 && !connection2.reserved)
6163
+ return errored(Errors.generic("UNSAFE_TRANSACTION", "Only use sql.begin, sql.reserved or max: 1"));
6164
+ if (query.options.simple)
6165
+ return BindComplete();
6166
+ if (query.cursorFn) {
6167
+ result.count && query.cursorFn(result);
6168
+ write(Sync);
6169
+ }
6170
+ }
6171
+ function ParseComplete() {
6172
+ query.parsing = false;
6173
+ }
6174
+ function BindComplete() {
6175
+ !result.statement && (result.statement = query.statement);
6176
+ result.columns = query.statement.columns;
6177
+ }
6178
+ function ParameterDescription(x) {
6179
+ const length2 = x.readUInt16BE(5);
6180
+ for (let i = 0; i < length2; ++i)
6181
+ !query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4));
6182
+ query.prepare && (statements[query.signature] = query.statement);
6183
+ query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false);
6184
+ }
6185
+ function RowDescription(x) {
6186
+ if (result.command) {
6187
+ results = results || [result];
6188
+ results.push(result = new Result());
6189
+ result.count = null;
6190
+ query.statement.columns = null;
6191
+ }
6192
+ const length2 = x.readUInt16BE(5);
6193
+ let index = 7;
6194
+ let start;
6195
+ query.statement.columns = Array(length2);
6196
+ for (let i = 0; i < length2; ++i) {
6197
+ start = index;
6198
+ while (x[index++] !== 0) ;
6199
+ const table = x.readUInt32BE(index);
6200
+ const number = x.readUInt16BE(index + 4);
6201
+ const type = x.readUInt32BE(index + 6);
6202
+ query.statement.columns[i] = {
6203
+ name: transform.column.from ? transform.column.from(x.toString("utf8", start, index - 1)) : x.toString("utf8", start, index - 1),
6204
+ parser: parsers2[type],
6205
+ table,
6206
+ number,
6207
+ type
6208
+ };
6209
+ index += 18;
6210
+ }
6211
+ result.statement = query.statement;
6212
+ if (query.onlyDescribe)
6213
+ return query.resolve(query.statement), write(Sync);
6214
+ }
6215
+ async function Authentication(x, type = x.readUInt32BE(5)) {
6216
+ (type === 3 ? AuthenticationCleartextPassword : type === 5 ? AuthenticationMD5Password : type === 10 ? SASL : type === 11 ? SASLContinue : type === 12 ? SASLFinal : type !== 0 ? UnknownAuth : noop)(x, type);
6217
+ }
6218
+ async function AuthenticationCleartextPassword() {
6219
+ const payload = await Pass();
6220
+ write(
6221
+ bytes_default().p().str(payload).z(1).end()
6222
+ );
6223
+ }
6224
+ async function AuthenticationMD5Password(x) {
6225
+ const payload = "md5" + await md5(
6226
+ Buffer.concat([
6227
+ Buffer.from(await md5(await Pass() + user)),
6228
+ x.subarray(9)
6229
+ ])
6230
+ );
6231
+ write(
6232
+ bytes_default().p().str(payload).z(1).end()
6233
+ );
6234
+ }
6235
+ async function SASL() {
6236
+ nonce = (await crypto4.randomBytes(18)).toString("base64");
6237
+ bytes_default().p().str("SCRAM-SHA-256" + bytes_default.N);
6238
+ const i = bytes_default.i;
6239
+ write(bytes_default.inc(4).str("n,,n=*,r=" + nonce).i32(bytes_default.i - i - 4, i).end());
6240
+ }
6241
+ async function SASLContinue(x) {
6242
+ const res = x.toString("utf8", 9).split(",").reduce((acc, x2) => (acc[x2[0]] = x2.slice(2), acc), {});
6243
+ const saltedPassword = await crypto4.pbkdf2Sync(
6244
+ await Pass(),
6245
+ Buffer.from(res.s, "base64"),
6246
+ parseInt(res.i),
6247
+ 32,
6248
+ "sha256"
6249
+ );
6250
+ const clientKey = await hmac2(saltedPassword, "Client Key");
6251
+ const auth = "n=*,r=" + nonce + ",r=" + res.r + ",s=" + res.s + ",i=" + res.i + ",c=biws,r=" + res.r;
6252
+ serverSignature = (await hmac2(await hmac2(saltedPassword, "Server Key"), auth)).toString("base64");
6253
+ const payload = "c=biws,r=" + res.r + ",p=" + xor(
6254
+ clientKey,
6255
+ Buffer.from(await hmac2(await sha2564(clientKey), auth))
6256
+ ).toString("base64");
6257
+ write(
6258
+ bytes_default().p().str(payload).end()
6259
+ );
6260
+ }
6261
+ function SASLFinal(x) {
6262
+ if (x.toString("utf8", 9).split(bytes_default.N, 1)[0].slice(2) === serverSignature)
6263
+ return;
6264
+ errored(Errors.generic("SASL_SIGNATURE_MISMATCH", "The server did not return the correct signature"));
6265
+ socket.destroy();
6266
+ }
6267
+ function Pass() {
6268
+ return Promise.resolve(
6269
+ typeof options.pass === "function" ? options.pass() : options.pass
6270
+ );
6271
+ }
6272
+ function NoData() {
6273
+ result.statement = query.statement;
6274
+ result.statement.columns = [];
6275
+ if (query.onlyDescribe)
6276
+ return query.resolve(query.statement), write(Sync);
6277
+ }
6278
+ function BackendKeyData(x) {
6279
+ backend.pid = x.readUInt32BE(5);
6280
+ backend.secret = x.readUInt32BE(9);
6281
+ }
6282
+ async function fetchArrayTypes() {
6283
+ needsTypes = false;
6284
+ const types2 = await new Query([`
6285
+ select b.oid, b.typarray
6286
+ from pg_catalog.pg_type a
6287
+ left join pg_catalog.pg_type b on b.oid = a.typelem
6288
+ where a.typcategory = 'A'
6289
+ group by b.oid, b.typarray
6290
+ order by b.oid
6291
+ `], [], execute);
6292
+ types2.forEach(({ oid, typarray }) => addArrayType(oid, typarray));
6293
+ }
6294
+ function addArrayType(oid, typarray) {
6295
+ if (!!options.parsers[typarray] && !!options.serializers[typarray]) return;
6296
+ const parser = options.parsers[oid];
6297
+ options.shared.typeArrayMap[oid] = typarray;
6298
+ options.parsers[typarray] = (xs) => arrayParser(xs, parser, typarray);
6299
+ options.parsers[typarray].array = true;
6300
+ options.serializers[typarray] = (xs) => arraySerializer(xs, options.serializers[oid], options, typarray);
6301
+ }
6302
+ function tryNext(x, xs) {
6303
+ return x === "read-write" && xs.default_transaction_read_only === "on" || x === "read-only" && xs.default_transaction_read_only === "off" || x === "primary" && xs.in_hot_standby === "on" || x === "standby" && xs.in_hot_standby === "off" || x === "prefer-standby" && xs.in_hot_standby === "off" && options.host[retries];
6304
+ }
6305
+ function fetchState() {
6306
+ const query2 = new Query([`
6307
+ show transaction_read_only;
6308
+ select pg_catalog.pg_is_in_recovery()
6309
+ `], [], execute, null, { simple: true });
6310
+ query2.resolve = ([[a], [b2]]) => {
6311
+ backendParameters.default_transaction_read_only = a.transaction_read_only;
6312
+ backendParameters.in_hot_standby = b2.pg_is_in_recovery ? "on" : "off";
6313
+ };
6314
+ query2.execute();
6315
+ }
6316
+ function ErrorResponse(x) {
6317
+ if (query) {
6318
+ (query.cursorFn || query.describeFirst) && write(Sync);
6319
+ errorResponse = Errors.postgres(parseError(x));
6320
+ } else {
6321
+ errored(Errors.postgres(parseError(x)));
6322
+ }
6323
+ }
6324
+ function retry(q, error2) {
6325
+ delete statements[q.signature];
6326
+ q.retried = error2;
6327
+ execute(q);
6328
+ }
6329
+ function NotificationResponse(x) {
6330
+ if (!onnotify)
6331
+ return;
6332
+ let index = 9;
6333
+ while (x[index++] !== 0) ;
6334
+ onnotify(
6335
+ x.toString("utf8", 9, index - 1),
6336
+ x.toString("utf8", index, x.length - 1)
6337
+ );
6338
+ }
6339
+ async function PortalSuspended() {
6340
+ try {
6341
+ const x = await Promise.resolve(query.cursorFn(result));
6342
+ rows = 0;
6343
+ x === CLOSE ? write(Close(query.portal)) : (result = new Result(), write(Execute("", query.cursorRows)));
6344
+ } catch (err) {
6345
+ write(Sync);
6346
+ query.reject(err);
6347
+ }
6348
+ }
6349
+ function CloseComplete() {
6350
+ result.count && query.cursorFn(result);
6351
+ query.resolve(result);
6352
+ }
6353
+ function CopyInResponse() {
6354
+ stream = new Stream.Writable({
6355
+ autoDestroy: true,
6356
+ write(chunk2, encoding, callback) {
6357
+ socket.write(bytes_default().d().raw(chunk2).end(), callback);
6358
+ },
6359
+ destroy(error2, callback) {
6360
+ callback(error2);
6361
+ socket.write(bytes_default().f().str(error2 + bytes_default.N).end());
6362
+ stream = null;
6363
+ },
6364
+ final(callback) {
6365
+ socket.write(bytes_default().c().end());
6366
+ final = callback;
6367
+ stream = null;
6368
+ }
6369
+ });
6370
+ query.resolve(stream);
6371
+ }
6372
+ function CopyOutResponse() {
6373
+ stream = new Stream.Readable({
6374
+ read() {
6375
+ socket.resume();
6376
+ }
6377
+ });
6378
+ query.resolve(stream);
6379
+ }
6380
+ function CopyBothResponse() {
6381
+ stream = new Stream.Duplex({
6382
+ autoDestroy: true,
6383
+ read() {
6384
+ socket.resume();
6385
+ },
6386
+ /* c8 ignore next 11 */
6387
+ write(chunk2, encoding, callback) {
6388
+ socket.write(bytes_default().d().raw(chunk2).end(), callback);
6389
+ },
6390
+ destroy(error2, callback) {
6391
+ callback(error2);
6392
+ socket.write(bytes_default().f().str(error2 + bytes_default.N).end());
6393
+ stream = null;
6394
+ },
6395
+ final(callback) {
6396
+ socket.write(bytes_default().c().end());
6397
+ final = callback;
6398
+ }
6399
+ });
6400
+ query.resolve(stream);
6401
+ }
6402
+ function CopyData(x) {
6403
+ stream && (stream.push(x.subarray(5)) || socket.pause());
6404
+ }
6405
+ function CopyDone() {
6406
+ stream && stream.push(null);
6407
+ stream = null;
6408
+ }
6409
+ function NoticeResponse(x) {
6410
+ onnotice ? onnotice(parseError(x)) : console.log(parseError(x));
6411
+ }
6412
+ function EmptyQueryResponse() {
6413
+ }
6414
+ function FunctionCallResponse() {
6415
+ errored(Errors.notSupported("FunctionCallResponse"));
6416
+ }
6417
+ function NegotiateProtocolVersion() {
6418
+ errored(Errors.notSupported("NegotiateProtocolVersion"));
6419
+ }
6420
+ function UnknownMessage(x) {
6421
+ console.error("Postgres.js : Unknown Message:", x[0]);
6422
+ }
6423
+ function UnknownAuth(x, type) {
6424
+ console.error("Postgres.js : Unknown Auth:", type);
6425
+ }
6426
+ function Bind(parameters, types2, statement = "", portal = "") {
6427
+ let prev, type;
6428
+ bytes_default().B().str(portal + bytes_default.N).str(statement + bytes_default.N).i16(0).i16(parameters.length);
6429
+ parameters.forEach((x, i) => {
6430
+ if (x === null)
6431
+ return bytes_default.i32(4294967295);
6432
+ type = types2[i];
6433
+ parameters[i] = x = type in options.serializers ? options.serializers[type](x) : "" + x;
6434
+ prev = bytes_default.i;
6435
+ bytes_default.inc(4).str(x).i32(bytes_default.i - prev - 4, prev);
6436
+ });
6437
+ bytes_default.i16(0);
6438
+ return bytes_default.end();
6439
+ }
6440
+ function Parse(str, parameters, types2, name = "") {
6441
+ bytes_default().P().str(name + bytes_default.N).str(str + bytes_default.N).i16(parameters.length);
6442
+ parameters.forEach((x, i) => bytes_default.i32(types2[i] || 0));
6443
+ return bytes_default.end();
6444
+ }
6445
+ function Describe(x, name = "") {
6446
+ return bytes_default().D().str(x).str(name + bytes_default.N).end();
6447
+ }
6448
+ function Execute(portal = "", rows2 = 0) {
6449
+ return Buffer.concat([
6450
+ bytes_default().E().str(portal + bytes_default.N).i32(rows2).end(),
6451
+ Flush
6452
+ ]);
6453
+ }
6454
+ function Close(portal = "") {
6455
+ return Buffer.concat([
6456
+ bytes_default().C().str("P").str(portal + bytes_default.N).end(),
6457
+ bytes_default().S().end()
6458
+ ]);
6459
+ }
6460
+ function StartupMessage() {
6461
+ return cancelMessage || bytes_default().inc(4).i16(3).z(2).str(
6462
+ Object.entries(Object.assign(
6463
+ {
6464
+ user,
6465
+ database,
6466
+ client_encoding: "UTF8"
6467
+ },
6468
+ options.connection
6469
+ )).filter(([, v]) => v).map(([k, v]) => k + bytes_default.N + v).join(bytes_default.N)
6470
+ ).z(2).end(0);
6471
+ }
6472
+ }
6473
+ function parseError(x) {
6474
+ const error = {};
6475
+ let start = 5;
6476
+ for (let i = 5; i < x.length - 1; i++) {
6477
+ if (x[i] === 0) {
6478
+ error[errorFields[x[start]]] = x.toString("utf8", start + 1, i);
6479
+ start = i + 1;
6480
+ }
6481
+ }
6482
+ return error;
6483
+ }
6484
+ function md5(x) {
6485
+ return crypto4.createHash("md5").update(x).digest("hex");
6486
+ }
6487
+ function hmac2(key, x) {
6488
+ return crypto4.createHmac("sha256", key).update(x).digest();
6489
+ }
6490
+ function sha2564(x) {
6491
+ return crypto4.createHash("sha256").update(x).digest();
6492
+ }
6493
+ function xor(a, b2) {
6494
+ const length = Math.max(a.length, b2.length);
6495
+ const buffer2 = Buffer.allocUnsafe(length);
6496
+ for (let i = 0; i < length; i++)
6497
+ buffer2[i] = a[i] ^ b2[i];
6498
+ return buffer2;
6499
+ }
6500
+ function timer(fn, seconds) {
6501
+ seconds = typeof seconds === "function" ? seconds() : seconds;
6502
+ if (!seconds)
6503
+ return { cancel: noop, start: noop };
6504
+ let timer2;
6505
+ return {
6506
+ cancel() {
6507
+ timer2 && (clearTimeout(timer2), timer2 = null);
6508
+ },
6509
+ start() {
6510
+ timer2 && clearTimeout(timer2);
6511
+ timer2 = setTimeout(done, seconds * 1e3, arguments);
6512
+ }
6513
+ };
6514
+ function done(args) {
6515
+ fn.apply(null, args);
6516
+ timer2 = null;
6517
+ }
6518
+ }
6519
+
6520
+ // node_modules/postgres/src/subscribe.js
6521
+ var noop2 = () => {
6522
+ };
6523
+ function Subscribe(postgres2, options) {
6524
+ const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {};
6525
+ let connection2, stream, ended = false;
6526
+ const sql = subscribe.sql = postgres2({
6527
+ ...options,
6528
+ transform: { column: {}, value: {}, row: {} },
6529
+ max: 1,
6530
+ fetch_types: false,
6531
+ idle_timeout: null,
6532
+ max_lifetime: null,
6533
+ connection: {
6534
+ ...options.connection,
6535
+ replication: "database"
6536
+ },
6537
+ onclose: async function() {
6538
+ if (ended)
6539
+ return;
6540
+ stream = null;
6541
+ state.pid = state.secret = void 0;
6542
+ connected(await init(sql, slot, options.publications));
6543
+ subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe()));
6544
+ },
6545
+ no_subscribe: true
6546
+ });
6547
+ const end = sql.end, close = sql.close;
6548
+ sql.end = async () => {
6549
+ ended = true;
6550
+ stream && await new Promise((r) => (stream.once("close", r), stream.end()));
6551
+ return end();
6552
+ };
6553
+ sql.close = async () => {
6554
+ stream && await new Promise((r) => (stream.once("close", r), stream.end()));
6555
+ return close();
6556
+ };
6557
+ return subscribe;
6558
+ async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) {
6559
+ event = parseEvent(event);
6560
+ if (!connection2)
6561
+ connection2 = init(sql, slot, options.publications);
6562
+ const subscriber = { fn, onsubscribe };
6563
+ const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event);
6564
+ const unsubscribe = () => {
6565
+ fns.delete(subscriber);
6566
+ fns.size === 0 && subscribers.delete(event);
6567
+ };
6568
+ return connection2.then((x) => {
6569
+ connected(x);
6570
+ onsubscribe();
6571
+ stream && stream.on("error", onerror);
6572
+ return { unsubscribe, state, sql };
6573
+ });
6574
+ }
6575
+ function connected(x) {
6576
+ stream = x.stream;
6577
+ state.pid = x.state.pid;
6578
+ state.secret = x.state.secret;
6579
+ }
6580
+ async function init(sql2, slot2, publications) {
6581
+ if (!publications)
6582
+ throw new Error("Missing publication names");
6583
+ const xs = await sql2.unsafe(
6584
+ `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`
6585
+ );
6586
+ const [x] = xs;
6587
+ const stream2 = await sql2.unsafe(
6588
+ `START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')`
6589
+ ).writable();
6590
+ const state2 = {
6591
+ lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex")))
6592
+ };
6593
+ stream2.on("data", data);
6594
+ stream2.on("error", error);
6595
+ stream2.on("close", sql2.close);
6596
+ return { stream: stream2, state: xs.state };
6597
+ function error(e) {
6598
+ console.error("Unexpected error during logical streaming - reconnecting", e);
6599
+ }
6600
+ function data(x2) {
6601
+ if (x2[0] === 119) {
6602
+ parse(x2.subarray(25), state2, sql2.options.parsers, handle, options.transform);
6603
+ } else if (x2[0] === 107 && x2[17]) {
6604
+ state2.lsn = x2.subarray(1, 9);
6605
+ pong();
6606
+ }
6607
+ }
6608
+ function handle(a, b2) {
6609
+ const path2 = b2.relation.schema + "." + b2.relation.table;
6610
+ call("*", a, b2);
6611
+ call("*:" + path2, a, b2);
6612
+ b2.relation.keys.length && call("*:" + path2 + "=" + b2.relation.keys.map((x2) => a[x2.name]), a, b2);
6613
+ call(b2.command, a, b2);
6614
+ call(b2.command + ":" + path2, a, b2);
6615
+ b2.relation.keys.length && call(b2.command + ":" + path2 + "=" + b2.relation.keys.map((x2) => a[x2.name]), a, b2);
6616
+ }
6617
+ function pong() {
6618
+ const x2 = Buffer.alloc(34);
6619
+ x2[0] = "r".charCodeAt(0);
6620
+ x2.fill(state2.lsn, 1);
6621
+ x2.writeBigInt64BE(BigInt(Date.now() - Date.UTC(2e3, 0, 1)) * BigInt(1e3), 25);
6622
+ stream2.write(x2);
6623
+ }
6624
+ }
6625
+ function call(x, a, b2) {
6626
+ subscribers.has(x) && subscribers.get(x).forEach(({ fn }) => fn(a, b2, x));
6627
+ }
6628
+ }
6629
+ function Time(x) {
6630
+ return new Date(Date.UTC(2e3, 0, 1) + Number(x / BigInt(1e3)));
6631
+ }
6632
+ function parse(x, state, parsers2, handle, transform) {
6633
+ const char = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc);
6634
+ Object.entries({
6635
+ R: (x2) => {
6636
+ let i = 1;
6637
+ const r = state[x2.readUInt32BE(i)] = {
6638
+ schema: x2.toString("utf8", i += 4, i = x2.indexOf(0, i)) || "pg_catalog",
6639
+ table: x2.toString("utf8", i + 1, i = x2.indexOf(0, i + 1)),
6640
+ columns: Array(x2.readUInt16BE(i += 2)),
6641
+ keys: []
6642
+ };
6643
+ i += 2;
6644
+ let columnIndex = 0, column;
6645
+ while (i < x2.length) {
6646
+ column = r.columns[columnIndex++] = {
6647
+ key: x2[i++],
6648
+ name: transform.column.from ? transform.column.from(x2.toString("utf8", i, i = x2.indexOf(0, i))) : x2.toString("utf8", i, i = x2.indexOf(0, i)),
6649
+ type: x2.readUInt32BE(i += 1),
6650
+ parser: parsers2[x2.readUInt32BE(i)],
6651
+ atttypmod: x2.readUInt32BE(i += 4)
6652
+ };
6653
+ column.key && r.keys.push(column);
6654
+ i += 4;
6655
+ }
6656
+ },
6657
+ Y: () => {
6658
+ },
6659
+ // Type
6660
+ O: () => {
6661
+ },
6662
+ // Origin
6663
+ B: (x2) => {
6664
+ state.date = Time(x2.readBigInt64BE(9));
6665
+ state.lsn = x2.subarray(1, 9);
6666
+ },
6667
+ I: (x2) => {
6668
+ let i = 1;
6669
+ const relation = state[x2.readUInt32BE(i)];
6670
+ const { row } = tuples(x2, relation.columns, i += 7, transform);
6671
+ handle(row, {
6672
+ command: "insert",
6673
+ relation
6674
+ });
6675
+ },
6676
+ D: (x2) => {
6677
+ let i = 1;
6678
+ const relation = state[x2.readUInt32BE(i)];
6679
+ i += 4;
6680
+ const key = x2[i] === 75;
6681
+ handle(
6682
+ key || x2[i] === 79 ? tuples(x2, relation.columns, i += 3, transform).row : null,
6683
+ {
6684
+ command: "delete",
6685
+ relation,
6686
+ key
6687
+ }
6688
+ );
6689
+ },
6690
+ U: (x2) => {
6691
+ let i = 1;
6692
+ const relation = state[x2.readUInt32BE(i)];
6693
+ i += 4;
6694
+ const key = x2[i] === 75;
6695
+ const xs = key || x2[i] === 79 ? tuples(x2, relation.columns, i += 3, transform) : null;
6696
+ xs && (i = xs.i);
6697
+ const { row } = tuples(x2, relation.columns, i + 3, transform);
6698
+ handle(row, {
6699
+ command: "update",
6700
+ relation,
6701
+ key,
6702
+ old: xs && xs.row
6703
+ });
6704
+ },
6705
+ T: () => {
6706
+ },
6707
+ // Truncate,
6708
+ C: () => {
6709
+ }
6710
+ // Commit
6711
+ }).reduce(char, {})[x[0]](x);
6712
+ }
6713
+ function tuples(x, columns, xi, transform) {
6714
+ let type, column, value;
6715
+ const row = transform.raw ? new Array(columns.length) : {};
6716
+ for (let i = 0; i < columns.length; i++) {
6717
+ type = x[xi++];
6718
+ column = columns[i];
6719
+ value = type === 110 ? null : type === 117 ? void 0 : column.parser === void 0 ? x.toString("utf8", xi + 4, xi += 4 + x.readUInt32BE(xi)) : column.parser.array === true ? column.parser(x.toString("utf8", xi + 5, xi += 4 + x.readUInt32BE(xi))) : column.parser(x.toString("utf8", xi + 4, xi += 4 + x.readUInt32BE(xi)));
6720
+ transform.raw ? row[i] = transform.raw === true ? value : transform.value.from ? transform.value.from(value, column) : value : row[column.name] = transform.value.from ? transform.value.from(value, column) : value;
6721
+ }
6722
+ return { i: xi, row: transform.row.from ? transform.row.from(row) : row };
6723
+ }
6724
+ function parseEvent(x) {
6725
+ const xs = x.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) || [];
6726
+ if (!xs)
6727
+ throw new Error("Malformed subscribe pattern: " + x);
6728
+ const [, command, path2, key] = xs;
6729
+ return (command || "*") + (path2 ? ":" + (path2.indexOf(".") === -1 ? "public." + path2 : path2) : "") + (key ? "=" + key : "");
6730
+ }
6731
+
6732
+ // node_modules/postgres/src/large.js
6733
+ import Stream2 from "stream";
6734
+ function largeObject(sql, oid, mode = 131072 | 262144) {
6735
+ return new Promise(async (resolve, reject) => {
6736
+ await sql.begin(async (sql2) => {
6737
+ let finish;
6738
+ !oid && ([{ oid }] = await sql2`select lo_creat(-1) as oid`);
6739
+ const [{ fd }] = await sql2`select lo_open(${oid}, ${mode}) as fd`;
6740
+ const lo = {
6741
+ writable,
6742
+ readable,
6743
+ close: () => sql2`select lo_close(${fd})`.then(finish),
6744
+ tell: () => sql2`select lo_tell64(${fd})`,
6745
+ read: (x) => sql2`select loread(${fd}, ${x}) as data`,
6746
+ write: (x) => sql2`select lowrite(${fd}, ${x})`,
6747
+ truncate: (x) => sql2`select lo_truncate64(${fd}, ${x})`,
6748
+ seek: (x, whence = 0) => sql2`select lo_lseek64(${fd}, ${x}, ${whence})`,
6749
+ size: () => sql2`
6750
+ select
6751
+ lo_lseek64(${fd}, location, 0) as position,
6752
+ seek.size
6753
+ from (
6754
+ select
6755
+ lo_lseek64($1, 0, 2) as size,
6756
+ tell.location
6757
+ from (select lo_tell64($1) as location) tell
6758
+ ) seek
6759
+ `
6760
+ };
6761
+ resolve(lo);
6762
+ return new Promise(async (r) => finish = r);
6763
+ async function readable({
6764
+ highWaterMark = 2048 * 8,
6765
+ start = 0,
6766
+ end = Infinity
6767
+ } = {}) {
6768
+ let max = end - start;
6769
+ start && await lo.seek(start);
6770
+ return new Stream2.Readable({
6771
+ highWaterMark,
6772
+ async read(size3) {
6773
+ const l = size3 > max ? size3 - max : size3;
6774
+ max -= size3;
6775
+ const [{ data }] = await lo.read(l);
6776
+ this.push(data);
6777
+ if (data.length < size3)
6778
+ this.push(null);
6779
+ }
6780
+ });
6781
+ }
6782
+ async function writable({
6783
+ highWaterMark = 2048 * 8,
6784
+ start = 0
6785
+ } = {}) {
6786
+ start && await lo.seek(start);
6787
+ return new Stream2.Writable({
6788
+ highWaterMark,
6789
+ write(chunk, encoding, callback) {
6790
+ lo.write(chunk).then(() => callback(), callback);
6791
+ }
6792
+ });
6793
+ }
6794
+ }).catch(reject);
6795
+ });
6796
+ }
6797
+
6798
+ // node_modules/postgres/src/index.js
6799
+ Object.assign(Postgres, {
6800
+ PostgresError,
6801
+ toPascal,
6802
+ pascal,
6803
+ toCamel,
6804
+ camel,
6805
+ toKebab,
6806
+ kebab,
6807
+ fromPascal,
6808
+ fromCamel,
6809
+ fromKebab,
6810
+ BigInt: {
6811
+ to: 20,
6812
+ from: [20],
6813
+ parse: (x) => BigInt(x),
6814
+ // eslint-disable-line
6815
+ serialize: (x) => x.toString()
6816
+ }
6817
+ });
6818
+ var src_default = Postgres;
6819
+ function Postgres(a, b2) {
6820
+ const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options });
6821
+ let ending = false;
6822
+ const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full };
6823
+ const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose }));
6824
+ const sql = Sql(handler);
6825
+ Object.assign(sql, {
6826
+ get parameters() {
6827
+ return options.parameters;
6828
+ },
6829
+ largeObject: largeObject.bind(null, sql),
6830
+ subscribe,
6831
+ CLOSE,
6832
+ END: CLOSE,
6833
+ PostgresError,
6834
+ options,
6835
+ reserve,
6836
+ listen,
6837
+ begin,
6838
+ close,
6839
+ end
6840
+ });
6841
+ return sql;
6842
+ function Sql(handler2) {
6843
+ handler2.debug = options.debug;
6844
+ Object.entries(options.types).reduce((acc, [name, type]) => {
6845
+ acc[name] = (x) => new Parameter(x, type.to);
6846
+ return acc;
6847
+ }, typed);
6848
+ Object.assign(sql2, {
6849
+ types: typed,
6850
+ typed,
6851
+ unsafe,
6852
+ notify,
6853
+ array,
6854
+ json,
6855
+ file
6856
+ });
6857
+ return sql2;
6858
+ function typed(value, type) {
6859
+ return new Parameter(value, type);
6860
+ }
6861
+ function sql2(strings, ...args) {
6862
+ const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args);
6863
+ return query;
6864
+ }
6865
+ function unsafe(string, args = [], options2 = {}) {
6866
+ arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []);
6867
+ const query = new Query([string], args, handler2, cancel, {
6868
+ prepare: false,
6869
+ ...options2,
6870
+ simple: "simple" in options2 ? options2.simple : args.length === 0
6871
+ });
6872
+ return query;
6873
+ }
6874
+ function file(path2, args = [], options2 = {}) {
6875
+ arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []);
6876
+ const query = new Query([], args, (query2) => {
6877
+ fs2.readFile(path2, "utf8", (err, string) => {
6878
+ if (err)
6879
+ return query2.reject(err);
6880
+ query2.strings = [string];
6881
+ handler2(query2);
6882
+ });
6883
+ }, cancel, {
6884
+ ...options2,
6885
+ simple: "simple" in options2 ? options2.simple : args.length === 0
6886
+ });
6887
+ return query;
6888
+ }
6889
+ }
6890
+ async function listen(name, fn, onlisten) {
6891
+ const listener = { fn, onlisten };
6892
+ const sql2 = listen.sql || (listen.sql = Postgres({
6893
+ ...options,
6894
+ max: 1,
6895
+ idle_timeout: null,
6896
+ max_lifetime: null,
6897
+ fetch_types: false,
6898
+ onclose() {
6899
+ Object.entries(listen.channels).forEach(([name2, { listeners }]) => {
6900
+ delete listen.channels[name2];
6901
+ Promise.all(listeners.map((l) => listen(name2, l.fn, l.onlisten).catch(() => {
6902
+ })));
6903
+ });
6904
+ },
6905
+ onnotify(c, x) {
6906
+ c in listen.channels && listen.channels[c].listeners.forEach((l) => l.fn(x));
6907
+ }
6908
+ }));
6909
+ const channels = listen.channels || (listen.channels = {}), exists = name in channels;
6910
+ if (exists) {
6911
+ channels[name].listeners.push(listener);
6912
+ const result2 = await channels[name].result;
6913
+ listener.onlisten && listener.onlisten();
6914
+ return { state: result2.state, unlisten };
6915
+ }
6916
+ channels[name] = { result: sql2`listen ${sql2.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] };
6917
+ const result = await channels[name].result;
6918
+ listener.onlisten && listener.onlisten();
6919
+ return { state: result.state, unlisten };
6920
+ async function unlisten() {
6921
+ if (name in channels === false)
6922
+ return;
6923
+ channels[name].listeners = channels[name].listeners.filter((x) => x !== listener);
6924
+ if (channels[name].listeners.length)
6925
+ return;
6926
+ delete channels[name];
6927
+ return sql2`unlisten ${sql2.unsafe('"' + name.replace(/"/g, '""') + '"')}`;
6928
+ }
6929
+ }
6930
+ async function notify(channel, payload) {
6931
+ return await sql`select pg_notify(${channel}, ${"" + payload})`;
6932
+ }
6933
+ async function reserve() {
6934
+ const queue = queue_default();
6935
+ const c = open.length ? open.shift() : await new Promise((resolve, reject) => {
6936
+ const query = { reserve: resolve, reject };
6937
+ queries.push(query);
6938
+ closed.length && connect(closed.shift(), query);
6939
+ });
6940
+ move(c, reserved);
6941
+ c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved);
6942
+ c.reserved.release = true;
6943
+ const sql2 = Sql(handler2);
6944
+ sql2.release = () => {
6945
+ c.reserved = null;
6946
+ onopen(c);
6947
+ };
6948
+ return sql2;
6949
+ function handler2(q) {
6950
+ c.queue === full ? queue.push(q) : c.execute(q) || move(c, full);
6951
+ }
6952
+ }
6953
+ async function begin(options2, fn) {
6954
+ !fn && (fn = options2, options2 = "");
6955
+ const queries2 = queue_default();
6956
+ let savepoints = 0, connection2, prepare = null;
6957
+ try {
6958
+ await sql.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute();
6959
+ return await Promise.race([
6960
+ scope(connection2, fn),
6961
+ new Promise((_, reject) => connection2.onclose = reject)
6962
+ ]);
6963
+ } catch (error) {
6964
+ throw error;
6965
+ }
6966
+ async function scope(c, fn2, name) {
6967
+ const sql2 = Sql(handler2);
6968
+ sql2.savepoint = savepoint;
6969
+ sql2.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi);
6970
+ let uncaughtError, result;
6971
+ name && await sql2`savepoint ${sql2(name)}`;
6972
+ try {
6973
+ result = await new Promise((resolve, reject) => {
6974
+ const x = fn2(sql2);
6975
+ Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject);
6976
+ });
6977
+ if (uncaughtError)
6978
+ throw uncaughtError;
6979
+ } catch (e) {
6980
+ await (name ? sql2`rollback to ${sql2(name)}` : sql2`rollback`);
6981
+ throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e;
6982
+ }
6983
+ if (!name) {
6984
+ prepare ? await sql2`prepare transaction '${sql2.unsafe(prepare)}'` : await sql2`commit`;
6985
+ }
6986
+ return result;
6987
+ function savepoint(name2, fn3) {
6988
+ if (name2 && Array.isArray(name2.raw))
6989
+ return savepoint((sql3) => sql3.apply(sql3, arguments));
6990
+ arguments.length === 1 && (fn3 = name2, name2 = null);
6991
+ return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : ""));
6992
+ }
6993
+ function handler2(q) {
6994
+ q.catch((e) => uncaughtError || (uncaughtError = e));
6995
+ c.queue === full ? queries2.push(q) : c.execute(q) || move(c, full);
6996
+ }
6997
+ }
6998
+ function onexecute(c) {
6999
+ connection2 = c;
7000
+ move(c, reserved);
7001
+ c.reserved = () => queries2.length ? c.execute(queries2.shift()) : move(c, reserved);
7002
+ }
7003
+ }
7004
+ function move(c, queue) {
7005
+ c.queue.remove(c);
7006
+ queue.push(c);
7007
+ c.queue = queue;
7008
+ queue === open ? c.idleTimer.start() : c.idleTimer.cancel();
7009
+ return c;
7010
+ }
7011
+ function json(x) {
7012
+ return new Parameter(x, 3802);
7013
+ }
7014
+ function array(x, type) {
7015
+ if (!Array.isArray(x))
7016
+ return array(Array.from(arguments));
7017
+ return new Parameter(x, type || (x.length ? inferType(x) || 25 : 0), options.shared.typeArrayMap);
7018
+ }
7019
+ function handler(query) {
7020
+ if (ending)
7021
+ return query.reject(Errors.connection("CONNECTION_ENDED", options, options));
7022
+ if (open.length)
7023
+ return go(open.shift(), query);
7024
+ if (closed.length)
7025
+ return connect(closed.shift(), query);
7026
+ busy.length ? go(busy.shift(), query) : queries.push(query);
7027
+ }
7028
+ function go(c, query) {
7029
+ return c.execute(query) ? move(c, busy) : move(c, full);
7030
+ }
7031
+ function cancel(query) {
7032
+ return new Promise((resolve, reject) => {
7033
+ query.state ? query.active ? connection_default(options).cancel(query.state, resolve, reject) : query.cancelled = { resolve, reject } : (queries.remove(query), query.cancelled = true, query.reject(Errors.generic("57014", "canceling statement due to user request")), resolve());
7034
+ });
7035
+ }
7036
+ async function end({ timeout = null } = {}) {
7037
+ if (ending)
7038
+ return ending;
7039
+ await 1;
7040
+ let timer2;
7041
+ return ending = Promise.race([
7042
+ new Promise((r) => timeout !== null && (timer2 = setTimeout(destroy, timeout * 1e3, r))),
7043
+ Promise.all(connections.map((c) => c.end()).concat(
7044
+ listen.sql ? listen.sql.end({ timeout: 0 }) : [],
7045
+ subscribe.sql ? subscribe.sql.end({ timeout: 0 }) : []
7046
+ ))
7047
+ ]).then(() => clearTimeout(timer2));
7048
+ }
7049
+ async function close() {
7050
+ await Promise.all(connections.map((c) => c.end()));
7051
+ }
7052
+ async function destroy(resolve) {
7053
+ await Promise.all(connections.map((c) => c.terminate()));
7054
+ while (queries.length)
7055
+ queries.shift().reject(Errors.connection("CONNECTION_DESTROYED", options));
7056
+ resolve();
7057
+ }
7058
+ function connect(c, query) {
7059
+ move(c, connecting);
7060
+ c.connect(query);
7061
+ return c;
7062
+ }
7063
+ function onend(c) {
7064
+ move(c, ended);
7065
+ }
7066
+ function onopen(c) {
7067
+ if (queries.length === 0)
7068
+ return move(c, open);
7069
+ let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true;
7070
+ while (ready && queries.length && max-- > 0) {
7071
+ const query = queries.shift();
7072
+ if (query.reserve)
7073
+ return query.reserve(c);
7074
+ ready = c.execute(query);
7075
+ }
7076
+ ready ? move(c, busy) : move(c, full);
7077
+ }
7078
+ function onclose(c, e) {
7079
+ move(c, closed);
7080
+ c.reserved = null;
7081
+ c.onclose && (c.onclose(e), c.onclose = null);
7082
+ options.onclose && options.onclose(c.id);
7083
+ queries.length && connect(c, queries.shift());
7084
+ }
7085
+ }
7086
+ function parseOptions(a, b2) {
7087
+ if (a && a.shared)
7088
+ return a;
7089
+ const env = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url, multihost } = parseUrl(a), query = [...url.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url.hostname || env.PGHOST || "localhost", port = o.port || url.port || env.PGPORT || 5432, user = o.user || o.username || url.username || env.PGUSERNAME || env.PGUSER || osUsername();
7090
+ o.no_prepare && (o.prepare = false);
7091
+ query.sslmode && (query.ssl = query.sslmode, delete query.sslmode);
7092
+ "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout);
7093
+ query.sslrootcert === "system" && (query.ssl = "verify-full");
7094
+ const ints = ["idle_timeout", "connect_timeout", "max_lifetime", "max_pipeline", "backoff", "keep_alive"];
7095
+ const defaults = {
7096
+ max: globalThis.Cloudflare ? 3 : 10,
7097
+ ssl: false,
7098
+ sslnegotiation: null,
7099
+ idle_timeout: null,
7100
+ connect_timeout: 30,
7101
+ max_lifetime,
7102
+ max_pipeline: 100,
7103
+ backoff,
7104
+ keep_alive: 60,
7105
+ prepare: true,
7106
+ debug: false,
7107
+ fetch_types: true,
7108
+ publications: "alltables",
7109
+ target_session_attrs: null
7110
+ };
7111
+ return {
7112
+ host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]),
7113
+ port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)),
7114
+ path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port,
7115
+ database: o.database || o.db || (url.pathname || "").slice(1) || env.PGDATABASE || user,
7116
+ user,
7117
+ pass: o.pass || o.password || url.password || env.PGPASSWORD || "",
7118
+ ...Object.entries(defaults).reduce(
7119
+ (acc, [k, d]) => {
7120
+ const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env["PG" + k.toUpperCase()] || d;
7121
+ acc[k] = typeof value === "string" && ints.includes(k) ? +value : value;
7122
+ return acc;
7123
+ },
7124
+ {}
7125
+ ),
7126
+ connection: {
7127
+ application_name: env.PGAPPNAME || "postgres.js",
7128
+ ...o.connection,
7129
+ ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {})
7130
+ },
7131
+ types: o.types || {},
7132
+ target_session_attrs: tsa(o, url, env),
7133
+ onnotice: o.onnotice,
7134
+ onnotify: o.onnotify,
7135
+ onclose: o.onclose,
7136
+ onparameter: o.onparameter,
7137
+ socket: o.socket,
7138
+ transform: parseTransform(o.transform || { undefined: void 0 }),
7139
+ parameters: {},
7140
+ shared: { retries: 0, typeArrayMap: {} },
7141
+ ...mergeUserTypes(o.types)
7142
+ };
7143
+ }
7144
+ function tsa(o, url, env) {
7145
+ const x = o.target_session_attrs || url.searchParams.get("target_session_attrs") || env.PGTARGETSESSIONATTRS;
7146
+ if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x))
7147
+ return x;
7148
+ throw new Error("target_session_attrs " + x + " is not supported");
7149
+ }
7150
+ function backoff(retries) {
7151
+ return (0.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20);
7152
+ }
7153
+ function max_lifetime() {
7154
+ return 60 * (30 + Math.random() * 30);
7155
+ }
7156
+ function parseTransform(x) {
7157
+ return {
7158
+ undefined: x.undefined,
7159
+ column: {
7160
+ from: typeof x.column === "function" ? x.column : x.column && x.column.from,
7161
+ to: x.column && x.column.to
7162
+ },
7163
+ value: {
7164
+ from: typeof x.value === "function" ? x.value : x.value && x.value.from,
7165
+ to: x.value && x.value.to
7166
+ },
7167
+ row: {
7168
+ from: typeof x.row === "function" ? x.row : x.row && x.row.from,
7169
+ to: x.row && x.row.to
7170
+ }
7171
+ };
7172
+ }
7173
+ function parseUrl(url) {
7174
+ if (!url || typeof url !== "string")
7175
+ return { url: { searchParams: /* @__PURE__ */ new Map() } };
7176
+ let host = url;
7177
+ host = host.slice(host.indexOf("://") + 3).split(/[?/]/)[0];
7178
+ host = decodeURIComponent(host.slice(host.indexOf("@") + 1));
7179
+ const urlObj = new URL(url.replace(host, host.split(",")[0]));
7180
+ return {
7181
+ url: {
7182
+ username: decodeURIComponent(urlObj.username),
7183
+ password: decodeURIComponent(urlObj.password),
7184
+ host: urlObj.host,
7185
+ hostname: urlObj.hostname,
7186
+ port: urlObj.port,
7187
+ pathname: urlObj.pathname,
7188
+ searchParams: urlObj.searchParams
7189
+ },
7190
+ multihost: host.indexOf(",") > -1 && host
7191
+ };
7192
+ }
7193
+ function osUsername() {
7194
+ try {
7195
+ return os.userInfo().username;
7196
+ } catch (_) {
7197
+ return process.env.USERNAME || process.env.USER || process.env.LOGNAME;
7198
+ }
7199
+ }
7200
+
7201
+ // src/postgres-redemption.mjs
7202
+ var claimId = (key) => createHash("sha256").update(String(key)).digest("hex");
7203
+ var EXPIRY_GRACE_MS = 60001;
7204
+ async function createPostgresRedemptionStore({ url } = {}) {
7205
+ const retentionMs = DEFAULT_RETENTION_MS;
7206
+ const sql = src_default(url, {
7207
+ max: 1,
7208
+ connect_timeout: 5,
7209
+ idle_timeout: 20,
7210
+ connection: { application_name: "mtok-relay", statement_timeout: 5e3, lock_timeout: 5e3, synchronous_commit: "on" },
7211
+ onnotice() {
7212
+ }
7213
+ });
7214
+ const expiryMs = retentionMs + EXPIRY_GRACE_MS;
7215
+ let initialized = false;
7216
+ try {
7217
+ await sql.begin(async (tx) => {
7218
+ await tx`select pg_advisory_xact_lock(hashtext('mtok_redemptions_v1'))`;
7219
+ await tx`
7220
+ create table if not exists mtok_redemptions (
7221
+ claimkey text primary key
7222
+ , state text not null check (state in ('pending', 'complete'))
7223
+ , payload jsonb
7224
+ , expiresat timestamptz not null
7225
+ , check ((state = 'pending' and payload is null) or (state = 'complete' and payload is not null))
7226
+ )
7227
+ `;
7228
+ await tx`create index if not exists mtok_redemptions_expiry on mtok_redemptions (expiresat)`;
7229
+ await tx`
7230
+ create table if not exists mtok_redemption_keys (
7231
+ keyid text primary key
7232
+ , claimkey text not null references mtok_redemptions (claimkey) on delete cascade
7233
+ )
7234
+ `;
7235
+ await tx`create index if not exists mtok_redemption_keys_claim on mtok_redemption_keys (claimkey)`;
7236
+ await tx`
7237
+ delete from mtok_redemptions
7238
+ where
7239
+ claimkey in (
7240
+ select claimkey from mtok_redemptions
7241
+ where expiresat < current_timestamp
7242
+ order by expiresat
7243
+ limit 256
7244
+ )
7245
+ `;
7246
+ });
7247
+ initialized = true;
7248
+ } finally {
7249
+ if (!initialized) await sql.end({ timeout: 1 });
7250
+ }
7251
+ const store = {
7252
+ durable: true,
7253
+ retentionMs,
7254
+ async state(key) {
7255
+ const [row] = await sql`
7256
+ select
7257
+ r.state
7258
+ from
7259
+ mtok_redemption_keys k
7260
+ join mtok_redemptions r on
7261
+ r.claimkey = k.claimkey
7262
+ where
7263
+ k.keyid = ${claimId(key)}
7264
+ `;
7265
+ return row?.state ?? null;
7266
+ },
7267
+ async get(key) {
7268
+ const [row] = await sql`
7269
+ select
7270
+ r.payload
7271
+ from
7272
+ mtok_redemption_keys k
7273
+ join mtok_redemptions r on
7274
+ r.claimkey = k.claimkey
7275
+ and r.state = 'complete'
7276
+ where
7277
+ k.keyid = ${claimId(key)}
7278
+ `;
7279
+ return row?.payload;
7280
+ },
7281
+ async claim(key, markerKey = key) {
7282
+ const id = claimId(key);
7283
+ if (markerKey !== key && key !== `legacy-v0:${markerKey}`) throw new TypeError("redemption marker does not match its claim");
7284
+ const aliases = [.../* @__PURE__ */ new Set([id, claimId(markerKey)])].sort();
7285
+ try {
7286
+ await sql.begin(async (tx) => {
7287
+ await tx`
7288
+ insert into mtok_redemptions (claimkey, state, expiresat)
7289
+ values (${id}, 'pending', current_timestamp + ${expiryMs} * interval '1 millisecond')
7290
+ `;
7291
+ await tx`
7292
+ insert into mtok_redemption_keys (keyid, claimkey)
7293
+ select
7294
+ unnest(${aliases}::text[])
7295
+ , ${id}
7296
+ `;
7297
+ });
7298
+ return true;
7299
+ } catch (error) {
7300
+ if (error.code === "23505" && ["mtok_redemptions_pkey", "mtok_redemption_keys_pkey"].includes(error.constraint_name)) return false;
7301
+ throw error;
7302
+ }
7303
+ },
7304
+ async complete(key, payload) {
7305
+ const rows = await sql`
7306
+ update mtok_redemptions
7307
+ set payload = ${sql.json(payload)}
7308
+ , state = 'complete'
7309
+ , expiresat = current_timestamp + ${expiryMs} * interval '1 millisecond'
7310
+ where
7311
+ claimkey = (select claimkey from mtok_redemption_keys where keyid = ${claimId(key)})
7312
+ and state = 'pending'
7313
+ returning claimkey
7314
+ `;
7315
+ if (rows.length !== 1) throw new Error("redemption is not pending");
7316
+ },
7317
+ async importRecord({ key, state, payload }) {
7318
+ if (!["pending", "complete"].includes(state)) throw new TypeError("invalid imported redemption state");
7319
+ if (state === "complete" && payload == null) throw new TypeError("completed redemption needs a payload");
7320
+ await store.claim(key);
7321
+ if (state === "pending") return;
7322
+ await sql.begin(async (tx) => {
7323
+ const [existing] = await tx`
7324
+ select
7325
+ r.claimkey
7326
+ from
7327
+ mtok_redemption_keys k
7328
+ join mtok_redemptions r on
7329
+ r.claimkey = k.claimkey
7330
+ where
7331
+ k.keyid = ${claimId(key)}
7332
+ for update of r
7333
+ `;
7334
+ await tx`
7335
+ update mtok_redemptions
7336
+ set state = 'complete', payload = ${tx.json(payload)}
7337
+ where
7338
+ claimkey = ${existing.claimkey}
7339
+ and state = 'pending'
7340
+ `;
7341
+ const [row] = await tx`
7342
+ select
7343
+ payload = ${tx.json(payload)} as matches
7344
+ from
7345
+ mtok_redemptions
7346
+ where
7347
+ claimkey = ${existing.claimkey}
7348
+ `;
7349
+ if (!row.matches) throw new Error("conflicting completed redemption records");
7350
+ });
7351
+ },
7352
+ close() {
7353
+ return sql.end({ timeout: 5 });
7354
+ }
7355
+ };
7356
+ return store;
7357
+ }
7358
+
5068
7359
  // core/onchain.js
5069
7360
  var TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
5070
7361
  var DRAW_PAID_TOPIC = "0xb0243f80521d0dccd159389597aba96047e60ba5d7a9df12b67e5cb75230ac41";
@@ -5080,9 +7371,9 @@ var asciiFromHex = (hex) => {
5080
7371
  const bytes = strip0x(hex);
5081
7372
  const out = [];
5082
7373
  for (let i = 0; i < bytes.length; i += 2) {
5083
- const b = parseInt(bytes.slice(i, i + 2), 16);
5084
- if (!Number.isFinite(b)) break;
5085
- out.push(b);
7374
+ const b2 = parseInt(bytes.slice(i, i + 2), 16);
7375
+ if (!Number.isFinite(b2)) break;
7376
+ out.push(b2);
5086
7377
  }
5087
7378
  return new TextDecoder().decode(new Uint8Array(out));
5088
7379
  };
@@ -5369,7 +7660,7 @@ var REQUEST_KEYS = /* @__PURE__ */ new Set(["model", "messages", "max_tokens", "
5369
7660
  async function hash32(v) {
5370
7661
  const bytes = new TextEncoder().encode(typeof v === "string" ? v : JSON.stringify(v ?? null));
5371
7662
  const digest = await crypto.subtle.digest("SHA-256", bytes);
5372
- return "0x" + [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
7663
+ return "0x" + [...new Uint8Array(digest)].map((b2) => b2.toString(16).padStart(2, "0")).join("");
5373
7664
  }
5374
7665
  function legacyContentText(content) {
5375
7666
  const render = (part) => {
@@ -5447,10 +7738,10 @@ function normalizeModelId(m) {
5447
7738
  }
5448
7739
  function modelsCompatible(upstreamModel, offerModel) {
5449
7740
  const a = normalizeModelId(upstreamModel);
5450
- const b = normalizeModelId(offerModel);
5451
- if (!a || !b) return false;
5452
- if (a === b) return true;
5453
- const [longer, shorter] = a.length >= b.length ? [a, b] : [b, a];
7741
+ const b2 = normalizeModelId(offerModel);
7742
+ if (!a || !b2) return false;
7743
+ if (a === b2) return true;
7744
+ const [longer, shorter] = a.length >= b2.length ? [a, b2] : [b2, a];
5454
7745
  if (!longer.startsWith(shorter)) return false;
5455
7746
  const rest = longer.slice(shorter.length);
5456
7747
  return /^([-._]\d+)+$/.test(rest);
@@ -5466,11 +7757,11 @@ function configuredFeeAtomic({ sellerUsdAtomic, feeAddress, feeBps }) {
5466
7757
  }
5467
7758
  var MESSAGE_OVERHEAD_TOKENS = 4;
5468
7759
  var BYTES_PER_TOKEN_EST = 3.2;
5469
- function estimateInputTokens(messages) {
7760
+ function estimateInputTokens(messages2) {
5470
7761
  const utf8 = new TextEncoder();
5471
7762
  let bytes = 0;
5472
7763
  let envelope = 3;
5473
- for (const m of messages ?? []) {
7764
+ for (const m of messages2 ?? []) {
5474
7765
  envelope += MESSAGE_OVERHEAD_TOKENS;
5475
7766
  bytes += utf8.encode(String(m?.role ?? "")).length;
5476
7767
  bytes += utf8.encode(typeof m?.content === "string" ? m.content : JSON.stringify(m?.content ?? null)).length;
@@ -5478,8 +7769,8 @@ function estimateInputTokens(messages) {
5478
7769
  return envelope + Math.ceil(bytes / BYTES_PER_TOKEN_EST);
5479
7770
  }
5480
7771
  var DEFAULT_MAX_OUTPUT_TOKENS = 32768;
5481
- function boundServe({ messages, budgetUsd, inPrice, outPrice, reqMax, contextCeil = DEFAULT_MAX_OUTPUT_TOKENS }) {
5482
- const estIn = estimateInputTokens(messages);
7772
+ function boundServe({ messages: messages2, budgetUsd, inPrice, outPrice, reqMax, contextCeil = DEFAULT_MAX_OUTPUT_TOKENS }) {
7773
+ const estIn = estimateInputTokens(messages2);
5483
7774
  const estInCostUsd = estIn * (Number(inPrice) > 0 ? Number(inPrice) : 0) / 1e6;
5484
7775
  if (estInCostUsd >= budgetUsd) return { refuse: true, reason: "input", estIn, estInCostUsd };
5485
7776
  const outBudgetUsd = budgetUsd - estInCostUsd;
@@ -5532,19 +7823,20 @@ function createServeCore({
5532
7823
  const requestHash = hasRequestNonce ? await hash32({ request, requestNonce }) : await hash32(request);
5533
7824
  const cacheKey = `${requestHashScheme}:${bookingId}:${n}:${requestHash}`;
5534
7825
  const oldLegacyKey = hasRequestNonce ? null : `${bookingId}:${n}:${requestHash}`;
7826
+ const redemptionContext = { claimKey: cacheKey };
5535
7827
  if (!dripContractAddress) {
5536
7828
  return { status: 402, body: { error: "contract_mode_required", detail: "this relay only serves contract-mode draws; the platform is not reporting a dripContractAddress" } };
5537
7829
  }
5538
7830
  if (!drawPaidTxHash) return { status: 402, body: { error: "draw_payment_required", detail: "contract mode requires drawPaidTxHash before upstream delivery" } };
5539
7831
  let storedKey = cacheKey;
5540
- let redemptionState = await redemption.state(storedKey);
7832
+ let redemptionState = await redemption.state(storedKey, redemptionContext);
5541
7833
  if (!redemptionState && oldLegacyKey) {
5542
- const oldLegacyState = await redemption.state(oldLegacyKey);
7834
+ const oldLegacyState = await redemption.state(oldLegacyKey, redemptionContext);
5543
7835
  if (oldLegacyState) {
5544
7836
  storedKey = oldLegacyKey;
5545
7837
  redemptionState = oldLegacyState;
5546
7838
  } else {
5547
- redemptionState = await redemption.state(cacheKey);
7839
+ redemptionState = await redemption.state(cacheKey, redemptionContext);
5548
7840
  }
5549
7841
  }
5550
7842
  let paid;
@@ -5580,7 +7872,11 @@ function createServeCore({
5580
7872
  return { status: 403, body: { error: "payer_denied", detail: "payer screening failed: " + e.message } };
5581
7873
  }
5582
7874
  }
5583
- if (redemptionState === "complete") return { status: 200, body: await redemption.get(storedKey) };
7875
+ if (redemptionState === "complete") {
7876
+ const payload2 = await redemption.get(storedKey, redemptionContext);
7877
+ if (payload2 == null) return { status: 503, body: { error: "redemption_unavailable", detail: "saved completion is no longer readable; retry this same paid draw", _bookingId: bookingId } };
7878
+ return { status: 200, body: payload2 };
7879
+ }
5584
7880
  if (redemptionState === "pending") {
5585
7881
  return { status: 409, body: { error: "draw_pending", detail: "this paid draw was already claimed; refusing to run upstream again", _bookingId: bookingId } };
5586
7882
  }
@@ -5611,7 +7907,7 @@ function createServeCore({
5611
7907
  }
5612
7908
  const safeRequest = { ...checked.safeRequest, model, max_tokens: bound.maxTok };
5613
7909
  try {
5614
- if (!await redemption.claim(cacheKey, oldLegacyKey ?? cacheKey)) {
7910
+ if (!await redemption.claim(cacheKey, oldLegacyKey ?? cacheKey, { paidAtMs: paid.paidAtMs })) {
5615
7911
  return { status: 409, body: { error: "draw_pending", detail: "this paid draw was already claimed; refusing to run upstream again", _bookingId: bookingId } };
5616
7912
  }
5617
7913
  } catch (e) {
@@ -5685,7 +7981,6 @@ var rpcUrlsFor = (chainId, override) => override ? [override] : Number(chainId)
5685
7981
 
5686
7982
  // src/runtime.mjs
5687
7983
  async function createRelayRuntime(config) {
5688
- const served = createRedemptionStore({ file: config.redemptionFile, log: config.log });
5689
7984
  const drawLocks = /* @__PURE__ */ new Map();
5690
7985
  const platform = await fetchPlatformConfig(config);
5691
7986
  const FEE_REFRESH_MS = 6e4;
@@ -5709,6 +8004,7 @@ async function createRelayRuntime(config) {
5709
8004
  };
5710
8005
  const verifier = createOnchainVerifier({ rpcUrls: rpcUrlsFor(platform.chainId, config.rpcFlag), usdcAddress: platform.usdcAddress, expectedChainId: platform.chainId });
5711
8006
  if (!verifier.configured) throw new Error("onchain verifier not configured (missing usdcAddress in /api/config)");
8007
+ const served = config.redemptionDatabaseUrl ? await createPostgresRedemptionStore({ url: config.redemptionDatabaseUrl }) : createRedemptionStore({ file: config.redemptionFile, log: config.log });
5712
8008
  const payerDenylist = new Set((config.payerDenylist ?? []).map((a) => String(a).trim().toLowerCase()).filter(Boolean));
5713
8009
  const screenPayer = typeof config.screenPayer === "function" ? config.screenPayer : null;
5714
8010
  const upstream = httpUpstream({ baseUrl: config.upstream + "/v1", key: config.upstreamKey, timeoutMs: config.upstreamTimeoutMs ?? 12e4 });
@@ -5773,7 +8069,7 @@ async function createRelayRuntime(config) {
5773
8069
  active--;
5774
8070
  }
5775
8071
  };
5776
- return { handleDraw };
8072
+ return { handleDraw, close: () => served.close?.() };
5777
8073
  }
5778
8074
  async function fetchPlatformConfig(config) {
5779
8075
  const r = await fetch(config.apiBase + "/api/config", { signal: AbortSignal.timeout(5e3) });
@@ -5789,11 +8085,58 @@ async function fetchPlatformConfig(config) {
5789
8085
  };
5790
8086
  }
5791
8087
 
8088
+ // src/import-redemptions.mjs
8089
+ import fs3 from "node:fs";
8090
+ import path from "node:path";
8091
+ import { createHash as createHash2 } from "node:crypto";
8092
+ async function importRedemptionFiles(store, files) {
8093
+ let imported = 0;
8094
+ for (const file of files) {
8095
+ for (const [index, line] of fs3.readFileSync(file, "utf8").split("\n").entries()) {
8096
+ if (!line.trim()) continue;
8097
+ const record = JSON.parse(line);
8098
+ const state = record.state ?? "complete";
8099
+ if (typeof record.k !== "string" || !record.k || !Number.isFinite(Number(record.at))) {
8100
+ throw new Error(`malformed redemption record at ${file}:${index + 1}`);
8101
+ }
8102
+ await store.importRecord({ key: record.k, state, payload: record.payload });
8103
+ imported++;
8104
+ }
8105
+ const directory = `${file}.claims`;
8106
+ if (!fs3.existsSync(directory)) continue;
8107
+ for (const name of fs3.readdirSync(directory)) {
8108
+ const text = fs3.readFileSync(path.join(directory, name), "utf8");
8109
+ const key = text.endsWith("\n") ? text.slice(0, -1) : text;
8110
+ if (!key || createHash2("sha256").update(key).digest("hex") !== name) {
8111
+ throw new Error(`malformed redemption marker in ${directory}`);
8112
+ }
8113
+ await store.importRecord({ key, state: "pending" });
8114
+ imported++;
8115
+ }
8116
+ }
8117
+ return imported;
8118
+ }
8119
+
5792
8120
  // mtok-relay.mjs
5793
8121
  try {
5794
- const config = readRelayConfig();
5795
- const runtime = await createRelayRuntime(config);
5796
- startRelayServer({ config, ...runtime });
8122
+ if (process.argv[2] === "import-redemptions") {
8123
+ const files = process.argv.slice(3);
8124
+ if (!files.length || !process.env.RELAY_REDEMPTION_DATABASE_URL) {
8125
+ throw new Error("import-redemptions needs one or more JSONL paths and RELAY_REDEMPTION_DATABASE_URL");
8126
+ }
8127
+ const store = await createPostgresRedemptionStore({ url: process.env.RELAY_REDEMPTION_DATABASE_URL });
8128
+ try {
8129
+ const count = await importRedemptionFiles(store, files);
8130
+ console.log(`mtok-relay: imported ${count} redemption records and markers`);
8131
+ } finally {
8132
+ await store.close();
8133
+ }
8134
+ } else {
8135
+ const config = readRelayConfig();
8136
+ const runtime = await createRelayRuntime(config);
8137
+ const server = startRelayServer({ config, ...runtime });
8138
+ server.on("close", () => runtime.close());
8139
+ }
5797
8140
  } catch (e) {
5798
8141
  console.error("mtok-relay: boot failed -", e.message);
5799
8142
  process.exit(1);