@tradejs/cli 2.0.4 → 2.0.6

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.
@@ -6,7 +6,11 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __commonJS = (cb, mod) => function __require() {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ try {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ } catch (e) {
12
+ throw mod = 0, e;
13
+ }
10
14
  };
11
15
  var __export = (target, all) => {
12
16
  for (var name in all)
@@ -971,11 +975,16 @@ var require_pg_types = __commonJS({
971
975
  var require_defaults = __commonJS({
972
976
  "../../node_modules/pg/lib/defaults.js"(exports2, module2) {
973
977
  "use strict";
978
+ var user;
979
+ try {
980
+ user = process.platform === "win32" ? process.env.USERNAME : process.env.USER;
981
+ } catch {
982
+ }
974
983
  module2.exports = {
975
984
  // database host. defaults to localhost
976
985
  host: "localhost",
977
986
  // database user's name
978
- user: process.platform === "win32" ? process.env.USERNAME : process.env.USER,
987
+ user,
979
988
  // name of database to connect
980
989
  database: void 0,
981
990
  // database user's password
@@ -1000,6 +1009,8 @@ var require_defaults = __commonJS({
1000
1009
  idleTimeoutMillis: 3e4,
1001
1010
  client_encoding: "",
1002
1011
  ssl: false,
1012
+ // SSL negotiation style: 'postgres' (traditional SSLRequest) or 'direct'
1013
+ sslnegotiation: void 0,
1003
1014
  application_name: void 0,
1004
1015
  fallback_application_name: void 0,
1005
1016
  options: void 0,
@@ -1034,8 +1045,7 @@ var require_utils = __commonJS({
1034
1045
  "../../node_modules/pg/lib/utils.js"(exports2, module2) {
1035
1046
  "use strict";
1036
1047
  var defaults2 = require_defaults();
1037
- var util = require("util");
1038
- var { isDate } = util.types || util;
1048
+ var { isDate } = require("util/types");
1039
1049
  function escapeElement(elementRepresentation) {
1040
1050
  const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
1041
1051
  return '"' + escaped + '"';
@@ -1044,28 +1054,23 @@ var require_utils = __commonJS({
1044
1054
  let result = "{";
1045
1055
  for (let i = 0; i < val.length; i++) {
1046
1056
  if (i > 0) {
1047
- result = result + ",";
1048
- }
1049
- if (val[i] === null || typeof val[i] === "undefined") {
1050
- result = result + "NULL";
1051
- } else if (Array.isArray(val[i])) {
1052
- result = result + arrayString(val[i]);
1053
- } else if (ArrayBuffer.isView(val[i])) {
1054
- let item = val[i];
1057
+ result += ",";
1058
+ }
1059
+ let item = val[i];
1060
+ if (item == null) {
1061
+ result += "NULL";
1062
+ } else if (Array.isArray(item)) {
1063
+ result += arrayString(item);
1064
+ } else if (ArrayBuffer.isView(item)) {
1055
1065
  if (!(item instanceof Buffer)) {
1056
- const buf = Buffer.from(item.buffer, item.byteOffset, item.byteLength);
1057
- if (buf.length === item.byteLength) {
1058
- item = buf;
1059
- } else {
1060
- item = buf.slice(item.byteOffset, item.byteOffset + item.byteLength);
1061
- }
1066
+ item = Buffer.from(item.buffer, item.byteOffset, item.byteLength);
1062
1067
  }
1063
1068
  result += "\\\\x" + item.toString("hex");
1064
1069
  } else {
1065
- result += escapeElement(prepareValue(val[i]));
1070
+ result += escapeElement(prepareValue(item));
1066
1071
  }
1067
1072
  }
1068
- result = result + "}";
1073
+ result += "}";
1069
1074
  return result;
1070
1075
  }
1071
1076
  var prepareValue = function(val, seen) {
@@ -1077,11 +1082,7 @@ var require_utils = __commonJS({
1077
1082
  return val;
1078
1083
  }
1079
1084
  if (ArrayBuffer.isView(val)) {
1080
- const buf = Buffer.from(val.buffer, val.byteOffset, val.byteLength);
1081
- if (buf.length === val.byteLength) {
1082
- return buf;
1083
- }
1084
- return buf.slice(val.byteOffset, val.byteOffset + val.byteLength);
1085
+ return Buffer.from(val.buffer, val.byteOffset, val.byteLength);
1085
1086
  }
1086
1087
  if (isDate(val)) {
1087
1088
  if (defaults2.parseInputDatesAsUTC) {
@@ -1187,47 +1188,9 @@ var require_utils = __commonJS({
1187
1188
  }
1188
1189
  });
1189
1190
 
1190
- // ../../node_modules/pg/lib/crypto/utils-legacy.js
1191
- var require_utils_legacy = __commonJS({
1192
- "../../node_modules/pg/lib/crypto/utils-legacy.js"(exports2, module2) {
1193
- "use strict";
1194
- var nodeCrypto = require("crypto");
1195
- function md5(string) {
1196
- return nodeCrypto.createHash("md5").update(string, "utf-8").digest("hex");
1197
- }
1198
- function postgresMd5PasswordHash(user, password, salt) {
1199
- const inner = md5(password + user);
1200
- const outer = md5(Buffer.concat([Buffer.from(inner), salt]));
1201
- return "md5" + outer;
1202
- }
1203
- function sha256(text) {
1204
- return nodeCrypto.createHash("sha256").update(text).digest();
1205
- }
1206
- function hashByName(hashName, text) {
1207
- hashName = hashName.replace(/(\D)-/, "$1");
1208
- return nodeCrypto.createHash(hashName).update(text).digest();
1209
- }
1210
- function hmacSha256(key, msg) {
1211
- return nodeCrypto.createHmac("sha256", key).update(msg).digest();
1212
- }
1213
- async function deriveKey(password, salt, iterations) {
1214
- return nodeCrypto.pbkdf2Sync(password, salt, iterations, 32, "sha256");
1215
- }
1216
- module2.exports = {
1217
- postgresMd5PasswordHash,
1218
- randomBytes: nodeCrypto.randomBytes,
1219
- deriveKey,
1220
- sha256,
1221
- hashByName,
1222
- hmacSha256,
1223
- md5
1224
- };
1225
- }
1226
- });
1227
-
1228
- // ../../node_modules/pg/lib/crypto/utils-webcrypto.js
1229
- var require_utils_webcrypto = __commonJS({
1230
- "../../node_modules/pg/lib/crypto/utils-webcrypto.js"(exports2, module2) {
1191
+ // ../../node_modules/pg/lib/crypto/utils.js
1192
+ var require_utils2 = __commonJS({
1193
+ "../../node_modules/pg/lib/crypto/utils.js"(exports2, module2) {
1231
1194
  "use strict";
1232
1195
  var nodeCrypto = require("crypto");
1233
1196
  module2.exports = {
@@ -1277,19 +1240,6 @@ var require_utils_webcrypto = __commonJS({
1277
1240
  }
1278
1241
  });
1279
1242
 
1280
- // ../../node_modules/pg/lib/crypto/utils.js
1281
- var require_utils2 = __commonJS({
1282
- "../../node_modules/pg/lib/crypto/utils.js"(exports2, module2) {
1283
- "use strict";
1284
- var useLegacyCrypto = parseInt(process.versions && process.versions.node && process.versions.node.split(".")[0]) < 15;
1285
- if (useLegacyCrypto) {
1286
- module2.exports = require_utils_legacy();
1287
- } else {
1288
- module2.exports = require_utils_webcrypto();
1289
- }
1290
- }
1291
- });
1292
-
1293
1243
  // ../../node_modules/pg/lib/crypto/cert-signatures.js
1294
1244
  var require_cert_signatures = __commonJS({
1295
1245
  "../../node_modules/pg/lib/crypto/cert-signatures.js"(exports2, module2) {
@@ -1410,7 +1360,13 @@ var require_sasl = __commonJS({
1410
1360
  "use strict";
1411
1361
  var crypto = require_utils2();
1412
1362
  var { signatureAlgorithmHashFromCertificate } = require_cert_signatures();
1413
- function startSession(mechanisms, stream) {
1363
+ function saslprep(password) {
1364
+ const nonAsciiSpace = /[\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000]/g;
1365
+ const mappedToNothing = /[\u00AD\u034F\u1806\u180B\u180C\u180D\u200C\u200D\u2060\uFE00-\uFE0F\uFEFF]/g;
1366
+ return password.replace(nonAsciiSpace, " ").replace(mappedToNothing, "").normalize("NFKC");
1367
+ }
1368
+ var DEFAULT_MAX_SCRAM_ITERATIONS = 1e5;
1369
+ function startSession(mechanisms, stream, scramMaxIterations = DEFAULT_MAX_SCRAM_ITERATIONS) {
1414
1370
  const candidates = ["SCRAM-SHA-256"];
1415
1371
  if (stream) candidates.unshift("SCRAM-SHA-256-PLUS");
1416
1372
  const mechanism = candidates.find((candidate) => mechanisms.includes(candidate));
@@ -1426,7 +1382,8 @@ var require_sasl = __commonJS({
1426
1382
  mechanism,
1427
1383
  clientNonce,
1428
1384
  response: gs2Header + ",,n=*,r=" + clientNonce,
1429
- message: "SASLInitialResponse"
1385
+ message: "SASLInitialResponse",
1386
+ scramMaxIterations
1430
1387
  };
1431
1388
  }
1432
1389
  async function continueSession(session, password, serverData, stream) {
@@ -1448,6 +1405,12 @@ var require_sasl = __commonJS({
1448
1405
  } else if (sv.nonce.length === session.clientNonce.length) {
1449
1406
  throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");
1450
1407
  }
1408
+ const scramMaxIterations = typeof session.scramMaxIterations === "number" ? session.scramMaxIterations : DEFAULT_MAX_SCRAM_ITERATIONS;
1409
+ if (scramMaxIterations !== 0 && sv.iteration > scramMaxIterations) {
1410
+ throw new Error(
1411
+ "SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration count " + sv.iteration + " exceeds scramMaxIterations of " + scramMaxIterations
1412
+ );
1413
+ }
1451
1414
  const clientFirstMessageBare = "n=*,r=" + session.clientNonce;
1452
1415
  const serverFirstMessage = "r=" + sv.nonce + ",s=" + sv.salt + ",i=" + sv.iteration;
1453
1416
  let channelBinding = stream ? "eSws" : "biws";
@@ -1462,7 +1425,7 @@ var require_sasl = __commonJS({
1462
1425
  const clientFinalMessageWithoutProof = "c=" + channelBinding + ",r=" + sv.nonce;
1463
1426
  const authMessage = clientFirstMessageBare + "," + serverFirstMessage + "," + clientFinalMessageWithoutProof;
1464
1427
  const saltBytes = Buffer.from(sv.salt, "base64");
1465
- const saltedPassword = await crypto.deriveKey(password, saltBytes, sv.iteration);
1428
+ const saltedPassword = await crypto.deriveKey(saslprep(password), saltBytes, sv.iteration);
1466
1429
  const clientKey = await crypto.hmacSha256(saltedPassword, "Client Key");
1467
1430
  const storedKey = await crypto.sha256(clientKey);
1468
1431
  const clientSignature = await crypto.hmacSha256(storedKey, authMessage);
@@ -1538,7 +1501,11 @@ var require_sasl = __commonJS({
1538
1501
  }
1539
1502
  function parseServerFinalMessage(serverData) {
1540
1503
  const attrPairs = parseAttributePairs(serverData);
1504
+ const error = attrPairs.get("e");
1541
1505
  const serverSignature = attrPairs.get("v");
1506
+ if (error) {
1507
+ throw new Error(`SASL: SCRAM-SERVER-FINAL-MESSAGE: server returned error: "${error}"`);
1508
+ }
1542
1509
  if (!serverSignature) {
1543
1510
  throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");
1544
1511
  } else if (!isBase64(serverSignature)) {
@@ -1566,7 +1533,8 @@ var require_sasl = __commonJS({
1566
1533
  module2.exports = {
1567
1534
  startSession,
1568
1535
  continueSession,
1569
- finalizeSession
1536
+ finalizeSession,
1537
+ DEFAULT_MAX_SCRAM_ITERATIONS
1570
1538
  };
1571
1539
  }
1572
1540
  });
@@ -1615,7 +1583,7 @@ var require_pg_connection_string = __commonJS({
1615
1583
  const config2 = str.split(" ");
1616
1584
  return { host: config2[0], database: config2[1] };
1617
1585
  }
1618
- const config = {};
1586
+ const config = /* @__PURE__ */ Object.create(null);
1619
1587
  let result;
1620
1588
  let dummyHost = false;
1621
1589
  if (/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str)) {
@@ -1630,6 +1598,7 @@ var require_pg_connection_string = __commonJS({
1630
1598
  }
1631
1599
  } catch (err) {
1632
1600
  err.input && (err.input = "*****REDACTED*****");
1601
+ throw err;
1633
1602
  }
1634
1603
  for (const entry of result.searchParams.entries()) {
1635
1604
  config[entry[0]] = entry[1];
@@ -1662,6 +1631,9 @@ var require_pg_connection_string = __commonJS({
1662
1631
  if (config.sslcert || config.sslkey || config.sslrootcert || config.sslmode) {
1663
1632
  config.ssl = {};
1664
1633
  }
1634
+ if (config.sslnegotiation === "direct" && config.ssl === void 0) {
1635
+ config.ssl = true;
1636
+ }
1665
1637
  const fs = config.sslcert || config.sslkey || config.sslrootcert ? require("fs") : null;
1666
1638
  if (config.sslcert) {
1667
1639
  config.ssl.cert = fs.readFileSync(config.sslcert).toString();
@@ -1718,6 +1690,9 @@ var require_pg_connection_string = __commonJS({
1718
1690
  case "require":
1719
1691
  case "verify-ca":
1720
1692
  case "verify-full": {
1693
+ if (config.sslmode !== "verify-full") {
1694
+ deprecatedSslModeWarning(config.sslmode);
1695
+ }
1721
1696
  break;
1722
1697
  }
1723
1698
  case "no-verify": {
@@ -1734,7 +1709,7 @@ var require_pg_connection_string = __commonJS({
1734
1709
  c[key] = value;
1735
1710
  }
1736
1711
  return c;
1737
- }, {});
1712
+ }, /* @__PURE__ */ Object.create(null));
1738
1713
  return connectionOptions;
1739
1714
  }
1740
1715
  function toClientConfig(config) {
@@ -1761,12 +1736,25 @@ var require_pg_connection_string = __commonJS({
1761
1736
  }
1762
1737
  }
1763
1738
  return c;
1764
- }, {});
1739
+ }, /* @__PURE__ */ Object.create(null));
1765
1740
  return poolConfig;
1766
1741
  }
1767
1742
  function parseIntoClientConfig(str) {
1768
1743
  return toClientConfig(parse(str));
1769
1744
  }
1745
+ function deprecatedSslModeWarning(sslmode) {
1746
+ if (!deprecatedSslModeWarning.warned && typeof process !== "undefined" && process.emitWarning) {
1747
+ deprecatedSslModeWarning.warned = true;
1748
+ process.emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'.
1749
+ In the next major version (pg-connection-string v3.0.0 and pg v9.0.0), these modes will adopt standard libpq semantics, which have weaker security guarantees.
1750
+
1751
+ To prepare for this change:
1752
+ - If you want the current behavior, explicitly use 'sslmode=verify-full'
1753
+ - If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${sslmode}'
1754
+
1755
+ See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`);
1756
+ }
1757
+ }
1770
1758
  module2.exports = parse;
1771
1759
  parse.parse = parse;
1772
1760
  parse.toClientConfig = toClientConfig;
@@ -1782,13 +1770,16 @@ var require_connection_parameters = __commonJS({
1782
1770
  var defaults2 = require_defaults();
1783
1771
  var parse = require_pg_connection_string().parse;
1784
1772
  var val = function(key, config, envVar) {
1773
+ if (config[key]) {
1774
+ return config[key];
1775
+ }
1785
1776
  if (envVar === void 0) {
1786
1777
  envVar = process.env["PG" + key.toUpperCase()];
1787
1778
  } else if (envVar === false) {
1788
1779
  } else {
1789
1780
  envVar = process.env[envVar];
1790
1781
  }
1791
- return config[key] || envVar || defaults2[key];
1782
+ return envVar || defaults2[key];
1792
1783
  };
1793
1784
  var readSSLConfigFromEnvironment = function() {
1794
1785
  switch (process.env.PGSSLMODE) {
@@ -1848,6 +1839,15 @@ var require_connection_parameters = __commonJS({
1848
1839
  enumerable: false
1849
1840
  });
1850
1841
  }
1842
+ this.sslnegotiation = val("sslnegotiation", config, "PGSSLNEGOTIATION");
1843
+ if (this.sslnegotiation !== void 0 && this.sslnegotiation !== "postgres" && this.sslnegotiation !== "direct") {
1844
+ throw new Error(
1845
+ `Invalid sslnegotiation value: "${this.sslnegotiation}". Valid values are "postgres" and "direct".`
1846
+ );
1847
+ }
1848
+ if (this.sslnegotiation === "direct" && !this.ssl) {
1849
+ throw new Error("sslnegotiation=direct requires SSL to be enabled");
1850
+ }
1851
1851
  this.client_encoding = val("client_encoding", config);
1852
1852
  this.replication = val("replication", config);
1853
1853
  this.isDomainSocket = !(this.host || "").indexOf("/");
@@ -1886,6 +1886,7 @@ var require_connection_parameters = __commonJS({
1886
1886
  add(params, ssl, "sslkey");
1887
1887
  add(params, ssl, "sslcert");
1888
1888
  add(params, ssl, "sslrootcert");
1889
+ add(params, this, "sslnegotiation");
1889
1890
  if (this.database) {
1890
1891
  params.push("dbname=" + quoteParamValue(this.database));
1891
1892
  }
@@ -1986,7 +1987,7 @@ var require_result = __commonJS({
1986
1987
  if (this.fields.length) {
1987
1988
  this._parsers = new Array(fieldDescriptions.length);
1988
1989
  }
1989
- const row = {};
1990
+ const row = /* @__PURE__ */ Object.create(null);
1990
1991
  for (let i = 0; i < fieldDescriptions.length; i++) {
1991
1992
  const desc = fieldDescriptions[i];
1992
1993
  row[desc.name] = null;
@@ -2181,6 +2182,8 @@ var require_query = __commonJS({
2181
2182
  valueMapper: utils.prepareValue
2182
2183
  });
2183
2184
  } catch (err) {
2185
+ connection.close({ type: "S", name: this.name });
2186
+ connection.sync();
2184
2187
  this.handleError(err, connection);
2185
2188
  return;
2186
2189
  }
@@ -2200,9 +2203,9 @@ var require_query = __commonJS({
2200
2203
  }
2201
2204
  });
2202
2205
 
2203
- // ../../node_modules/pg-protocol/dist/messages.js
2206
+ // ../../node_modules/pg/node_modules/pg-protocol/dist/messages.js
2204
2207
  var require_messages = __commonJS({
2205
- "../../node_modules/pg-protocol/dist/messages.js"(exports2) {
2208
+ "../../node_modules/pg/node_modules/pg-protocol/dist/messages.js"(exports2) {
2206
2209
  "use strict";
2207
2210
  Object.defineProperty(exports2, "__esModule", { value: true });
2208
2211
  exports2.NoticeMessage = exports2.DataRowMessage = exports2.CommandCompleteMessage = exports2.ReadyForQueryMessage = exports2.NotificationResponseMessage = exports2.BackendKeyDataMessage = exports2.AuthenticationMD5Password = exports2.ParameterStatusMessage = exports2.ParameterDescriptionMessage = exports2.RowDescriptionMessage = exports2.Field = exports2.CopyResponse = exports2.CopyDataMessage = exports2.DatabaseError = exports2.copyDone = exports2.emptyQuery = exports2.replicationStart = exports2.portalSuspended = exports2.noData = exports2.closeComplete = exports2.bindComplete = exports2.parseComplete = void 0;
@@ -2365,9 +2368,9 @@ var require_messages = __commonJS({
2365
2368
  }
2366
2369
  });
2367
2370
 
2368
- // ../../node_modules/pg-protocol/dist/buffer-writer.js
2371
+ // ../../node_modules/pg/node_modules/pg-protocol/dist/buffer-writer.js
2369
2372
  var require_buffer_writer = __commonJS({
2370
- "../../node_modules/pg-protocol/dist/buffer-writer.js"(exports2) {
2373
+ "../../node_modules/pg/node_modules/pg-protocol/dist/buffer-writer.js"(exports2) {
2371
2374
  "use strict";
2372
2375
  Object.defineProperty(exports2, "__esModule", { value: true });
2373
2376
  exports2.Writer = void 0;
@@ -2420,6 +2423,25 @@ var require_buffer_writer = __commonJS({
2420
2423
  this.offset += len;
2421
2424
  return this;
2422
2425
  }
2426
+ // Write an Int32 byte-length prefix immediately followed by the string's UTF-8
2427
+ // bytes. Postgres' Bind wire format prefixes every parameter with its length,
2428
+ // and doing it in one method computes Buffer.byteLength ONCE — the previous
2429
+ // `addInt32(Buffer.byteLength(s)).addString(s)` pairing scanned the string
2430
+ // three times (byteLength for the prefix, byteLength again inside addString,
2431
+ // then the encode), which is costly for large text parameters.
2432
+ addInt32PrefixedString(string) {
2433
+ const len = Buffer.byteLength(string);
2434
+ this.ensure(4 + len);
2435
+ const buffer = this.buffer;
2436
+ let offset = this.offset;
2437
+ buffer[offset++] = len >>> 24 & 255;
2438
+ buffer[offset++] = len >>> 16 & 255;
2439
+ buffer[offset++] = len >>> 8 & 255;
2440
+ buffer[offset++] = len >>> 0 & 255;
2441
+ buffer.write(string, offset, "utf-8");
2442
+ this.offset = offset + len;
2443
+ return this;
2444
+ }
2423
2445
  add(otherBuffer) {
2424
2446
  this.ensure(otherBuffer.length);
2425
2447
  otherBuffer.copy(this.buffer, this.offset);
@@ -2441,14 +2463,18 @@ var require_buffer_writer = __commonJS({
2441
2463
  this.buffer = Buffer.allocUnsafe(this.size);
2442
2464
  return result;
2443
2465
  }
2466
+ clear() {
2467
+ this.offset = 5;
2468
+ this.headerPosition = 0;
2469
+ }
2444
2470
  };
2445
2471
  exports2.Writer = Writer;
2446
2472
  }
2447
2473
  });
2448
2474
 
2449
- // ../../node_modules/pg-protocol/dist/serializer.js
2475
+ // ../../node_modules/pg/node_modules/pg-protocol/dist/serializer.js
2450
2476
  var require_serializer = __commonJS({
2451
- "../../node_modules/pg-protocol/dist/serializer.js"(exports2) {
2477
+ "../../node_modules/pg/node_modules/pg-protocol/dist/serializer.js"(exports2) {
2452
2478
  "use strict";
2453
2479
  Object.defineProperty(exports2, "__esModule", { value: true });
2454
2480
  exports2.serialize = void 0;
@@ -2477,7 +2503,7 @@ var require_serializer = __commonJS({
2477
2503
  );
2478
2504
  };
2479
2505
  var sendSASLInitialResponseMessage = function(mechanism, initialResponse) {
2480
- writer.addCString(mechanism).addInt32(Buffer.byteLength(initialResponse)).addString(initialResponse);
2506
+ writer.addCString(mechanism).addInt32PrefixedString(initialResponse);
2481
2507
  return writer.flush(
2482
2508
  112
2483
2509
  /* code.startup */
@@ -2536,8 +2562,7 @@ var require_serializer = __commonJS({
2536
2562
  0
2537
2563
  /* ParamType.STRING */
2538
2564
  );
2539
- paramWriter.addInt32(Buffer.byteLength(mappedVal));
2540
- paramWriter.addString(mappedVal);
2565
+ paramWriter.addInt32PrefixedString(mappedVal);
2541
2566
  }
2542
2567
  }
2543
2568
  };
@@ -2549,7 +2574,13 @@ var require_serializer = __commonJS({
2549
2574
  const len = values.length;
2550
2575
  writer.addCString(portal).addCString(statement);
2551
2576
  writer.addInt16(len);
2552
- writeValues(values, config.valueMapper);
2577
+ try {
2578
+ writeValues(values, config.valueMapper);
2579
+ } catch (err) {
2580
+ writer.clear();
2581
+ paramWriter.clear();
2582
+ throw err;
2583
+ }
2553
2584
  writer.addInt16(len);
2554
2585
  writer.add(paramWriter.flush());
2555
2586
  writer.addInt16(1);
@@ -2663,17 +2694,16 @@ var require_serializer = __commonJS({
2663
2694
  }
2664
2695
  });
2665
2696
 
2666
- // ../../node_modules/pg-protocol/dist/buffer-reader.js
2697
+ // ../../node_modules/pg/node_modules/pg-protocol/dist/buffer-reader.js
2667
2698
  var require_buffer_reader = __commonJS({
2668
- "../../node_modules/pg-protocol/dist/buffer-reader.js"(exports2) {
2699
+ "../../node_modules/pg/node_modules/pg-protocol/dist/buffer-reader.js"(exports2) {
2669
2700
  "use strict";
2670
2701
  Object.defineProperty(exports2, "__esModule", { value: true });
2671
2702
  exports2.BufferReader = void 0;
2672
- var emptyBuffer = Buffer.allocUnsafe(0);
2673
2703
  var BufferReader = class {
2674
2704
  constructor(offset = 0) {
2675
2705
  this.offset = offset;
2676
- this.buffer = emptyBuffer;
2706
+ this.buffer = Buffer.allocUnsafe(0);
2677
2707
  this.encoding = "utf-8";
2678
2708
  }
2679
2709
  setBuffer(offset, buffer) {
@@ -2708,7 +2738,7 @@ var require_buffer_reader = __commonJS({
2708
2738
  cstring() {
2709
2739
  const start = this.offset;
2710
2740
  let end = start;
2711
- while (this.buffer[end++] !== 0) {
2741
+ while (this.buffer[end++]) {
2712
2742
  }
2713
2743
  this.offset = end;
2714
2744
  return this.buffer.toString(this.encoding, start, end - 1);
@@ -2723,9 +2753,9 @@ var require_buffer_reader = __commonJS({
2723
2753
  }
2724
2754
  });
2725
2755
 
2726
- // ../../node_modules/pg-protocol/dist/parser.js
2756
+ // ../../node_modules/pg/node_modules/pg-protocol/dist/parser.js
2727
2757
  var require_parser = __commonJS({
2728
- "../../node_modules/pg-protocol/dist/parser.js"(exports2) {
2758
+ "../../node_modules/pg/node_modules/pg-protocol/dist/parser.js"(exports2) {
2729
2759
  "use strict";
2730
2760
  Object.defineProperty(exports2, "__esModule", { value: true });
2731
2761
  exports2.Parser = void 0;
@@ -2734,6 +2764,7 @@ var require_parser = __commonJS({
2734
2764
  var CODE_LENGTH = 1;
2735
2765
  var LEN_LENGTH = 4;
2736
2766
  var HEADER_LENGTH = CODE_LENGTH + LEN_LENGTH;
2767
+ var LATEINIT_LENGTH = -1;
2737
2768
  var emptyBuffer = Buffer.allocUnsafe(0);
2738
2769
  var Parser = class {
2739
2770
  constructor(opts) {
@@ -2799,229 +2830,243 @@ var require_parser = __commonJS({
2799
2830
  }
2800
2831
  }
2801
2832
  handlePacket(offset, code, length, bytes) {
2833
+ const { reader } = this;
2834
+ reader.setBuffer(offset, bytes);
2835
+ let message;
2802
2836
  switch (code) {
2803
2837
  case 50:
2804
- return messages_1.bindComplete;
2838
+ message = messages_1.bindComplete;
2839
+ break;
2805
2840
  case 49:
2806
- return messages_1.parseComplete;
2841
+ message = messages_1.parseComplete;
2842
+ break;
2807
2843
  case 51:
2808
- return messages_1.closeComplete;
2844
+ message = messages_1.closeComplete;
2845
+ break;
2809
2846
  case 110:
2810
- return messages_1.noData;
2847
+ message = messages_1.noData;
2848
+ break;
2811
2849
  case 115:
2812
- return messages_1.portalSuspended;
2850
+ message = messages_1.portalSuspended;
2851
+ break;
2813
2852
  case 99:
2814
- return messages_1.copyDone;
2853
+ message = messages_1.copyDone;
2854
+ break;
2815
2855
  case 87:
2816
- return messages_1.replicationStart;
2856
+ message = messages_1.replicationStart;
2857
+ break;
2817
2858
  case 73:
2818
- return messages_1.emptyQuery;
2859
+ message = messages_1.emptyQuery;
2860
+ break;
2819
2861
  case 68:
2820
- return this.parseDataRowMessage(offset, length, bytes);
2862
+ message = parseDataRowMessage(reader);
2863
+ break;
2821
2864
  case 67:
2822
- return this.parseCommandCompleteMessage(offset, length, bytes);
2865
+ message = parseCommandCompleteMessage(reader);
2866
+ break;
2823
2867
  case 90:
2824
- return this.parseReadyForQueryMessage(offset, length, bytes);
2868
+ message = parseReadyForQueryMessage(reader);
2869
+ break;
2825
2870
  case 65:
2826
- return this.parseNotificationMessage(offset, length, bytes);
2871
+ message = parseNotificationMessage(reader);
2872
+ break;
2827
2873
  case 82:
2828
- return this.parseAuthenticationResponse(offset, length, bytes);
2874
+ message = parseAuthenticationResponse(reader, length);
2875
+ break;
2829
2876
  case 83:
2830
- return this.parseParameterStatusMessage(offset, length, bytes);
2877
+ message = parseParameterStatusMessage(reader);
2878
+ break;
2831
2879
  case 75:
2832
- return this.parseBackendKeyData(offset, length, bytes);
2880
+ message = parseBackendKeyData(reader);
2881
+ break;
2833
2882
  case 69:
2834
- return this.parseErrorMessage(offset, length, bytes, "error");
2883
+ message = parseErrorMessage(reader, "error");
2884
+ break;
2835
2885
  case 78:
2836
- return this.parseErrorMessage(offset, length, bytes, "notice");
2837
- case 84:
2838
- return this.parseRowDescriptionMessage(offset, length, bytes);
2839
- case 116:
2840
- return this.parseParameterDescriptionMessage(offset, length, bytes);
2841
- case 71:
2842
- return this.parseCopyInMessage(offset, length, bytes);
2843
- case 72:
2844
- return this.parseCopyOutMessage(offset, length, bytes);
2845
- case 100:
2846
- return this.parseCopyData(offset, length, bytes);
2847
- default:
2848
- return new messages_1.DatabaseError("received invalid response: " + code.toString(16), length, "error");
2849
- }
2850
- }
2851
- parseReadyForQueryMessage(offset, length, bytes) {
2852
- this.reader.setBuffer(offset, bytes);
2853
- const status = this.reader.string(1);
2854
- return new messages_1.ReadyForQueryMessage(length, status);
2855
- }
2856
- parseCommandCompleteMessage(offset, length, bytes) {
2857
- this.reader.setBuffer(offset, bytes);
2858
- const text = this.reader.cstring();
2859
- return new messages_1.CommandCompleteMessage(length, text);
2860
- }
2861
- parseCopyData(offset, length, bytes) {
2862
- const chunk = bytes.slice(offset, offset + (length - 4));
2863
- return new messages_1.CopyDataMessage(length, chunk);
2864
- }
2865
- parseCopyInMessage(offset, length, bytes) {
2866
- return this.parseCopyMessage(offset, length, bytes, "copyInResponse");
2867
- }
2868
- parseCopyOutMessage(offset, length, bytes) {
2869
- return this.parseCopyMessage(offset, length, bytes, "copyOutResponse");
2870
- }
2871
- parseCopyMessage(offset, length, bytes, messageName) {
2872
- this.reader.setBuffer(offset, bytes);
2873
- const isBinary = this.reader.byte() !== 0;
2874
- const columnCount = this.reader.int16();
2875
- const message = new messages_1.CopyResponse(length, messageName, isBinary, columnCount);
2876
- for (let i = 0; i < columnCount; i++) {
2877
- message.columnTypes[i] = this.reader.int16();
2878
- }
2879
- return message;
2880
- }
2881
- parseNotificationMessage(offset, length, bytes) {
2882
- this.reader.setBuffer(offset, bytes);
2883
- const processId = this.reader.int32();
2884
- const channel = this.reader.cstring();
2885
- const payload = this.reader.cstring();
2886
- return new messages_1.NotificationResponseMessage(length, processId, channel, payload);
2887
- }
2888
- parseRowDescriptionMessage(offset, length, bytes) {
2889
- this.reader.setBuffer(offset, bytes);
2890
- const fieldCount = this.reader.int16();
2891
- const message = new messages_1.RowDescriptionMessage(length, fieldCount);
2892
- for (let i = 0; i < fieldCount; i++) {
2893
- message.fields[i] = this.parseField();
2894
- }
2895
- return message;
2896
- }
2897
- parseField() {
2898
- const name = this.reader.cstring();
2899
- const tableID = this.reader.uint32();
2900
- const columnID = this.reader.int16();
2901
- const dataTypeID = this.reader.uint32();
2902
- const dataTypeSize = this.reader.int16();
2903
- const dataTypeModifier = this.reader.int32();
2904
- const mode = this.reader.int16() === 0 ? "text" : "binary";
2905
- return new messages_1.Field(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, mode);
2906
- }
2907
- parseParameterDescriptionMessage(offset, length, bytes) {
2908
- this.reader.setBuffer(offset, bytes);
2909
- const parameterCount = this.reader.int16();
2910
- const message = new messages_1.ParameterDescriptionMessage(length, parameterCount);
2911
- for (let i = 0; i < parameterCount; i++) {
2912
- message.dataTypeIDs[i] = this.reader.int32();
2913
- }
2914
- return message;
2915
- }
2916
- parseDataRowMessage(offset, length, bytes) {
2917
- this.reader.setBuffer(offset, bytes);
2918
- const fieldCount = this.reader.int16();
2919
- const fields = new Array(fieldCount);
2920
- for (let i = 0; i < fieldCount; i++) {
2921
- const len = this.reader.int32();
2922
- fields[i] = len === -1 ? null : this.reader.string(len);
2923
- }
2924
- return new messages_1.DataRowMessage(length, fields);
2925
- }
2926
- parseParameterStatusMessage(offset, length, bytes) {
2927
- this.reader.setBuffer(offset, bytes);
2928
- const name = this.reader.cstring();
2929
- const value = this.reader.cstring();
2930
- return new messages_1.ParameterStatusMessage(length, name, value);
2931
- }
2932
- parseBackendKeyData(offset, length, bytes) {
2933
- this.reader.setBuffer(offset, bytes);
2934
- const processID = this.reader.int32();
2935
- const secretKey = this.reader.int32();
2936
- return new messages_1.BackendKeyDataMessage(length, processID, secretKey);
2937
- }
2938
- parseAuthenticationResponse(offset, length, bytes) {
2939
- this.reader.setBuffer(offset, bytes);
2940
- const code = this.reader.int32();
2941
- const message = {
2942
- name: "authenticationOk",
2943
- length
2944
- };
2945
- switch (code) {
2946
- case 0:
2886
+ message = parseErrorMessage(reader, "notice");
2947
2887
  break;
2948
- case 3:
2949
- if (message.length === 8) {
2950
- message.name = "authenticationCleartextPassword";
2951
- }
2888
+ case 84:
2889
+ message = parseRowDescriptionMessage(reader);
2952
2890
  break;
2953
- case 5:
2954
- if (message.length === 12) {
2955
- message.name = "authenticationMD5Password";
2956
- const salt = this.reader.bytes(4);
2957
- return new messages_1.AuthenticationMD5Password(length, salt);
2958
- }
2891
+ case 116:
2892
+ message = parseParameterDescriptionMessage(reader);
2959
2893
  break;
2960
- case 10:
2961
- {
2962
- message.name = "authenticationSASL";
2963
- message.mechanisms = [];
2964
- let mechanism;
2965
- do {
2966
- mechanism = this.reader.cstring();
2967
- if (mechanism) {
2968
- message.mechanisms.push(mechanism);
2969
- }
2970
- } while (mechanism);
2971
- }
2894
+ case 71:
2895
+ message = parseCopyInMessage(reader);
2972
2896
  break;
2973
- case 11:
2974
- message.name = "authenticationSASLContinue";
2975
- message.data = this.reader.string(length - 8);
2897
+ case 72:
2898
+ message = parseCopyOutMessage(reader);
2976
2899
  break;
2977
- case 12:
2978
- message.name = "authenticationSASLFinal";
2979
- message.data = this.reader.string(length - 8);
2900
+ case 100:
2901
+ message = parseCopyData(reader, length);
2980
2902
  break;
2981
2903
  default:
2982
- throw new Error("Unknown authenticationOk message type " + code);
2904
+ return new messages_1.DatabaseError("received invalid response: " + code.toString(16), length, "error");
2983
2905
  }
2984
- return message;
2985
- }
2986
- parseErrorMessage(offset, length, bytes, name) {
2987
- this.reader.setBuffer(offset, bytes);
2988
- const fields = {};
2989
- let fieldType = this.reader.string(1);
2990
- while (fieldType !== "\0") {
2991
- fields[fieldType] = this.reader.cstring();
2992
- fieldType = this.reader.string(1);
2993
- }
2994
- const messageValue = fields.M;
2995
- const message = name === "notice" ? new messages_1.NoticeMessage(length, messageValue) : new messages_1.DatabaseError(messageValue, length, name);
2996
- message.severity = fields.S;
2997
- message.code = fields.C;
2998
- message.detail = fields.D;
2999
- message.hint = fields.H;
3000
- message.position = fields.P;
3001
- message.internalPosition = fields.p;
3002
- message.internalQuery = fields.q;
3003
- message.where = fields.W;
3004
- message.schema = fields.s;
3005
- message.table = fields.t;
3006
- message.column = fields.c;
3007
- message.dataType = fields.d;
3008
- message.constraint = fields.n;
3009
- message.file = fields.F;
3010
- message.line = fields.L;
3011
- message.routine = fields.R;
2906
+ reader.setBuffer(0, emptyBuffer);
2907
+ message.length = length;
3012
2908
  return message;
3013
2909
  }
3014
2910
  };
3015
2911
  exports2.Parser = Parser;
2912
+ var parseReadyForQueryMessage = (reader) => {
2913
+ const status = reader.string(1);
2914
+ return new messages_1.ReadyForQueryMessage(LATEINIT_LENGTH, status);
2915
+ };
2916
+ var parseCommandCompleteMessage = (reader) => {
2917
+ const text = reader.cstring();
2918
+ return new messages_1.CommandCompleteMessage(LATEINIT_LENGTH, text);
2919
+ };
2920
+ var parseCopyData = (reader, length) => {
2921
+ const chunk = reader.bytes(length - 4);
2922
+ return new messages_1.CopyDataMessage(LATEINIT_LENGTH, chunk);
2923
+ };
2924
+ var parseCopyInMessage = (reader) => parseCopyMessage(reader, "copyInResponse");
2925
+ var parseCopyOutMessage = (reader) => parseCopyMessage(reader, "copyOutResponse");
2926
+ var parseCopyMessage = (reader, messageName) => {
2927
+ const isBinary = reader.byte() !== 0;
2928
+ const columnCount = reader.int16();
2929
+ const message = new messages_1.CopyResponse(LATEINIT_LENGTH, messageName, isBinary, columnCount);
2930
+ for (let i = 0; i < columnCount; i++) {
2931
+ message.columnTypes[i] = reader.int16();
2932
+ }
2933
+ return message;
2934
+ };
2935
+ var parseNotificationMessage = (reader) => {
2936
+ const processId = reader.int32();
2937
+ const channel = reader.cstring();
2938
+ const payload = reader.cstring();
2939
+ return new messages_1.NotificationResponseMessage(LATEINIT_LENGTH, processId, channel, payload);
2940
+ };
2941
+ var parseRowDescriptionMessage = (reader) => {
2942
+ const fieldCount = reader.int16();
2943
+ const message = new messages_1.RowDescriptionMessage(LATEINIT_LENGTH, fieldCount);
2944
+ for (let i = 0; i < fieldCount; i++) {
2945
+ message.fields[i] = parseField(reader);
2946
+ }
2947
+ return message;
2948
+ };
2949
+ var parseField = (reader) => {
2950
+ const name = reader.cstring();
2951
+ const tableID = reader.uint32();
2952
+ const columnID = reader.int16();
2953
+ const dataTypeID = reader.uint32();
2954
+ const dataTypeSize = reader.int16();
2955
+ const dataTypeModifier = reader.int32();
2956
+ const mode = reader.int16() === 0 ? "text" : "binary";
2957
+ return new messages_1.Field(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, mode);
2958
+ };
2959
+ var parseParameterDescriptionMessage = (reader) => {
2960
+ const parameterCount = reader.int16();
2961
+ const message = new messages_1.ParameterDescriptionMessage(LATEINIT_LENGTH, parameterCount);
2962
+ for (let i = 0; i < parameterCount; i++) {
2963
+ message.dataTypeIDs[i] = reader.int32();
2964
+ }
2965
+ return message;
2966
+ };
2967
+ var parseDataRowMessage = (reader) => {
2968
+ const fieldCount = reader.int16();
2969
+ const fields = new Array(fieldCount);
2970
+ for (let i = 0; i < fieldCount; i++) {
2971
+ const len = reader.int32();
2972
+ fields[i] = len === -1 ? null : reader.string(len);
2973
+ }
2974
+ return new messages_1.DataRowMessage(LATEINIT_LENGTH, fields);
2975
+ };
2976
+ var parseParameterStatusMessage = (reader) => {
2977
+ const name = reader.cstring();
2978
+ const value = reader.cstring();
2979
+ return new messages_1.ParameterStatusMessage(LATEINIT_LENGTH, name, value);
2980
+ };
2981
+ var parseBackendKeyData = (reader) => {
2982
+ const processID = reader.int32();
2983
+ const secretKey = reader.int32();
2984
+ return new messages_1.BackendKeyDataMessage(LATEINIT_LENGTH, processID, secretKey);
2985
+ };
2986
+ var parseAuthenticationResponse = (reader, length) => {
2987
+ const code = reader.int32();
2988
+ const message = {
2989
+ name: "authenticationOk",
2990
+ length
2991
+ };
2992
+ switch (code) {
2993
+ case 0:
2994
+ break;
2995
+ case 3:
2996
+ if (message.length === 8) {
2997
+ message.name = "authenticationCleartextPassword";
2998
+ }
2999
+ break;
3000
+ case 5:
3001
+ if (message.length === 12) {
3002
+ message.name = "authenticationMD5Password";
3003
+ const salt = reader.bytes(4);
3004
+ return new messages_1.AuthenticationMD5Password(LATEINIT_LENGTH, salt);
3005
+ }
3006
+ break;
3007
+ case 10:
3008
+ {
3009
+ message.name = "authenticationSASL";
3010
+ message.mechanisms = [];
3011
+ let mechanism;
3012
+ do {
3013
+ mechanism = reader.cstring();
3014
+ if (mechanism) {
3015
+ message.mechanisms.push(mechanism);
3016
+ }
3017
+ } while (mechanism);
3018
+ }
3019
+ break;
3020
+ case 11:
3021
+ message.name = "authenticationSASLContinue";
3022
+ message.data = reader.string(length - 8);
3023
+ break;
3024
+ case 12:
3025
+ message.name = "authenticationSASLFinal";
3026
+ message.data = reader.string(length - 8);
3027
+ break;
3028
+ default:
3029
+ throw new Error("Unknown authenticationOk message type " + code);
3030
+ }
3031
+ return message;
3032
+ };
3033
+ var parseErrorMessage = (reader, name) => {
3034
+ const fields = {};
3035
+ let fieldType = reader.string(1);
3036
+ while (fieldType !== "\0") {
3037
+ fields[fieldType] = reader.cstring();
3038
+ fieldType = reader.string(1);
3039
+ }
3040
+ const messageValue = fields.M;
3041
+ const message = name === "notice" ? new messages_1.NoticeMessage(LATEINIT_LENGTH, messageValue) : new messages_1.DatabaseError(messageValue, LATEINIT_LENGTH, name);
3042
+ message.severity = fields.S;
3043
+ message.code = fields.C;
3044
+ message.detail = fields.D;
3045
+ message.hint = fields.H;
3046
+ message.position = fields.P;
3047
+ message.internalPosition = fields.p;
3048
+ message.internalQuery = fields.q;
3049
+ message.where = fields.W;
3050
+ message.schema = fields.s;
3051
+ message.table = fields.t;
3052
+ message.column = fields.c;
3053
+ message.dataType = fields.d;
3054
+ message.constraint = fields.n;
3055
+ message.file = fields.F;
3056
+ message.line = fields.L;
3057
+ message.routine = fields.R;
3058
+ return message;
3059
+ };
3016
3060
  }
3017
3061
  });
3018
3062
 
3019
- // ../../node_modules/pg-protocol/dist/index.js
3063
+ // ../../node_modules/pg/node_modules/pg-protocol/dist/index.js
3020
3064
  var require_dist = __commonJS({
3021
- "../../node_modules/pg-protocol/dist/index.js"(exports2) {
3065
+ "../../node_modules/pg/node_modules/pg-protocol/dist/index.js"(exports2) {
3022
3066
  "use strict";
3023
3067
  Object.defineProperty(exports2, "__esModule", { value: true });
3024
- exports2.DatabaseError = exports2.serialize = exports2.parse = void 0;
3068
+ exports2.DatabaseError = exports2.serialize = void 0;
3069
+ exports2.parse = parse;
3025
3070
  var messages_1 = require_messages();
3026
3071
  Object.defineProperty(exports2, "DatabaseError", { enumerable: true, get: function() {
3027
3072
  return messages_1.DatabaseError;
@@ -3036,7 +3081,6 @@ var require_dist = __commonJS({
3036
3081
  stream.on("data", (buffer) => parser.parse(buffer, callback));
3037
3082
  return new Promise((resolve) => stream.on("end", () => resolve()));
3038
3083
  }
3039
- exports2.parse = parse;
3040
3084
  }
3041
3085
  });
3042
3086
 
@@ -3122,7 +3166,8 @@ var require_connection = __commonJS({
3122
3166
  "use strict";
3123
3167
  var EventEmitter = require("events").EventEmitter;
3124
3168
  var { parse, serialize } = require_dist();
3125
- var { getStream, getSecureStream } = require_stream();
3169
+ var stream = require_stream();
3170
+ var { getStream } = stream;
3126
3171
  var flushBuffer = serialize.flush();
3127
3172
  var syncBuffer = serialize.sync();
3128
3173
  var endBuffer = serialize.end();
@@ -3136,9 +3181,9 @@ var require_connection = __commonJS({
3136
3181
  }
3137
3182
  this._keepAlive = config.keepAlive;
3138
3183
  this._keepAliveInitialDelayMillis = config.keepAliveInitialDelayMillis;
3139
- this.lastBuffer = false;
3140
3184
  this.parsedStatements = {};
3141
3185
  this.ssl = config.ssl || false;
3186
+ this.sslNegotiation = config.sslNegotiation || "postgres";
3142
3187
  this._ending = false;
3143
3188
  this._emitMessage = false;
3144
3189
  const self = this;
@@ -3172,6 +3217,11 @@ var require_connection = __commonJS({
3172
3217
  if (!this.ssl) {
3173
3218
  return this.attachListeners(this.stream);
3174
3219
  }
3220
+ if (this.sslNegotiation === "direct") {
3221
+ return this.stream.once("connect", function() {
3222
+ self.upgradeToSSL(host, reportStreamError);
3223
+ });
3224
+ }
3175
3225
  this.stream.once("data", function(buffer) {
3176
3226
  const responseCode = buffer.toString("utf8");
3177
3227
  switch (responseCode) {
@@ -3184,31 +3234,38 @@ var require_connection = __commonJS({
3184
3234
  self.stream.end();
3185
3235
  return self.emit("error", new Error("There was an error establishing an SSL connection"));
3186
3236
  }
3187
- const options = {
3188
- socket: self.stream
3189
- };
3190
- if (self.ssl !== true) {
3191
- Object.assign(options, self.ssl);
3192
- if ("key" in self.ssl) {
3193
- options.key = self.ssl.key;
3194
- }
3195
- }
3196
- const net2 = require("net");
3197
- if (net2.isIP && net2.isIP(host) === 0) {
3198
- options.servername = host;
3199
- }
3200
- try {
3201
- self.stream = getSecureStream(options);
3202
- } catch (err) {
3203
- return self.emit("error", err);
3204
- }
3205
- self.attachListeners(self.stream);
3206
- self.stream.on("error", reportStreamError);
3207
- self.emit("sslconnect");
3237
+ self.upgradeToSSL(host, reportStreamError);
3208
3238
  });
3209
3239
  }
3210
- attachListeners(stream) {
3211
- parse(stream, (msg) => {
3240
+ upgradeToSSL(host, reportStreamError) {
3241
+ const self = this;
3242
+ const options = {
3243
+ socket: self.stream
3244
+ };
3245
+ if (self.ssl !== true) {
3246
+ Object.assign(options, self.ssl);
3247
+ if ("key" in self.ssl) {
3248
+ options.key = self.ssl.key;
3249
+ }
3250
+ }
3251
+ if (self.sslNegotiation === "direct") {
3252
+ options.ALPNProtocols = ["postgresql"];
3253
+ }
3254
+ const net2 = require("net");
3255
+ if (net2.isIP && net2.isIP(host) === 0) {
3256
+ options.servername = host;
3257
+ }
3258
+ try {
3259
+ self.stream = stream.getSecureStream(options);
3260
+ } catch (err) {
3261
+ return self.emit("error", err);
3262
+ }
3263
+ self.attachListeners(self.stream);
3264
+ self.stream.on("error", reportStreamError);
3265
+ self.emit("sslconnect");
3266
+ }
3267
+ attachListeners(stream2) {
3268
+ parse(stream2, (msg) => {
3212
3269
  const eventName = msg.name === "error" ? "errorMessage" : msg.name;
3213
3270
  if (this._emitMessage) {
3214
3271
  this.emit("message", msg);
@@ -3599,6 +3656,7 @@ var require_client = __commonJS({
3599
3656
  "use strict";
3600
3657
  var EventEmitter = require("events").EventEmitter;
3601
3658
  var utils = require_utils();
3659
+ var nodeUtils = require("util");
3602
3660
  var sasl = require_sasl();
3603
3661
  var TypeOverrides2 = require_type_overrides();
3604
3662
  var ConnectionParameters = require_connection_parameters();
@@ -3606,6 +3664,41 @@ var require_client = __commonJS({
3606
3664
  var defaults2 = require_defaults();
3607
3665
  var Connection2 = require_connection();
3608
3666
  var crypto = require_utils2();
3667
+ var activeQueryDeprecationNotice = nodeUtils.deprecate(
3668
+ () => {
3669
+ },
3670
+ "Client.activeQuery is deprecated and will be removed in pg@9.0"
3671
+ );
3672
+ var queryQueueDeprecationNotice = nodeUtils.deprecate(
3673
+ () => {
3674
+ },
3675
+ "Client.queryQueue is deprecated and will be removed in pg@9.0."
3676
+ );
3677
+ var pgPassDeprecationNotice = nodeUtils.deprecate(
3678
+ () => {
3679
+ },
3680
+ "pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code."
3681
+ );
3682
+ var byoPromiseDeprecationNotice = nodeUtils.deprecate(
3683
+ () => {
3684
+ },
3685
+ "Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."
3686
+ );
3687
+ var queryQueueLengthDeprecationNotice = nodeUtils.deprecate(
3688
+ () => {
3689
+ },
3690
+ "Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."
3691
+ );
3692
+ function coerceNumberOrDefault(value, defaultValue) {
3693
+ if (typeof value === "number") {
3694
+ return Number.isFinite(value) ? value : defaultValue;
3695
+ }
3696
+ if (typeof value === "string" && value.trim() !== "") {
3697
+ const n = Number(value);
3698
+ return Number.isFinite(n) ? n : defaultValue;
3699
+ }
3700
+ return defaultValue;
3701
+ }
3609
3702
  var Client2 = class extends EventEmitter {
3610
3703
  constructor(config) {
3611
3704
  super();
@@ -3622,6 +3715,9 @@ var require_client = __commonJS({
3622
3715
  });
3623
3716
  this.replication = this.connectionParameters.replication;
3624
3717
  const c = config || {};
3718
+ if (c.Promise) {
3719
+ byoPromiseDeprecationNotice();
3720
+ }
3625
3721
  this._Promise = c.Promise || global.Promise;
3626
3722
  this._types = new TypeOverrides2(c.types);
3627
3723
  this._ending = false;
@@ -3630,19 +3726,24 @@ var require_client = __commonJS({
3630
3726
  this._connected = false;
3631
3727
  this._connectionError = false;
3632
3728
  this._queryable = true;
3729
+ this._activeQuery = null;
3730
+ this._txStatus = null;
3633
3731
  this.enableChannelBinding = Boolean(c.enableChannelBinding);
3732
+ this.scramMaxIterations = coerceNumberOrDefault(c.scramMaxIterations, sasl.DEFAULT_MAX_SCRAM_ITERATIONS);
3634
3733
  this.connection = c.connection || new Connection2({
3635
3734
  stream: c.stream,
3636
3735
  ssl: this.connectionParameters.ssl,
3736
+ sslNegotiation: this.connectionParameters.sslnegotiation,
3637
3737
  keepAlive: c.keepAlive || false,
3638
3738
  keepAliveInitialDelayMillis: c.keepAliveInitialDelayMillis || 0,
3639
3739
  encoding: this.connectionParameters.client_encoding || "utf8"
3640
3740
  });
3641
- this.queryQueue = [];
3741
+ this._queryQueue = [];
3642
3742
  this.binary = c.binary || defaults2.binary;
3643
3743
  this.processID = null;
3644
3744
  this.secretKey = null;
3645
3745
  this.ssl = this.connectionParameters.ssl || false;
3746
+ this.sslNegotiation = this.connectionParameters.sslnegotiation || "postgres";
3646
3747
  if (this.ssl && this.ssl.key) {
3647
3748
  Object.defineProperty(this.ssl, "key", {
3648
3749
  enumerable: false
@@ -3650,18 +3751,30 @@ var require_client = __commonJS({
3650
3751
  }
3651
3752
  this._connectionTimeoutMillis = c.connectionTimeoutMillis || 0;
3652
3753
  }
3754
+ get activeQuery() {
3755
+ activeQueryDeprecationNotice();
3756
+ return this._activeQuery;
3757
+ }
3758
+ set activeQuery(val) {
3759
+ activeQueryDeprecationNotice();
3760
+ this._activeQuery = val;
3761
+ }
3762
+ _getActiveQuery() {
3763
+ return this._activeQuery;
3764
+ }
3653
3765
  _errorAllQueries(err) {
3654
3766
  const enqueueError = (query) => {
3655
3767
  process.nextTick(() => {
3656
3768
  query.handleError(err, this.connection);
3657
3769
  });
3658
3770
  };
3659
- if (this.activeQuery) {
3660
- enqueueError(this.activeQuery);
3661
- this.activeQuery = null;
3771
+ const activeQuery = this._getActiveQuery();
3772
+ if (activeQuery) {
3773
+ enqueueError(activeQuery);
3774
+ this._activeQuery = null;
3662
3775
  }
3663
- this.queryQueue.forEach(enqueueError);
3664
- this.queryQueue.length = 0;
3776
+ this._queryQueue.forEach(enqueueError);
3777
+ this._queryQueue.length = 0;
3665
3778
  }
3666
3779
  _connect(callback) {
3667
3780
  const self = this;
@@ -3691,7 +3804,9 @@ var require_client = __commonJS({
3691
3804
  }
3692
3805
  con.on("connect", function() {
3693
3806
  if (self.ssl) {
3694
- con.requestSsl();
3807
+ if (self.sslNegotiation !== "direct") {
3808
+ con.requestSsl();
3809
+ }
3695
3810
  } else {
3696
3811
  con.startup(self.getStartupConf());
3697
3812
  }
@@ -3731,7 +3846,7 @@ var require_client = __commonJS({
3731
3846
  if (error) {
3732
3847
  reject(error);
3733
3848
  } else {
3734
- resolve();
3849
+ resolve(this);
3735
3850
  }
3736
3851
  });
3737
3852
  });
@@ -3757,12 +3872,10 @@ var require_client = __commonJS({
3757
3872
  con.on("copyData", this._handleCopyData.bind(this));
3758
3873
  con.on("notification", this._handleNotification.bind(this));
3759
3874
  }
3760
- // TODO(bmc): deprecate pgpass "built in" integration since this.password can be a function
3761
- // it can be supplied by the user if required - this is a breaking change!
3762
- _checkPgPass(cb) {
3875
+ _getPassword(cb) {
3763
3876
  const con = this.connection;
3764
3877
  if (typeof this.password === "function") {
3765
- this._Promise.resolve().then(() => this.password()).then((pass) => {
3878
+ this._Promise.resolve().then(() => this.password(this.connectionParameters)).then((pass) => {
3766
3879
  if (pass !== void 0) {
3767
3880
  if (typeof pass !== "string") {
3768
3881
  con.emit("error", new TypeError("Password must be a string"));
@@ -3783,6 +3896,7 @@ var require_client = __commonJS({
3783
3896
  const pgPass = require_lib();
3784
3897
  pgPass(this.connectionParameters, (pass) => {
3785
3898
  if (void 0 !== pass) {
3899
+ pgPassDeprecationNotice();
3786
3900
  this.connectionParameters.password = this.password = pass;
3787
3901
  }
3788
3902
  cb();
@@ -3793,12 +3907,12 @@ var require_client = __commonJS({
3793
3907
  }
3794
3908
  }
3795
3909
  _handleAuthCleartextPassword(msg) {
3796
- this._checkPgPass(() => {
3910
+ this._getPassword(() => {
3797
3911
  this.connection.password(this.password);
3798
3912
  });
3799
3913
  }
3800
3914
  _handleAuthMD5Password(msg) {
3801
- this._checkPgPass(async () => {
3915
+ this._getPassword(async () => {
3802
3916
  try {
3803
3917
  const hashedPassword = await crypto.postgresMd5PasswordHash(this.user, this.password, msg.salt);
3804
3918
  this.connection.password(hashedPassword);
@@ -3808,9 +3922,13 @@ var require_client = __commonJS({
3808
3922
  });
3809
3923
  }
3810
3924
  _handleAuthSASL(msg) {
3811
- this._checkPgPass(() => {
3925
+ this._getPassword(() => {
3812
3926
  try {
3813
- this.saslSession = sasl.startSession(msg.mechanisms, this.enableChannelBinding && this.connection.stream);
3927
+ this.saslSession = sasl.startSession(
3928
+ msg.mechanisms,
3929
+ this.enableChannelBinding && this.connection.stream,
3930
+ this.scramMaxIterations
3931
+ );
3814
3932
  this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism, this.saslSession.response);
3815
3933
  } catch (err) {
3816
3934
  this.connection.emit("error", err);
@@ -3853,8 +3971,9 @@ var require_client = __commonJS({
3853
3971
  }
3854
3972
  this.emit("connect");
3855
3973
  }
3856
- const { activeQuery } = this;
3857
- this.activeQuery = null;
3974
+ const activeQuery = this._getActiveQuery();
3975
+ this._activeQuery = null;
3976
+ this._txStatus = msg?.status ?? null;
3858
3977
  this.readyForQuery = true;
3859
3978
  if (activeQuery) {
3860
3979
  activeQuery.handleReadyForQuery(this.connection);
@@ -3890,49 +4009,87 @@ var require_client = __commonJS({
3890
4009
  if (this._connecting) {
3891
4010
  return this._handleErrorWhileConnecting(msg);
3892
4011
  }
3893
- const activeQuery = this.activeQuery;
4012
+ const activeQuery = this._getActiveQuery();
3894
4013
  if (!activeQuery) {
3895
4014
  this._handleErrorEvent(msg);
3896
4015
  return;
3897
4016
  }
3898
- this.activeQuery = null;
4017
+ this._activeQuery = null;
3899
4018
  activeQuery.handleError(msg, this.connection);
3900
4019
  }
3901
4020
  _handleRowDescription(msg) {
3902
- this.activeQuery.handleRowDescription(msg);
4021
+ const activeQuery = this._getActiveQuery();
4022
+ if (activeQuery == null) {
4023
+ const error = new Error("Received unexpected rowDescription message from backend.");
4024
+ this._handleErrorEvent(error);
4025
+ return;
4026
+ }
4027
+ activeQuery.handleRowDescription(msg);
3903
4028
  }
3904
4029
  _handleDataRow(msg) {
3905
- this.activeQuery.handleDataRow(msg);
4030
+ const activeQuery = this._getActiveQuery();
4031
+ if (activeQuery == null) {
4032
+ const error = new Error("Received unexpected dataRow message from backend.");
4033
+ this._handleErrorEvent(error);
4034
+ return;
4035
+ }
4036
+ activeQuery.handleDataRow(msg);
3906
4037
  }
3907
4038
  _handlePortalSuspended(msg) {
3908
- this.activeQuery.handlePortalSuspended(this.connection);
4039
+ const activeQuery = this._getActiveQuery();
4040
+ if (activeQuery == null) {
4041
+ const error = new Error("Received unexpected portalSuspended message from backend.");
4042
+ this._handleErrorEvent(error);
4043
+ return;
4044
+ }
4045
+ activeQuery.handlePortalSuspended(this.connection);
3909
4046
  }
3910
4047
  _handleEmptyQuery(msg) {
3911
- this.activeQuery.handleEmptyQuery(this.connection);
4048
+ const activeQuery = this._getActiveQuery();
4049
+ if (activeQuery == null) {
4050
+ const error = new Error("Received unexpected emptyQuery message from backend.");
4051
+ this._handleErrorEvent(error);
4052
+ return;
4053
+ }
4054
+ activeQuery.handleEmptyQuery(this.connection);
3912
4055
  }
3913
4056
  _handleCommandComplete(msg) {
3914
- if (this.activeQuery == null) {
4057
+ const activeQuery = this._getActiveQuery();
4058
+ if (activeQuery == null) {
3915
4059
  const error = new Error("Received unexpected commandComplete message from backend.");
3916
4060
  this._handleErrorEvent(error);
3917
4061
  return;
3918
4062
  }
3919
- this.activeQuery.handleCommandComplete(msg, this.connection);
4063
+ activeQuery.handleCommandComplete(msg, this.connection);
3920
4064
  }
3921
4065
  _handleParseComplete() {
3922
- if (this.activeQuery == null) {
4066
+ const activeQuery = this._getActiveQuery();
4067
+ if (activeQuery == null) {
3923
4068
  const error = new Error("Received unexpected parseComplete message from backend.");
3924
4069
  this._handleErrorEvent(error);
3925
4070
  return;
3926
4071
  }
3927
- if (this.activeQuery.name) {
3928
- this.connection.parsedStatements[this.activeQuery.name] = this.activeQuery.text;
4072
+ if (activeQuery.name) {
4073
+ this.connection.parsedStatements[activeQuery.name] = activeQuery.text;
3929
4074
  }
3930
4075
  }
3931
4076
  _handleCopyInResponse(msg) {
3932
- this.activeQuery.handleCopyInResponse(this.connection);
4077
+ const activeQuery = this._getActiveQuery();
4078
+ if (activeQuery == null) {
4079
+ const error = new Error("Received unexpected copyInResponse message from backend.");
4080
+ this._handleErrorEvent(error);
4081
+ return;
4082
+ }
4083
+ activeQuery.handleCopyInResponse(this.connection);
3933
4084
  }
3934
4085
  _handleCopyData(msg) {
3935
- this.activeQuery.handleCopyData(msg, this.connection);
4086
+ const activeQuery = this._getActiveQuery();
4087
+ if (activeQuery == null) {
4088
+ const error = new Error("Received unexpected copyData message from backend.");
4089
+ this._handleErrorEvent(error);
4090
+ return;
4091
+ }
4092
+ activeQuery.handleCopyData(msg, this.connection);
3936
4093
  }
3937
4094
  _handleNotification(msg) {
3938
4095
  this.emit("notification", msg);
@@ -3978,8 +4135,8 @@ var require_client = __commonJS({
3978
4135
  con.on("connect", function() {
3979
4136
  con.cancel(client.processID, client.secretKey);
3980
4137
  });
3981
- } else if (client.queryQueue.indexOf(query) !== -1) {
3982
- client.queryQueue.splice(client.queryQueue.indexOf(query), 1);
4138
+ } else if (client._queryQueue.indexOf(query) !== -1) {
4139
+ client._queryQueue.splice(client._queryQueue.indexOf(query), 1);
3983
4140
  }
3984
4141
  }
3985
4142
  setTypeParser(oid, format, parseFn) {
@@ -3999,20 +4156,21 @@ var require_client = __commonJS({
3999
4156
  }
4000
4157
  _pulseQueryQueue() {
4001
4158
  if (this.readyForQuery === true) {
4002
- this.activeQuery = this.queryQueue.shift();
4003
- if (this.activeQuery) {
4159
+ this._activeQuery = this._queryQueue.shift();
4160
+ const activeQuery = this._getActiveQuery();
4161
+ if (activeQuery) {
4004
4162
  this.readyForQuery = false;
4005
4163
  this.hasExecuted = true;
4006
- const queryError = this.activeQuery.submit(this.connection);
4164
+ const queryError = activeQuery.submit(this.connection);
4007
4165
  if (queryError) {
4008
4166
  process.nextTick(() => {
4009
- this.activeQuery.handleError(queryError, this.connection);
4167
+ activeQuery.handleError(queryError, this.connection);
4010
4168
  this.readyForQuery = true;
4011
4169
  this._pulseQueryQueue();
4012
4170
  });
4013
4171
  }
4014
4172
  } else if (this.hasExecuted) {
4015
- this.activeQuery = null;
4173
+ this._activeQuery = null;
4016
4174
  this.emit("drain");
4017
4175
  }
4018
4176
  }
@@ -4020,19 +4178,19 @@ var require_client = __commonJS({
4020
4178
  query(config, values, callback) {
4021
4179
  let query;
4022
4180
  let result;
4023
- let readTimeout;
4024
- let readTimeoutTimer;
4025
- let queryCallback;
4026
- if (config === null || config === void 0) {
4181
+ if (config == null) {
4027
4182
  throw new TypeError("Client was passed a null or undefined query");
4028
- } else if (typeof config.submit === "function") {
4029
- readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
4183
+ }
4184
+ if (typeof config.submit === "function") {
4030
4185
  result = query = config;
4031
- if (typeof values === "function") {
4032
- query.callback = query.callback || values;
4186
+ if (!query.callback) {
4187
+ if (typeof values === "function") {
4188
+ query.callback = values;
4189
+ } else if (callback) {
4190
+ query.callback = callback;
4191
+ }
4033
4192
  }
4034
4193
  } else {
4035
- readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
4036
4194
  query = new Query2(config, values, callback);
4037
4195
  if (!query.callback) {
4038
4196
  result = new this._Promise((resolve, reject) => {
@@ -4041,11 +4199,15 @@ var require_client = __commonJS({
4041
4199
  Error.captureStackTrace(err);
4042
4200
  throw err;
4043
4201
  });
4202
+ } else if (typeof query.callback !== "function") {
4203
+ throw new TypeError("callback is not a function");
4044
4204
  }
4045
4205
  }
4206
+ const readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
4046
4207
  if (readTimeout) {
4047
- queryCallback = query.callback;
4048
- readTimeoutTimer = setTimeout(() => {
4208
+ const queryCallback = query.callback || (() => {
4209
+ });
4210
+ const readTimeoutTimer = setTimeout(() => {
4049
4211
  const error = new Error("Query read timeout");
4050
4212
  process.nextTick(() => {
4051
4213
  query.handleError(error, this.connection);
@@ -4053,9 +4215,9 @@ var require_client = __commonJS({
4053
4215
  queryCallback(error);
4054
4216
  query.callback = () => {
4055
4217
  };
4056
- const index = this.queryQueue.indexOf(query);
4218
+ const index = this._queryQueue.indexOf(query);
4057
4219
  if (index > -1) {
4058
- this.queryQueue.splice(index, 1);
4220
+ this._queryQueue.splice(index, 1);
4059
4221
  }
4060
4222
  this._pulseQueryQueue();
4061
4223
  }, readTimeout);
@@ -4082,7 +4244,10 @@ var require_client = __commonJS({
4082
4244
  });
4083
4245
  return result;
4084
4246
  }
4085
- this.queryQueue.push(query);
4247
+ if (this._queryQueue.length > 0) {
4248
+ queryQueueLengthDeprecationNotice();
4249
+ }
4250
+ this._queryQueue.push(query);
4086
4251
  this._pulseQueryQueue();
4087
4252
  return result;
4088
4253
  }
@@ -4092,16 +4257,20 @@ var require_client = __commonJS({
4092
4257
  unref() {
4093
4258
  this.connection.unref();
4094
4259
  }
4260
+ getTransactionStatus() {
4261
+ return this._txStatus;
4262
+ }
4095
4263
  end(cb) {
4096
4264
  this._ending = true;
4097
4265
  if (!this.connection._connecting || this._ended) {
4098
4266
  if (cb) {
4099
4267
  cb();
4268
+ return;
4100
4269
  } else {
4101
4270
  return this._Promise.resolve();
4102
4271
  }
4103
4272
  }
4104
- if (this.activeQuery || !this._queryable) {
4273
+ if (this._getActiveQuery() || !this._queryable) {
4105
4274
  this.connection.stream.destroy();
4106
4275
  } else {
4107
4276
  this.connection.end();
@@ -4114,6 +4283,10 @@ var require_client = __commonJS({
4114
4283
  });
4115
4284
  }
4116
4285
  }
4286
+ get queryQueue() {
4287
+ queryQueueDeprecationNotice();
4288
+ return this._queryQueue;
4289
+ }
4117
4290
  };
4118
4291
  Client2.Query = Query2;
4119
4292
  module2.exports = Client2;
@@ -4212,6 +4385,13 @@ var require_pg_pool = __commonJS({
4212
4385
  this.ending = false;
4213
4386
  this.ended = false;
4214
4387
  }
4388
+ _promiseTry(f) {
4389
+ const Promise2 = this.Promise;
4390
+ if (typeof Promise2.try === "function") {
4391
+ return Promise2.try(f);
4392
+ }
4393
+ return new Promise2((resolve) => resolve(f()));
4394
+ }
4215
4395
  _isFull() {
4216
4396
  return this._clients.length >= this.options.max;
4217
4397
  }
@@ -4315,9 +4495,15 @@ var require_pg_pool = __commonJS({
4315
4495
  let timeoutHit = false;
4316
4496
  if (this.options.connectionTimeoutMillis) {
4317
4497
  tid = setTimeout(() => {
4318
- this.log("ending client due to timeout");
4319
- timeoutHit = true;
4320
- client.connection ? client.connection.stream.destroy() : client.end();
4498
+ if (client.connection) {
4499
+ this.log("ending client due to timeout");
4500
+ timeoutHit = true;
4501
+ client.connection.stream.destroy();
4502
+ } else if (!client.isConnected()) {
4503
+ this.log("ending client due to timeout");
4504
+ timeoutHit = true;
4505
+ client.end();
4506
+ }
4321
4507
  }, this.options.connectionTimeoutMillis);
4322
4508
  }
4323
4509
  this.log("connecting new client");
@@ -4338,27 +4524,47 @@ var require_pg_pool = __commonJS({
4338
4524
  }
4339
4525
  } else {
4340
4526
  this.log("new client connected");
4341
- if (this.options.maxLifetimeSeconds !== 0) {
4342
- const maxLifetimeTimeout = setTimeout(() => {
4343
- this.log("ending client due to expired lifetime");
4344
- this._expired.add(client);
4345
- const idleIndex = this._idle.findIndex((idleItem) => idleItem.client === client);
4346
- if (idleIndex !== -1) {
4347
- this._acquireClient(
4348
- client,
4349
- new PendingItem((err2, client2, clientRelease) => clientRelease()),
4350
- idleListener,
4351
- false
4352
- );
4527
+ if (this.options.onConnect) {
4528
+ this._promiseTry(() => this.options.onConnect(client)).then(
4529
+ () => {
4530
+ this._afterConnect(client, pendingItem, idleListener);
4531
+ },
4532
+ (hookErr) => {
4533
+ this._clients = this._clients.filter((c) => c !== client);
4534
+ client.end(() => {
4535
+ this._pulseQueue();
4536
+ if (!pendingItem.timedOut) {
4537
+ pendingItem.callback(hookErr, void 0, NOOP);
4538
+ }
4539
+ });
4353
4540
  }
4354
- }, this.options.maxLifetimeSeconds * 1e3);
4355
- maxLifetimeTimeout.unref();
4356
- client.once("end", () => clearTimeout(maxLifetimeTimeout));
4541
+ );
4542
+ return;
4357
4543
  }
4358
- return this._acquireClient(client, pendingItem, idleListener, true);
4544
+ return this._afterConnect(client, pendingItem, idleListener);
4359
4545
  }
4360
4546
  });
4361
4547
  }
4548
+ _afterConnect(client, pendingItem, idleListener) {
4549
+ if (this.options.maxLifetimeSeconds !== 0) {
4550
+ const maxLifetimeTimeout = setTimeout(() => {
4551
+ this.log("ending client due to expired lifetime");
4552
+ this._expired.add(client);
4553
+ const idleIndex = this._idle.findIndex((idleItem) => idleItem.client === client);
4554
+ if (idleIndex !== -1) {
4555
+ this._acquireClient(
4556
+ client,
4557
+ new PendingItem((err, client2, clientRelease) => clientRelease()),
4558
+ idleListener,
4559
+ false
4560
+ );
4561
+ }
4562
+ }, this.options.maxLifetimeSeconds * 1e3);
4563
+ maxLifetimeTimeout.unref();
4564
+ client.once("end", () => clearTimeout(maxLifetimeTimeout));
4565
+ }
4566
+ return this._acquireClient(client, pendingItem, idleListener, true);
4567
+ }
4362
4568
  // acquire a client for a pending work item
4363
4569
  _acquireClient(client, pendingItem, idleListener, isNew) {
4364
4570
  if (isNew) {
@@ -4419,8 +4625,10 @@ var require_pg_pool = __commonJS({
4419
4625
  let tid;
4420
4626
  if (this.options.idleTimeoutMillis && this._isAboveMin()) {
4421
4627
  tid = setTimeout(() => {
4422
- this.log("remove idle client");
4423
- this._remove(client, this._pulseQueue.bind(this));
4628
+ if (this._isAboveMin()) {
4629
+ this.log("remove idle client");
4630
+ this._remove(client, this._pulseQueue.bind(this));
4631
+ }
4424
4632
  }, this.options.idleTimeoutMillis);
4425
4633
  if (this.options.allowExitOnIdle) {
4426
4634
  tid.unref();
@@ -4656,6 +4864,7 @@ var require_query2 = __commonJS({
4656
4864
  var require_client2 = __commonJS({
4657
4865
  "../../node_modules/pg/lib/native/client.js"(exports2, module2) {
4658
4866
  "use strict";
4867
+ var nodeUtils = require("util");
4659
4868
  var Native;
4660
4869
  try {
4661
4870
  Native = require("pg-native");
@@ -4667,6 +4876,11 @@ var require_client2 = __commonJS({
4667
4876
  var util = require("util");
4668
4877
  var ConnectionParameters = require_connection_parameters();
4669
4878
  var NativeQuery = require_query2();
4879
+ var queryQueueLengthDeprecationNotice = nodeUtils.deprecate(
4880
+ () => {
4881
+ },
4882
+ "Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."
4883
+ );
4670
4884
  var Client2 = module2.exports = function(config) {
4671
4885
  EventEmitter.call(this);
4672
4886
  config = config || {};
@@ -4739,7 +4953,7 @@ var require_client2 = __commonJS({
4739
4953
  });
4740
4954
  self.emit("connect");
4741
4955
  self._pulseQueryQueue(true);
4742
- cb();
4956
+ cb(null, this);
4743
4957
  });
4744
4958
  });
4745
4959
  };
@@ -4753,7 +4967,7 @@ var require_client2 = __commonJS({
4753
4967
  if (error) {
4754
4968
  reject(error);
4755
4969
  } else {
4756
- resolve();
4970
+ resolve(this);
4757
4971
  }
4758
4972
  });
4759
4973
  });
@@ -4788,7 +5002,8 @@ var require_client2 = __commonJS({
4788
5002
  }
4789
5003
  }
4790
5004
  if (readTimeout) {
4791
- queryCallback = query.callback;
5005
+ queryCallback = query.callback || (() => {
5006
+ });
4792
5007
  readTimeoutTimer = setTimeout(() => {
4793
5008
  const error = new Error("Query read timeout");
4794
5009
  process.nextTick(() => {
@@ -4822,6 +5037,9 @@ var require_client2 = __commonJS({
4822
5037
  });
4823
5038
  return result;
4824
5039
  }
5040
+ if (this._queryQueue.length > 0) {
5041
+ queryQueueLengthDeprecationNotice();
5042
+ }
4825
5043
  this._queryQueue.push(query);
4826
5044
  this._pulseQueryQueue();
4827
5045
  return result;
@@ -4829,8 +5047,11 @@ var require_client2 = __commonJS({
4829
5047
  Client2.prototype.end = function(cb) {
4830
5048
  const self = this;
4831
5049
  this._ending = true;
4832
- if (!this._connected) {
4833
- this.once("connect", this.end.bind(this, cb));
5050
+ if (this._connecting && !this._connected) {
5051
+ this.once("connect", () => {
5052
+ this.end(() => {
5053
+ });
5054
+ });
4834
5055
  }
4835
5056
  let result;
4836
5057
  if (!cb) {
@@ -4839,6 +5060,7 @@ var require_client2 = __commonJS({
4839
5060
  });
4840
5061
  }
4841
5062
  this.native.end(function() {
5063
+ self._connected = false;
4842
5064
  self._errorAllQueries(new Error("Connection terminated"));
4843
5065
  process.nextTick(() => {
4844
5066
  self.emit("end");
@@ -4889,6 +5111,12 @@ var require_client2 = __commonJS({
4889
5111
  Client2.prototype.getTypeParser = function(oid, format) {
4890
5112
  return this._types.getTypeParser(oid, format);
4891
5113
  };
5114
+ Client2.prototype.isConnected = function() {
5115
+ return this._connected;
5116
+ };
5117
+ Client2.prototype.getTransactionStatus = function() {
5118
+ return this.native.getTransactionStatus();
5119
+ };
4892
5120
  }
4893
5121
  });
4894
5122
 
@@ -4920,9 +5148,9 @@ var require_lib2 = __commonJS({
4920
5148
  }
4921
5149
  };
4922
5150
  };
4923
- var PG = function(clientConstructor) {
5151
+ var PG = function(clientConstructor2) {
4924
5152
  this.defaults = defaults2;
4925
- this.Client = clientConstructor;
5153
+ this.Client = clientConstructor2;
4926
5154
  this.Query = this.Client.Query;
4927
5155
  this.Pool = poolFactory(this.Client);
4928
5156
  this._pools = [];
@@ -4935,29 +5163,34 @@ var require_lib2 = __commonJS({
4935
5163
  this.Result = Result2;
4936
5164
  this.utils = utils;
4937
5165
  };
4938
- if (typeof process.env.NODE_PG_FORCE_NATIVE !== "undefined") {
4939
- module2.exports = new PG(require_native());
4940
- } else {
4941
- module2.exports = new PG(Client2);
4942
- Object.defineProperty(module2.exports, "native", {
4943
- configurable: true,
4944
- enumerable: false,
4945
- get() {
4946
- let native = null;
4947
- try {
4948
- native = new PG(require_native());
4949
- } catch (err) {
4950
- if (err.code !== "MODULE_NOT_FOUND") {
4951
- throw err;
4952
- }
5166
+ var clientConstructor = Client2;
5167
+ var forceNative = false;
5168
+ try {
5169
+ forceNative = !!process.env.NODE_PG_FORCE_NATIVE;
5170
+ } catch {
5171
+ }
5172
+ if (forceNative) {
5173
+ clientConstructor = require_native();
5174
+ }
5175
+ module2.exports = new PG(clientConstructor);
5176
+ Object.defineProperty(module2.exports, "native", {
5177
+ configurable: true,
5178
+ enumerable: false,
5179
+ get() {
5180
+ let native = null;
5181
+ try {
5182
+ native = new PG(require_native());
5183
+ } catch (err) {
5184
+ if (err.code !== "MODULE_NOT_FOUND") {
5185
+ throw err;
4953
5186
  }
4954
- Object.defineProperty(module2.exports, "native", {
4955
- value: native
4956
- });
4957
- return native;
4958
5187
  }
4959
- });
4960
- }
5188
+ Object.defineProperty(module2.exports, "native", {
5189
+ value: native
5190
+ });
5191
+ return native;
5192
+ }
5193
+ });
4961
5194
  }
4962
5195
  });
4963
5196