azure-mock 2.20.0 → 2.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +201 -201
  2. package/dist/better-sqlite3-CtLaF97z-DWR9uC3b.js +129 -0
  3. package/dist/chunk-2X2C5D2I-dJHtPFe9-DxsO-1YF.js +4026 -0
  4. package/dist/d1-pK2J-_yx-BoQTXsTa.js +185 -0
  5. package/dist/dialect-pBb6Cg_F-xgpUtfmk.js +570 -0
  6. package/dist/dist-C481edUb-CHbOkeXH.js +10131 -0
  7. package/dist/dist-DUzzleZr-DxHmeYjp.js +2 -0
  8. package/dist/index.d.ts +21 -21
  9. package/dist/index.js +20396 -18921
  10. package/dist/libsql-Nq-S0r5x-d2dAzhgO.js +240 -0
  11. package/dist/logger-TIsK7375-CLNNa25D.js +652 -0
  12. package/dist/migrator-B9kYwLqO-4g9JX3_v.js +8 -0
  13. package/dist/migrator-BfTfJctM-DrNlb1BS.js +8 -0
  14. package/dist/migrator-BjoW0_3j-CD-XdZ5a.js +8 -0
  15. package/dist/migrator-CWWlo_Jk-C4Hw4PPN.js +8 -0
  16. package/dist/migrator-CpiXRkls-COYfhljd.js +24 -0
  17. package/dist/migrator-CtqJkLVI-D1lU6ZV0.js +8 -0
  18. package/dist/migrator-CxcBjmET-Dcd21VIf.js +8 -0
  19. package/dist/migrator-Cyhbhxo_-Bh7sF0R3.js +21 -0
  20. package/dist/migrator-DG1mWUoR-DVfkqn_v.js +31 -0
  21. package/dist/migrator-DrWmHwY2-YjAfotd7.js +8 -0
  22. package/dist/migrator-WAPonQxA-CRvJJhKG.js +8 -0
  23. package/dist/migrator-Zdh8WMMx-gsmNXspd.js +8 -0
  24. package/dist/migrator-xRJ6NOTS-SsAuB-Gi.js +24 -0
  25. package/dist/migrator-xbWwvFYF-BjyVdQS8.js +8 -0
  26. package/dist/mysql2-DkoPEsRu-BMwVSCmY.js +251 -0
  27. package/dist/neon-serverless-BEVFA7yv-DGSPAG1z.js +205 -0
  28. package/dist/node-postgres-DQA7bEhW-CkM_cVLD.js +216 -0
  29. package/dist/nodefs-Bc8b83o_-DetP9qUa.js +24 -0
  30. package/dist/opfs-ahp-DbstDvx--CHskKtzG.js +365 -0
  31. package/dist/pg-ylxXyvKj-Hm8vcZoi.js +279 -0
  32. package/dist/pglite-CPs4w-D9-DHOg0D8W.js +179 -0
  33. package/dist/pglite-DMWgTUE6-BOIRUWUT.js +2 -0
  34. package/dist/planetscale-serverless-DUMheN-f-Dyc_W6V_.js +172 -0
  35. package/dist/query-builder-CLJAKedv-DTZiP7B6.js +1715 -0
  36. package/dist/query-builder-CT3_liD0-hhg5kRTk.js +1347 -0
  37. package/dist/session-BOEirggu-DTmpyU_x.js +2485 -0
  38. package/dist/session-CAUQtT0A-BoVK2x7A.js +745 -0
  39. package/dist/session-Cjeygn2Z-BO0mi6pq.js +989 -0
  40. package/dist/singlestore-Cdlo23hW-BuFJ4Zqb.js +1647 -0
  41. package/dist/sql-CNZp2yLp-Bwugq384.js +611 -0
  42. package/dist/sqlite-proxy-BgUfVEbZ-CsSkc-_K.js +190 -0
  43. package/dist/src-LcyXhCXE-C_vKJiLK.js +1920 -0
  44. package/dist/vercel-postgres-BYmFKsTS-CpV2usun.js +203 -0
  45. package/package.json +7 -8
@@ -0,0 +1,1920 @@
1
+ import net from "net";
2
+ import tls from "tls";
3
+ import Stream from "stream";
4
+ import os from "os";
5
+ import fs from "fs";
6
+ import crypto2 from "crypto";
7
+ import { performance } from "perf_hooks";
8
+ //#region ../db/dist/src-LcyXhCXE.js
9
+ const originCache = /* @__PURE__ */ new Map(), originStackCache = /* @__PURE__ */ new Map(), originError = Symbol("OriginError");
10
+ const CLOSE = {};
11
+ var Query = class extends Promise {
12
+ constructor(strings, args, handler, canceller, options = {}) {
13
+ let resolve, reject;
14
+ super((a, b) => {
15
+ resolve = a;
16
+ reject = b;
17
+ });
18
+ this.tagged = Array.isArray(strings.raw);
19
+ this.strings = strings;
20
+ this.args = args;
21
+ this.handler = handler;
22
+ this.canceller = canceller;
23
+ this.options = options;
24
+ this.state = null;
25
+ this.statement = null;
26
+ this.resolve = (x) => (this.active = false, resolve(x));
27
+ this.reject = (x) => (this.active = false, reject(x));
28
+ this.active = false;
29
+ this.cancelled = null;
30
+ this.executed = false;
31
+ this.signature = "";
32
+ this[originError] = this.handler.debug ? /* @__PURE__ */ new Error() : this.tagged && cachedError(this.strings);
33
+ }
34
+ get origin() {
35
+ 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)) || "";
36
+ }
37
+ static get [Symbol.species]() {
38
+ return Promise;
39
+ }
40
+ cancel() {
41
+ return this.canceller && (this.canceller(this), this.canceller = null);
42
+ }
43
+ simple() {
44
+ this.options.simple = true;
45
+ this.options.prepare = false;
46
+ return this;
47
+ }
48
+ async readable() {
49
+ this.simple();
50
+ this.streaming = true;
51
+ return this;
52
+ }
53
+ async writable() {
54
+ this.simple();
55
+ this.streaming = true;
56
+ return this;
57
+ }
58
+ cursor(rows = 1, fn) {
59
+ this.options.simple = false;
60
+ if (typeof rows === "function") {
61
+ fn = rows;
62
+ rows = 1;
63
+ }
64
+ this.cursorRows = rows;
65
+ if (typeof fn === "function") return this.cursorFn = fn, this;
66
+ let prev;
67
+ return { [Symbol.asyncIterator]: () => ({
68
+ next: () => {
69
+ if (this.executed && !this.active) return { done: true };
70
+ prev && prev();
71
+ const promise = new Promise((resolve, reject) => {
72
+ this.cursorFn = (value) => {
73
+ resolve({
74
+ value,
75
+ done: false
76
+ });
77
+ return new Promise((r) => prev = r);
78
+ };
79
+ this.resolve = () => (this.active = false, resolve({ done: true }));
80
+ this.reject = (x) => (this.active = false, reject(x));
81
+ });
82
+ this.execute();
83
+ return promise;
84
+ },
85
+ return() {
86
+ prev && prev(CLOSE);
87
+ return { done: true };
88
+ }
89
+ }) };
90
+ }
91
+ describe() {
92
+ this.options.simple = false;
93
+ this.onlyDescribe = this.options.prepare = true;
94
+ return this;
95
+ }
96
+ stream() {
97
+ throw new Error(".stream has been renamed to .forEach");
98
+ }
99
+ forEach(fn) {
100
+ this.forEachFn = fn;
101
+ this.handle();
102
+ return this;
103
+ }
104
+ raw() {
105
+ this.isRaw = true;
106
+ return this;
107
+ }
108
+ values() {
109
+ this.isRaw = "values";
110
+ return this;
111
+ }
112
+ async handle() {
113
+ !this.executed && (this.executed = true) && await 1 && this.handler(this);
114
+ }
115
+ execute() {
116
+ this.handle();
117
+ return this;
118
+ }
119
+ then() {
120
+ this.handle();
121
+ return super.then.apply(this, arguments);
122
+ }
123
+ catch() {
124
+ this.handle();
125
+ return super.catch.apply(this, arguments);
126
+ }
127
+ finally() {
128
+ this.handle();
129
+ return super.finally.apply(this, arguments);
130
+ }
131
+ };
132
+ function cachedError(xs) {
133
+ if (originCache.has(xs)) return originCache.get(xs);
134
+ const x = Error.stackTraceLimit;
135
+ Error.stackTraceLimit = 4;
136
+ originCache.set(xs, /* @__PURE__ */ new Error());
137
+ Error.stackTraceLimit = x;
138
+ return originCache.get(xs);
139
+ }
140
+ var PostgresError = class extends Error {
141
+ constructor(x) {
142
+ super(x.message);
143
+ this.name = this.constructor.name;
144
+ Object.assign(this, x);
145
+ }
146
+ };
147
+ const Errors = {
148
+ connection,
149
+ postgres,
150
+ generic,
151
+ notSupported
152
+ };
153
+ function connection(x, options, socket) {
154
+ const { host, port } = socket || options;
155
+ const error = Object.assign(/* @__PURE__ */ new Error("write " + x + " " + (options.path || host + ":" + port)), {
156
+ code: x,
157
+ errno: x,
158
+ address: options.path || host
159
+ }, options.path ? {} : { port });
160
+ Error.captureStackTrace(error, connection);
161
+ return error;
162
+ }
163
+ function postgres(x) {
164
+ const error = new PostgresError(x);
165
+ Error.captureStackTrace(error, postgres);
166
+ return error;
167
+ }
168
+ function generic(code, message) {
169
+ const error = Object.assign(/* @__PURE__ */ new Error(code + ": " + message), { code });
170
+ Error.captureStackTrace(error, generic);
171
+ return error;
172
+ }
173
+ /* c8 ignore next 10 */
174
+ function notSupported(x) {
175
+ const error = Object.assign(/* @__PURE__ */ new Error(x + " (B) is not supported"), {
176
+ code: "MESSAGE_NOT_SUPPORTED",
177
+ name: x
178
+ });
179
+ Error.captureStackTrace(error, notSupported);
180
+ return error;
181
+ }
182
+ const types = {
183
+ string: {
184
+ to: 25,
185
+ from: null,
186
+ serialize: (x) => "" + x
187
+ },
188
+ number: {
189
+ to: 0,
190
+ from: [
191
+ 21,
192
+ 23,
193
+ 26,
194
+ 700,
195
+ 701
196
+ ],
197
+ serialize: (x) => "" + x,
198
+ parse: (x) => +x
199
+ },
200
+ json: {
201
+ to: 114,
202
+ from: [114, 3802],
203
+ serialize: (x) => JSON.stringify(x),
204
+ parse: (x) => JSON.parse(x)
205
+ },
206
+ boolean: {
207
+ to: 16,
208
+ from: 16,
209
+ serialize: (x) => x === true ? "t" : "f",
210
+ parse: (x) => x === "t"
211
+ },
212
+ date: {
213
+ to: 1184,
214
+ from: [
215
+ 1082,
216
+ 1114,
217
+ 1184
218
+ ],
219
+ serialize: (x) => (x instanceof Date ? x : new Date(x)).toISOString(),
220
+ parse: (x) => new Date(x)
221
+ },
222
+ bytea: {
223
+ to: 17,
224
+ from: 17,
225
+ serialize: (x) => "\\x" + Buffer.from(x).toString("hex"),
226
+ parse: (x) => Buffer.from(x.slice(2), "hex")
227
+ }
228
+ };
229
+ var NotTagged = class {
230
+ then() {
231
+ notTagged();
232
+ }
233
+ catch() {
234
+ notTagged();
235
+ }
236
+ finally() {
237
+ notTagged();
238
+ }
239
+ };
240
+ var Identifier = class extends NotTagged {
241
+ constructor(value) {
242
+ super();
243
+ this.value = escapeIdentifier(value);
244
+ }
245
+ };
246
+ var Parameter = class extends NotTagged {
247
+ constructor(value, type, array) {
248
+ super();
249
+ this.value = value;
250
+ this.type = type;
251
+ this.array = array;
252
+ }
253
+ };
254
+ var Builder = class extends NotTagged {
255
+ constructor(first, rest) {
256
+ super();
257
+ this.first = first;
258
+ this.rest = rest;
259
+ }
260
+ build(before, parameters, types, options) {
261
+ const keyword = builders.map(([x, fn]) => ({
262
+ fn,
263
+ i: before.search(x)
264
+ })).sort((a, b) => a.i - b.i).pop();
265
+ return keyword.i === -1 ? escapeIdentifiers(this.first, options) : keyword.fn(this.first, this.rest, parameters, types, options);
266
+ }
267
+ };
268
+ function handleValue(x, parameters, types, options) {
269
+ let value = x instanceof Parameter ? x.value : x;
270
+ if (value === void 0) {
271
+ x instanceof Parameter ? x.value = options.transform.undefined : value = x = options.transform.undefined;
272
+ if (value === void 0) throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed");
273
+ }
274
+ return "$" + types.push(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)));
275
+ }
276
+ const defaultHandlers = typeHandlers(types);
277
+ function stringify(q, string, value, parameters, types, options) {
278
+ for (let i = 1; i < q.strings.length; i++) {
279
+ string += stringifyValue(string, value, parameters, types, options) + q.strings[i];
280
+ value = q.args[i];
281
+ }
282
+ return string;
283
+ }
284
+ function stringifyValue(string, value, parameters, types, o) {
285
+ return value instanceof Builder ? value.build(string, parameters, types, o) : value instanceof Query ? fragment(value, parameters, types, o) : value instanceof Identifier ? value.value : value && value[0] instanceof Query ? value.reduce((acc, x) => acc + " " + fragment(x, parameters, types, o), "") : handleValue(value, parameters, types, o);
286
+ }
287
+ function fragment(q, parameters, types, options) {
288
+ q.fragment = true;
289
+ return stringify(q, q.strings[0], q.args[0], parameters, types, options);
290
+ }
291
+ function valuesBuilder(first, parameters, types, columns, options) {
292
+ return first.map((row) => "(" + columns.map((column) => stringifyValue("values", row[column], parameters, types, options)).join(",") + ")").join(",");
293
+ }
294
+ function values(first, rest, parameters, types, options) {
295
+ const multi = Array.isArray(first[0]);
296
+ const columns = rest.length ? rest.flat() : Object.keys(multi ? first[0] : first);
297
+ return valuesBuilder(multi ? first : [first], parameters, types, columns, options);
298
+ }
299
+ function select(first, rest, parameters, types, options) {
300
+ typeof first === "string" && (first = [first].concat(rest));
301
+ if (Array.isArray(first)) return escapeIdentifiers(first, options);
302
+ let value;
303
+ return (rest.length ? rest.flat() : Object.keys(first)).map((x) => {
304
+ value = first[x];
305
+ return (value instanceof Query ? fragment(value, parameters, types, options) : value instanceof Identifier ? value.value : handleValue(value, parameters, types, options)) + " as " + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x);
306
+ }).join(",");
307
+ }
308
+ const builders = Object.entries({
309
+ values,
310
+ in: (...xs) => {
311
+ const x = values(...xs);
312
+ return x === "()" ? "(null)" : x;
313
+ },
314
+ select,
315
+ as: select,
316
+ returning: select,
317
+ "\\(": select,
318
+ update(first, rest, parameters, types, options) {
319
+ return (rest.length ? rest.flat() : Object.keys(first)).map((x) => escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x) + "=" + stringifyValue("values", first[x], parameters, types, options));
320
+ },
321
+ insert(first, rest, parameters, types, options) {
322
+ const columns = rest.length ? rest.flat() : Object.keys(Array.isArray(first) ? first[0] : first);
323
+ return "(" + escapeIdentifiers(columns, options) + ")values" + valuesBuilder(Array.isArray(first) ? first : [first], parameters, types, columns, options);
324
+ }
325
+ }).map(([x, fn]) => [new RegExp("((?:^|[\\s(])" + x + "(?:$|[\\s(]))(?![\\s\\S]*\\1)", "i"), fn]);
326
+ function notTagged() {
327
+ throw Errors.generic("NOT_TAGGED_CALL", "Query not called as a tagged template literal");
328
+ }
329
+ const serializers = defaultHandlers.serializers;
330
+ const parsers = defaultHandlers.parsers;
331
+ function firstIsString(x) {
332
+ if (Array.isArray(x)) return firstIsString(x[0]);
333
+ return typeof x === "string" ? 1009 : 0;
334
+ }
335
+ const mergeUserTypes = function(types) {
336
+ const user = typeHandlers(types || {});
337
+ return {
338
+ serializers: Object.assign({}, serializers, user.serializers),
339
+ parsers: Object.assign({}, parsers, user.parsers)
340
+ };
341
+ };
342
+ function typeHandlers(types) {
343
+ return Object.keys(types).reduce((acc, k) => {
344
+ types[k].from && [].concat(types[k].from).forEach((x) => acc.parsers[x] = types[k].parse);
345
+ if (types[k].serialize) {
346
+ acc.serializers[types[k].to] = types[k].serialize;
347
+ types[k].from && [].concat(types[k].from).forEach((x) => acc.serializers[x] = types[k].serialize);
348
+ }
349
+ return acc;
350
+ }, {
351
+ parsers: {},
352
+ serializers: {}
353
+ });
354
+ }
355
+ function escapeIdentifiers(xs, { transform: { column } }) {
356
+ return xs.map((x) => escapeIdentifier(column.to ? column.to(x) : x)).join(",");
357
+ }
358
+ const escapeIdentifier = function escape(str) {
359
+ return "\"" + str.replace(/"/g, "\"\"").replace(/\./g, "\".\"") + "\"";
360
+ };
361
+ const inferType = function inferType(x) {
362
+ 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) ? inferType(x[0]) : 0;
363
+ };
364
+ const escapeBackslash = /\\/g;
365
+ const escapeQuote = /"/g;
366
+ function arrayEscape(x) {
367
+ return x.replace(escapeBackslash, "\\\\").replace(escapeQuote, "\\\"");
368
+ }
369
+ const arraySerializer = function arraySerializer(xs, serializer, options, typarray) {
370
+ if (Array.isArray(xs) === false) return xs;
371
+ if (!xs.length) return "{}";
372
+ const first = xs[0];
373
+ const delimiter = typarray === 1020 ? ";" : ",";
374
+ if (Array.isArray(first) && !first.type) return "{" + xs.map((x) => arraySerializer(x, serializer, options, typarray)).join(delimiter) + "}";
375
+ return "{" + xs.map((x) => {
376
+ if (x === void 0) {
377
+ x = options.transform.undefined;
378
+ if (x === void 0) throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed");
379
+ }
380
+ return x === null ? "null" : "\"" + arrayEscape(serializer ? serializer(x.type ? x.value : x) : "" + x) + "\"";
381
+ }).join(delimiter) + "}";
382
+ };
383
+ const arrayParserState = {
384
+ i: 0,
385
+ char: null,
386
+ str: "",
387
+ quoted: false,
388
+ last: 0
389
+ };
390
+ const arrayParser = function arrayParser(x, parser, typarray) {
391
+ arrayParserState.i = arrayParserState.last = 0;
392
+ return arrayParserLoop(arrayParserState, x, parser, typarray);
393
+ };
394
+ function arrayParserLoop(s, x, parser, typarray) {
395
+ const xs = [];
396
+ const delimiter = typarray === 1020 ? ";" : ",";
397
+ for (; s.i < x.length; s.i++) {
398
+ s.char = x[s.i];
399
+ if (s.quoted) if (s.char === "\\") s.str += x[++s.i];
400
+ else if (s.char === "\"") {
401
+ xs.push(parser ? parser(s.str) : s.str);
402
+ s.str = "";
403
+ s.quoted = x[s.i + 1] === "\"";
404
+ s.last = s.i + 2;
405
+ } else s.str += s.char;
406
+ else if (s.char === "\"") s.quoted = true;
407
+ else if (s.char === "{") {
408
+ s.last = ++s.i;
409
+ xs.push(arrayParserLoop(s, x, parser, typarray));
410
+ } else if (s.char === "}") {
411
+ s.quoted = false;
412
+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i));
413
+ s.last = s.i + 1;
414
+ break;
415
+ } else if (s.char === delimiter && s.p !== "}" && s.p !== "\"") {
416
+ xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i));
417
+ s.last = s.i + 1;
418
+ }
419
+ s.p = s.char;
420
+ }
421
+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i + 1)) : x.slice(s.last, s.i + 1));
422
+ return xs;
423
+ }
424
+ const toCamel = (x) => {
425
+ let str = x[0];
426
+ for (let i = 1; i < x.length; i++) str += x[i] === "_" ? x[++i].toUpperCase() : x[i];
427
+ return str;
428
+ };
429
+ const toPascal = (x) => {
430
+ let str = x[0].toUpperCase();
431
+ for (let i = 1; i < x.length; i++) str += x[i] === "_" ? x[++i].toUpperCase() : x[i];
432
+ return str;
433
+ };
434
+ const toKebab = (x) => x.replace(/_/g, "-");
435
+ const fromCamel = (x) => x.replace(/([A-Z])/g, "_$1").toLowerCase();
436
+ const fromPascal = (x) => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, "_$1")).toLowerCase();
437
+ const fromKebab = (x) => x.replace(/-/g, "_");
438
+ function createJsonTransform(fn) {
439
+ return function jsonTransform(x, column) {
440
+ return typeof x === "object" && x !== null && (column.type === 114 || column.type === 3802) ? Array.isArray(x) ? x.map((x) => jsonTransform(x, column)) : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: jsonTransform(v, column) }), {}) : x;
441
+ };
442
+ }
443
+ toCamel.column = { from: toCamel };
444
+ toCamel.value = { from: createJsonTransform(toCamel) };
445
+ fromCamel.column = { to: fromCamel };
446
+ const camel = { ...toCamel };
447
+ camel.column.to = fromCamel;
448
+ toPascal.column = { from: toPascal };
449
+ toPascal.value = { from: createJsonTransform(toPascal) };
450
+ fromPascal.column = { to: fromPascal };
451
+ const pascal = { ...toPascal };
452
+ pascal.column.to = fromPascal;
453
+ toKebab.column = { from: toKebab };
454
+ toKebab.value = { from: createJsonTransform(toKebab) };
455
+ fromKebab.column = { to: fromKebab };
456
+ const kebab = { ...toKebab };
457
+ kebab.column.to = fromKebab;
458
+ var Result = class extends Array {
459
+ constructor() {
460
+ super();
461
+ Object.defineProperties(this, {
462
+ count: {
463
+ value: null,
464
+ writable: true
465
+ },
466
+ state: {
467
+ value: null,
468
+ writable: true
469
+ },
470
+ command: {
471
+ value: null,
472
+ writable: true
473
+ },
474
+ columns: {
475
+ value: null,
476
+ writable: true
477
+ },
478
+ statement: {
479
+ value: null,
480
+ writable: true
481
+ }
482
+ });
483
+ }
484
+ static get [Symbol.species]() {
485
+ return Array;
486
+ }
487
+ };
488
+ var queue_default = Queue;
489
+ function Queue(initial = []) {
490
+ let xs = initial.slice();
491
+ let index = 0;
492
+ return {
493
+ get length() {
494
+ return xs.length - index;
495
+ },
496
+ remove: (x) => {
497
+ const index = xs.indexOf(x);
498
+ return index === -1 ? null : (xs.splice(index, 1), x);
499
+ },
500
+ push: (x) => (xs.push(x), x),
501
+ shift: () => {
502
+ const out = xs[index++];
503
+ if (index === xs.length) {
504
+ index = 0;
505
+ xs = [];
506
+ } else xs[index - 1] = void 0;
507
+ return out;
508
+ }
509
+ };
510
+ }
511
+ const size = 256;
512
+ let buffer = Buffer.allocUnsafe(size);
513
+ const messages = "BCcDdEFfHPpQSX".split("").reduce((acc, x) => {
514
+ const v = x.charCodeAt(0);
515
+ acc[x] = () => {
516
+ buffer[0] = v;
517
+ b.i = 5;
518
+ return b;
519
+ };
520
+ return acc;
521
+ }, {});
522
+ const b = Object.assign(reset, messages, {
523
+ N: String.fromCharCode(0),
524
+ i: 0,
525
+ inc(x) {
526
+ b.i += x;
527
+ return b;
528
+ },
529
+ str(x) {
530
+ const length = Buffer.byteLength(x);
531
+ fit(length);
532
+ b.i += buffer.write(x, b.i, length, "utf8");
533
+ return b;
534
+ },
535
+ i16(x) {
536
+ fit(2);
537
+ buffer.writeUInt16BE(x, b.i);
538
+ b.i += 2;
539
+ return b;
540
+ },
541
+ i32(x, i) {
542
+ if (i || i === 0) {
543
+ buffer.writeUInt32BE(x, i);
544
+ return b;
545
+ }
546
+ fit(4);
547
+ buffer.writeUInt32BE(x, b.i);
548
+ b.i += 4;
549
+ return b;
550
+ },
551
+ z(x) {
552
+ fit(x);
553
+ buffer.fill(0, b.i, b.i + x);
554
+ b.i += x;
555
+ return b;
556
+ },
557
+ raw(x) {
558
+ buffer = Buffer.concat([buffer.subarray(0, b.i), x]);
559
+ b.i = buffer.length;
560
+ return b;
561
+ },
562
+ end(at = 1) {
563
+ buffer.writeUInt32BE(b.i - at, at);
564
+ const out = buffer.subarray(0, b.i);
565
+ b.i = 0;
566
+ buffer = Buffer.allocUnsafe(size);
567
+ return out;
568
+ }
569
+ });
570
+ function fit(x) {
571
+ if (buffer.length - b.i < x) {
572
+ const prev = buffer, length = prev.length;
573
+ buffer = Buffer.allocUnsafe(length + (length >> 1) + x);
574
+ prev.copy(buffer);
575
+ }
576
+ }
577
+ function reset() {
578
+ b.i = 0;
579
+ return b;
580
+ }
581
+ var connection_default = Connection;
582
+ let uid = 1;
583
+ const Sync = b().S().end(), Flush = b().H().end(), SSLRequest = b().i32(8).i32(80877103).end(8), ExecuteUnnamed = Buffer.concat([b().E().str(b.N).i32(0).end(), Sync]), DescribeUnnamed = b().D().str("S").str(b.N).end(), noop$1 = () => {};
584
+ const retryRoutines = new Set([
585
+ "FetchPreparedStatement",
586
+ "RevalidateCachedQuery",
587
+ "transformAssignedExpr"
588
+ ]);
589
+ const errorFields = {
590
+ 83: "severity_local",
591
+ 86: "severity",
592
+ 67: "code",
593
+ 77: "message",
594
+ 68: "detail",
595
+ 72: "hint",
596
+ 80: "position",
597
+ 112: "internal_position",
598
+ 113: "internal_query",
599
+ 87: "where",
600
+ 115: "schema_name",
601
+ 116: "table_name",
602
+ 99: "column_name",
603
+ 100: "data type_name",
604
+ 110: "constraint_name",
605
+ 70: "file",
606
+ 76: "line",
607
+ 82: "routine"
608
+ };
609
+ function Connection(options, queues = {}, { onopen = noop$1, onend = noop$1, onclose = noop$1 } = {}) {
610
+ const { sslnegotiation, ssl, max, user, host, port, database, parsers, transform, onnotice, onnotify, onparameter, max_pipeline, keep_alive, backoff, target_session_attrs } = options;
611
+ const sent = queue_default(), id = uid++, backend = {
612
+ pid: null,
613
+ secret: null
614
+ }, idleTimer = timer(end, options.idle_timeout), lifeTimer = timer(end, options.max_lifetime), connectTimer = timer(connectTimedOut, options.connect_timeout);
615
+ 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;
616
+ const connection = {
617
+ queue: queues.closed,
618
+ idleTimer,
619
+ connect(query) {
620
+ initial = query;
621
+ reconnect();
622
+ },
623
+ terminate,
624
+ execute,
625
+ cancel,
626
+ end,
627
+ count: 0,
628
+ id
629
+ };
630
+ queues.closed && queues.closed.push(connection);
631
+ return connection;
632
+ async function createSocket() {
633
+ let x;
634
+ try {
635
+ x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket();
636
+ } catch (e) {
637
+ error(e);
638
+ return;
639
+ }
640
+ x.on("error", error);
641
+ x.on("close", closed);
642
+ x.on("drain", drain);
643
+ return x;
644
+ }
645
+ async function cancel({ pid, secret }, resolve, reject) {
646
+ try {
647
+ cancelMessage = b().i32(16).i32(80877102).i32(pid).i32(secret).end(16);
648
+ await connect();
649
+ socket.once("error", reject);
650
+ socket.once("close", resolve);
651
+ } catch (error) {
652
+ reject(error);
653
+ }
654
+ }
655
+ function execute(q) {
656
+ if (terminated) return queryError(q, Errors.connection("CONNECTION_DESTROYED", options));
657
+ if (stream) return queryError(q, Errors.generic("COPY_IN_PROGRESS", "You cannot execute queries during copy"));
658
+ if (q.cancelled) return;
659
+ try {
660
+ q.state = backend;
661
+ query ? sent.push(q) : (query = q, query.active = true);
662
+ build(q);
663
+ return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection));
664
+ } catch (error) {
665
+ sent.length === 0 && write(Sync);
666
+ errored(error);
667
+ return true;
668
+ }
669
+ }
670
+ function toBuffer(q) {
671
+ if (q.parameters.length >= 65534) throw Errors.generic("MAX_PARAMETERS_EXCEEDED", "Max number of parameters (65534) exceeded");
672
+ return q.options.simple ? b().Q().str(q.statement.string + b.N).end() : q.describeFirst ? Buffer.concat([describe(q), Flush]) : q.prepare ? q.prepared ? prepared(q) : Buffer.concat([describe(q), prepared(q)]) : unnamed(q);
673
+ }
674
+ function describe(q) {
675
+ return Buffer.concat([Parse(q.statement.string, q.parameters, q.statement.types, q.statement.name), Describe("S", q.statement.name)]);
676
+ }
677
+ function prepared(q) {
678
+ return Buffer.concat([Bind(q.parameters, q.statement.types, q.statement.name, q.cursorName), q.cursorFn ? Execute("", q.cursorRows) : ExecuteUnnamed]);
679
+ }
680
+ function unnamed(q) {
681
+ return Buffer.concat([
682
+ Parse(q.statement.string, q.parameters, q.statement.types),
683
+ DescribeUnnamed,
684
+ prepared(q)
685
+ ]);
686
+ }
687
+ function build(q) {
688
+ const parameters = [], types = [];
689
+ const string = stringify(q, q.strings[0], q.args[0], parameters, types, options);
690
+ !q.tagged && q.args.forEach((x) => handleValue(x, parameters, types, options));
691
+ q.prepare = options.prepare && ("prepare" in q.options ? q.options.prepare : true);
692
+ q.string = string;
693
+ q.signature = q.prepare && types + string;
694
+ q.onlyDescribe && delete statements[q.signature];
695
+ q.parameters = q.parameters || parameters;
696
+ q.prepared = q.prepare && q.signature in statements;
697
+ q.describeFirst = q.onlyDescribe || parameters.length && !q.prepared;
698
+ q.statement = q.prepared ? statements[q.signature] : {
699
+ string,
700
+ types,
701
+ name: q.prepare ? statementId + statementCount++ : ""
702
+ };
703
+ typeof options.debug === "function" && options.debug(id, string, parameters, types);
704
+ }
705
+ function write(x, fn) {
706
+ chunk = chunk ? Buffer.concat([chunk, x]) : Buffer.from(x);
707
+ if (fn || chunk.length >= 1024) return nextWrite(fn);
708
+ nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite));
709
+ return true;
710
+ }
711
+ function nextWrite(fn) {
712
+ const x = socket.write(chunk, fn);
713
+ nextWriteTimer !== null && clearImmediate(nextWriteTimer);
714
+ chunk = nextWriteTimer = null;
715
+ return x;
716
+ }
717
+ function connectTimedOut() {
718
+ errored(Errors.connection("CONNECT_TIMEOUT", options, socket));
719
+ socket.destroy();
720
+ }
721
+ async function secure() {
722
+ if (sslnegotiation !== "direct") {
723
+ write(SSLRequest);
724
+ if (!await new Promise((r) => socket.once("data", (x) => r(x[0] === 83))) && ssl === "prefer") return connected();
725
+ }
726
+ const options = {
727
+ socket,
728
+ servername: net.isIP(socket.host) ? void 0 : socket.host
729
+ };
730
+ if (sslnegotiation === "direct") options.ALPNProtocols = ["postgresql"];
731
+ if (ssl === "require" || ssl === "allow" || ssl === "prefer") options.rejectUnauthorized = false;
732
+ else if (typeof ssl === "object") Object.assign(options, ssl);
733
+ socket.removeAllListeners();
734
+ socket = tls.connect(options);
735
+ socket.on("secureConnect", connected);
736
+ socket.on("error", error);
737
+ socket.on("close", closed);
738
+ socket.on("drain", drain);
739
+ }
740
+ /* c8 ignore next 3 */
741
+ function drain() {
742
+ !query && onopen(connection);
743
+ }
744
+ function data(x) {
745
+ if (incomings) {
746
+ incomings.push(x);
747
+ remaining -= x.length;
748
+ if (remaining > 0) return;
749
+ }
750
+ incoming = incomings ? Buffer.concat(incomings, length - remaining) : incoming.length === 0 ? x : Buffer.concat([incoming, x], incoming.length + x.length);
751
+ while (incoming.length > 4) {
752
+ length = incoming.readUInt32BE(1);
753
+ if (length >= incoming.length) {
754
+ remaining = length - incoming.length;
755
+ incomings = [incoming];
756
+ break;
757
+ }
758
+ try {
759
+ handle(incoming.subarray(0, length + 1));
760
+ } catch (e) {
761
+ query && (query.cursorFn || query.describeFirst) && write(Sync);
762
+ errored(e);
763
+ }
764
+ incoming = incoming.subarray(length + 1);
765
+ remaining = 0;
766
+ incomings = null;
767
+ }
768
+ }
769
+ async function connect() {
770
+ terminated = false;
771
+ backendParameters = {};
772
+ socket || (socket = await createSocket());
773
+ if (!socket) return;
774
+ connectTimer.start();
775
+ if (options.socket) return ssl ? secure() : connected();
776
+ socket.on("connect", ssl ? secure : connected);
777
+ if (options.path) return socket.connect(options.path);
778
+ socket.ssl = ssl;
779
+ socket.connect(port[hostIndex], host[hostIndex]);
780
+ socket.host = host[hostIndex];
781
+ socket.port = port[hostIndex];
782
+ hostIndex = (hostIndex + 1) % port.length;
783
+ }
784
+ function reconnect() {
785
+ setTimeout(connect, closedTime ? Math.max(0, closedTime + delay - performance.now()) : 0);
786
+ }
787
+ function connected() {
788
+ try {
789
+ statements = {};
790
+ needsTypes = options.fetch_types;
791
+ statementId = Math.random().toString(36).slice(2);
792
+ statementCount = 1;
793
+ lifeTimer.start();
794
+ socket.on("data", data);
795
+ keep_alive && socket.setKeepAlive && socket.setKeepAlive(true, 1e3 * keep_alive);
796
+ write(StartupMessage());
797
+ } catch (err) {
798
+ error(err);
799
+ }
800
+ }
801
+ function error(err) {
802
+ if (connection.queue === queues.connecting && options.host[retries + 1]) return;
803
+ errored(err);
804
+ while (sent.length) queryError(sent.shift(), err);
805
+ }
806
+ function errored(err) {
807
+ stream && (stream.destroy(err), stream = null);
808
+ query && queryError(query, err);
809
+ initial && (queryError(initial, err), initial = null);
810
+ }
811
+ function queryError(query, err) {
812
+ if (query.reserve) return query.reject(err);
813
+ if (!err || typeof err !== "object") err = new Error(err);
814
+ "query" in err || "parameters" in err || Object.defineProperties(err, {
815
+ stack: {
816
+ value: err.stack + query.origin.replace(/.*\n/, "\n"),
817
+ enumerable: options.debug
818
+ },
819
+ query: {
820
+ value: query.string,
821
+ enumerable: options.debug
822
+ },
823
+ parameters: {
824
+ value: query.parameters,
825
+ enumerable: options.debug
826
+ },
827
+ args: {
828
+ value: query.args,
829
+ enumerable: options.debug
830
+ },
831
+ types: {
832
+ value: query.statement && query.statement.types,
833
+ enumerable: options.debug
834
+ }
835
+ });
836
+ query.reject(err);
837
+ }
838
+ function end() {
839
+ return ending || (!connection.reserved && onend(connection), !connection.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));
840
+ }
841
+ function terminate() {
842
+ terminated = true;
843
+ if (stream || query || initial || sent.length) error(Errors.connection("CONNECTION_DESTROYED", options));
844
+ clearImmediate(nextWriteTimer);
845
+ if (socket) {
846
+ socket.removeListener("data", data);
847
+ socket.removeListener("connect", connected);
848
+ socket.readyState === "open" && socket.end(b().X().end());
849
+ }
850
+ ended && (ended(), ending = ended = null);
851
+ }
852
+ async function closed(hadError) {
853
+ incoming = Buffer.alloc(0);
854
+ remaining = 0;
855
+ incomings = null;
856
+ clearImmediate(nextWriteTimer);
857
+ socket.removeListener("data", data);
858
+ socket.removeListener("connect", connected);
859
+ idleTimer.cancel();
860
+ lifeTimer.cancel();
861
+ connectTimer.cancel();
862
+ socket.removeAllListeners();
863
+ socket = null;
864
+ if (initial) return reconnect();
865
+ !hadError && (query || sent.length) && error(Errors.connection("CONNECTION_CLOSED", options, socket));
866
+ closedTime = performance.now();
867
+ hadError && options.shared.retries++;
868
+ delay = (typeof backoff === "function" ? backoff(options.shared.retries) : backoff) * 1e3;
869
+ onclose(connection, Errors.connection("CONNECTION_CLOSED", options, socket));
870
+ }
871
+ function handle(xs, x = xs[0]) {
872
+ (x === 68 ? DataRow : x === 100 ? CopyData : x === 65 ? NotificationResponse : x === 83 ? ParameterStatus : x === 90 ? ReadyForQuery : x === 67 ? CommandComplete : x === 50 ? BindComplete : x === 49 ? ParseComplete : x === 116 ? ParameterDescription : x === 84 ? RowDescription : x === 82 ? Authentication : x === 110 ? NoData : x === 75 ? BackendKeyData : x === 69 ? ErrorResponse : x === 115 ? PortalSuspended : x === 51 ? CloseComplete : x === 71 ? CopyInResponse : x === 78 ? NoticeResponse : x === 72 ? CopyOutResponse : x === 99 ? CopyDone : x === 73 ? EmptyQueryResponse : x === 86 ? FunctionCallResponse : x === 118 ? NegotiateProtocolVersion : x === 87 ? CopyBothResponse :
873
+ /* c8 ignore next */
874
+ UnknownMessage)(xs);
875
+ }
876
+ function DataRow(x) {
877
+ let index = 7;
878
+ let length;
879
+ let column;
880
+ let value;
881
+ const row = query.isRaw ? new Array(query.statement.columns.length) : {};
882
+ for (let i = 0; i < query.statement.columns.length; i++) {
883
+ column = query.statement.columns[i];
884
+ length = x.readInt32BE(index);
885
+ index += 4;
886
+ value = length === -1 ? null : query.isRaw === true ? x.subarray(index, index += length) : column.parser === void 0 ? x.toString("utf8", index, index += length) : column.parser.array === true ? column.parser(x.toString("utf8", index + 1, index += length)) : column.parser(x.toString("utf8", index, index += length));
887
+ 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;
888
+ }
889
+ query.forEachFn ? query.forEachFn(transform.row.from ? transform.row.from(row) : row, result) : result[rows++] = transform.row.from ? transform.row.from(row) : row;
890
+ }
891
+ function ParameterStatus(x) {
892
+ const [k, v] = x.toString("utf8", 5, x.length - 1).split(b.N);
893
+ backendParameters[k] = v;
894
+ if (options.parameters[k] !== v) {
895
+ options.parameters[k] = v;
896
+ onparameter && onparameter(k, v);
897
+ }
898
+ }
899
+ function ReadyForQuery(x) {
900
+ if (query) if (errorResponse) query.retried ? errored(query.retried) : query.prepared && retryRoutines.has(errorResponse.routine) ? retry(query, errorResponse) : errored(errorResponse);
901
+ else query.resolve(results || result);
902
+ else if (errorResponse) errored(errorResponse);
903
+ query = results = errorResponse = null;
904
+ result = new Result();
905
+ connectTimer.cancel();
906
+ if (initial) {
907
+ if (target_session_attrs) {
908
+ if (!backendParameters.in_hot_standby || !backendParameters.default_transaction_read_only) return fetchState();
909
+ else if (tryNext(target_session_attrs, backendParameters)) return terminate();
910
+ }
911
+ if (needsTypes) {
912
+ initial.reserve && (initial = null);
913
+ return fetchArrayTypes();
914
+ }
915
+ initial && !initial.reserve && execute(initial);
916
+ options.shared.retries = retries = 0;
917
+ initial = null;
918
+ return;
919
+ }
920
+ while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled)) Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject);
921
+ if (query) return;
922
+ connection.reserved ? !connection.reserved.release && x[5] === 73 ? ending ? terminate() : (connection.reserved = null, onopen(connection)) : connection.reserved() : ending ? terminate() : onopen(connection);
923
+ }
924
+ function CommandComplete(x) {
925
+ rows = 0;
926
+ for (let i = x.length - 1; i > 0; i--) {
927
+ if (x[i] === 32 && x[i + 1] < 58 && result.count === null) result.count = +x.toString("utf8", i + 1, x.length - 1);
928
+ if (x[i - 1] >= 65) {
929
+ result.command = x.toString("utf8", 5, i);
930
+ result.state = backend;
931
+ break;
932
+ }
933
+ }
934
+ final && (final(), final = null);
935
+ if (result.command === "BEGIN" && max !== 1 && !connection.reserved) return errored(Errors.generic("UNSAFE_TRANSACTION", "Only use sql.begin, sql.reserved or max: 1"));
936
+ if (query.options.simple) return BindComplete();
937
+ if (query.cursorFn) {
938
+ result.count && query.cursorFn(result);
939
+ write(Sync);
940
+ }
941
+ }
942
+ function ParseComplete() {
943
+ query.parsing = false;
944
+ }
945
+ function BindComplete() {
946
+ !result.statement && (result.statement = query.statement);
947
+ result.columns = query.statement.columns;
948
+ }
949
+ function ParameterDescription(x) {
950
+ const length = x.readUInt16BE(5);
951
+ for (let i = 0; i < length; ++i) !query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4));
952
+ query.prepare && (statements[query.signature] = query.statement);
953
+ query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false);
954
+ }
955
+ function RowDescription(x) {
956
+ if (result.command) {
957
+ results = results || [result];
958
+ results.push(result = new Result());
959
+ result.count = null;
960
+ query.statement.columns = null;
961
+ }
962
+ const length = x.readUInt16BE(5);
963
+ let index = 7;
964
+ let start;
965
+ query.statement.columns = Array(length);
966
+ for (let i = 0; i < length; ++i) {
967
+ start = index;
968
+ while (x[index++] !== 0);
969
+ const table = x.readUInt32BE(index);
970
+ const number = x.readUInt16BE(index + 4);
971
+ const type = x.readUInt32BE(index + 6);
972
+ query.statement.columns[i] = {
973
+ name: transform.column.from ? transform.column.from(x.toString("utf8", start, index - 1)) : x.toString("utf8", start, index - 1),
974
+ parser: parsers[type],
975
+ table,
976
+ number,
977
+ type
978
+ };
979
+ index += 18;
980
+ }
981
+ result.statement = query.statement;
982
+ if (query.onlyDescribe) return query.resolve(query.statement), write(Sync);
983
+ }
984
+ async function Authentication(x, type = x.readUInt32BE(5)) {
985
+ (type === 3 ? AuthenticationCleartextPassword : type === 5 ? AuthenticationMD5Password : type === 10 ? SASL : type === 11 ? SASLContinue : type === 12 ? SASLFinal : type !== 0 ? UnknownAuth : noop$1)(x, type);
986
+ }
987
+ /* c8 ignore next 5 */
988
+ async function AuthenticationCleartextPassword() {
989
+ const payload = await Pass();
990
+ write(b().p().str(payload).z(1).end());
991
+ }
992
+ async function AuthenticationMD5Password(x) {
993
+ const payload = "md5" + await md5(Buffer.concat([Buffer.from(await md5(await Pass() + user)), x.subarray(9)]));
994
+ write(b().p().str(payload).z(1).end());
995
+ }
996
+ async function SASL() {
997
+ nonce = (await crypto2.randomBytes(18)).toString("base64");
998
+ b().p().str("SCRAM-SHA-256" + b.N);
999
+ const i = b.i;
1000
+ write(b.inc(4).str("n,,n=*,r=" + nonce).i32(b.i - i - 4, i).end());
1001
+ }
1002
+ async function SASLContinue(x) {
1003
+ const res = x.toString("utf8", 9).split(",").reduce((acc, x) => (acc[x[0]] = x.slice(2), acc), {});
1004
+ const saltedPassword = await crypto2.pbkdf2Sync(await Pass(), Buffer.from(res.s, "base64"), parseInt(res.i), 32, "sha256");
1005
+ const clientKey = await hmac(saltedPassword, "Client Key");
1006
+ const auth = "n=*,r=" + nonce + ",r=" + res.r + ",s=" + res.s + ",i=" + res.i + ",c=biws,r=" + res.r;
1007
+ serverSignature = (await hmac(await hmac(saltedPassword, "Server Key"), auth)).toString("base64");
1008
+ const payload = "c=biws,r=" + res.r + ",p=" + xor(clientKey, Buffer.from(await hmac(await sha256(clientKey), auth))).toString("base64");
1009
+ write(b().p().str(payload).end());
1010
+ }
1011
+ function SASLFinal(x) {
1012
+ if (x.toString("utf8", 9).split(b.N, 1)[0].slice(2) === serverSignature) return;
1013
+ /* c8 ignore next 5 */
1014
+ errored(Errors.generic("SASL_SIGNATURE_MISMATCH", "The server did not return the correct signature"));
1015
+ socket.destroy();
1016
+ }
1017
+ function Pass() {
1018
+ return Promise.resolve(typeof options.pass === "function" ? options.pass() : options.pass);
1019
+ }
1020
+ function NoData() {
1021
+ result.statement = query.statement;
1022
+ result.statement.columns = [];
1023
+ if (query.onlyDescribe) return query.resolve(query.statement), write(Sync);
1024
+ }
1025
+ function BackendKeyData(x) {
1026
+ backend.pid = x.readUInt32BE(5);
1027
+ backend.secret = x.readUInt32BE(9);
1028
+ }
1029
+ async function fetchArrayTypes() {
1030
+ needsTypes = false;
1031
+ (await new Query([`
1032
+ select b.oid, b.typarray
1033
+ from pg_catalog.pg_type a
1034
+ left join pg_catalog.pg_type b on b.oid = a.typelem
1035
+ where a.typcategory = 'A'
1036
+ group by b.oid, b.typarray
1037
+ order by b.oid
1038
+ `], [], execute)).forEach(({ oid, typarray }) => addArrayType(oid, typarray));
1039
+ }
1040
+ function addArrayType(oid, typarray) {
1041
+ if (!!options.parsers[typarray] && !!options.serializers[typarray]) return;
1042
+ const parser = options.parsers[oid];
1043
+ options.shared.typeArrayMap[oid] = typarray;
1044
+ options.parsers[typarray] = (xs) => arrayParser(xs, parser, typarray);
1045
+ options.parsers[typarray].array = true;
1046
+ options.serializers[typarray] = (xs) => arraySerializer(xs, options.serializers[oid], options, typarray);
1047
+ }
1048
+ function tryNext(x, xs) {
1049
+ 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];
1050
+ }
1051
+ function fetchState() {
1052
+ const query = new Query([`
1053
+ show transaction_read_only;
1054
+ select pg_catalog.pg_is_in_recovery()
1055
+ `], [], execute, null, { simple: true });
1056
+ query.resolve = ([[a], [b]]) => {
1057
+ backendParameters.default_transaction_read_only = a.transaction_read_only;
1058
+ backendParameters.in_hot_standby = b.pg_is_in_recovery ? "on" : "off";
1059
+ };
1060
+ query.execute();
1061
+ }
1062
+ function ErrorResponse(x) {
1063
+ if (query) {
1064
+ (query.cursorFn || query.describeFirst) && write(Sync);
1065
+ errorResponse = Errors.postgres(parseError(x));
1066
+ } else errored(Errors.postgres(parseError(x)));
1067
+ }
1068
+ function retry(q, error) {
1069
+ delete statements[q.signature];
1070
+ q.retried = error;
1071
+ execute(q);
1072
+ }
1073
+ function NotificationResponse(x) {
1074
+ if (!onnotify) return;
1075
+ let index = 9;
1076
+ while (x[index++] !== 0);
1077
+ onnotify(x.toString("utf8", 9, index - 1), x.toString("utf8", index, x.length - 1));
1078
+ }
1079
+ async function PortalSuspended() {
1080
+ try {
1081
+ const x = await Promise.resolve(query.cursorFn(result));
1082
+ rows = 0;
1083
+ x === CLOSE ? write(Close(query.portal)) : (result = new Result(), write(Execute("", query.cursorRows)));
1084
+ } catch (err) {
1085
+ write(Sync);
1086
+ query.reject(err);
1087
+ }
1088
+ }
1089
+ function CloseComplete() {
1090
+ result.count && query.cursorFn(result);
1091
+ query.resolve(result);
1092
+ }
1093
+ function CopyInResponse() {
1094
+ stream = new Stream.Writable({
1095
+ autoDestroy: true,
1096
+ write(chunk, encoding, callback) {
1097
+ socket.write(b().d().raw(chunk).end(), callback);
1098
+ },
1099
+ destroy(error, callback) {
1100
+ callback(error);
1101
+ socket.write(b().f().str(error + b.N).end());
1102
+ stream = null;
1103
+ },
1104
+ final(callback) {
1105
+ socket.write(b().c().end());
1106
+ final = callback;
1107
+ stream = null;
1108
+ }
1109
+ });
1110
+ query.resolve(stream);
1111
+ }
1112
+ function CopyOutResponse() {
1113
+ stream = new Stream.Readable({ read() {
1114
+ socket.resume();
1115
+ } });
1116
+ query.resolve(stream);
1117
+ }
1118
+ /* c8 ignore next 3 */
1119
+ function CopyBothResponse() {
1120
+ stream = new Stream.Duplex({
1121
+ autoDestroy: true,
1122
+ read() {
1123
+ socket.resume();
1124
+ },
1125
+ write(chunk, encoding, callback) {
1126
+ socket.write(b().d().raw(chunk).end(), callback);
1127
+ },
1128
+ destroy(error, callback) {
1129
+ callback(error);
1130
+ socket.write(b().f().str(error + b.N).end());
1131
+ stream = null;
1132
+ },
1133
+ final(callback) {
1134
+ socket.write(b().c().end());
1135
+ final = callback;
1136
+ }
1137
+ });
1138
+ query.resolve(stream);
1139
+ }
1140
+ function CopyData(x) {
1141
+ stream && (stream.push(x.subarray(5)) || socket.pause());
1142
+ }
1143
+ function CopyDone() {
1144
+ stream && stream.push(null);
1145
+ stream = null;
1146
+ }
1147
+ function NoticeResponse(x) {
1148
+ onnotice ? onnotice(parseError(x)) : console.log(parseError(x));
1149
+ }
1150
+ /* c8 ignore next 3 */
1151
+ function EmptyQueryResponse() {}
1152
+ /* c8 ignore next 3 */
1153
+ function FunctionCallResponse() {
1154
+ errored(Errors.notSupported("FunctionCallResponse"));
1155
+ }
1156
+ /* c8 ignore next 3 */
1157
+ function NegotiateProtocolVersion() {
1158
+ errored(Errors.notSupported("NegotiateProtocolVersion"));
1159
+ }
1160
+ /* c8 ignore next 3 */
1161
+ function UnknownMessage(x) {
1162
+ console.error("Postgres.js : Unknown Message:", x[0]);
1163
+ }
1164
+ /* c8 ignore next 3 */
1165
+ function UnknownAuth(x, type) {
1166
+ console.error("Postgres.js : Unknown Auth:", type);
1167
+ }
1168
+ function Bind(parameters, types, statement = "", portal = "") {
1169
+ let prev, type;
1170
+ b().B().str(portal + b.N).str(statement + b.N).i16(0).i16(parameters.length);
1171
+ parameters.forEach((x, i) => {
1172
+ if (x === null) return b.i32(4294967295);
1173
+ type = types[i];
1174
+ parameters[i] = x = type in options.serializers ? options.serializers[type](x) : "" + x;
1175
+ prev = b.i;
1176
+ b.inc(4).str(x).i32(b.i - prev - 4, prev);
1177
+ });
1178
+ b.i16(0);
1179
+ return b.end();
1180
+ }
1181
+ function Parse(str, parameters, types, name = "") {
1182
+ b().P().str(name + b.N).str(str + b.N).i16(parameters.length);
1183
+ parameters.forEach((x, i) => b.i32(types[i] || 0));
1184
+ return b.end();
1185
+ }
1186
+ function Describe(x, name = "") {
1187
+ return b().D().str(x).str(name + b.N).end();
1188
+ }
1189
+ function Execute(portal = "", rows = 0) {
1190
+ return Buffer.concat([b().E().str(portal + b.N).i32(rows).end(), Flush]);
1191
+ }
1192
+ function Close(portal = "") {
1193
+ return Buffer.concat([b().C().str("P").str(portal + b.N).end(), b().S().end()]);
1194
+ }
1195
+ function StartupMessage() {
1196
+ return cancelMessage || b().inc(4).i16(3).z(2).str(Object.entries(Object.assign({
1197
+ user,
1198
+ database,
1199
+ client_encoding: "UTF8"
1200
+ }, options.connection)).filter(([, v]) => v).map(([k, v]) => k + b.N + v).join(b.N)).z(2).end(0);
1201
+ }
1202
+ }
1203
+ function parseError(x) {
1204
+ const error = {};
1205
+ let start = 5;
1206
+ for (let i = 5; i < x.length - 1; i++) if (x[i] === 0) {
1207
+ error[errorFields[x[start]]] = x.toString("utf8", start + 1, i);
1208
+ start = i + 1;
1209
+ }
1210
+ return error;
1211
+ }
1212
+ function md5(x) {
1213
+ return crypto2.createHash("md5").update(x).digest("hex");
1214
+ }
1215
+ function hmac(key, x) {
1216
+ return crypto2.createHmac("sha256", key).update(x).digest();
1217
+ }
1218
+ function sha256(x) {
1219
+ return crypto2.createHash("sha256").update(x).digest();
1220
+ }
1221
+ function xor(a, b) {
1222
+ const length = Math.max(a.length, b.length);
1223
+ const buffer = Buffer.allocUnsafe(length);
1224
+ for (let i = 0; i < length; i++) buffer[i] = a[i] ^ b[i];
1225
+ return buffer;
1226
+ }
1227
+ function timer(fn, seconds) {
1228
+ seconds = typeof seconds === "function" ? seconds() : seconds;
1229
+ if (!seconds) return {
1230
+ cancel: noop$1,
1231
+ start: noop$1
1232
+ };
1233
+ let timer;
1234
+ return {
1235
+ cancel() {
1236
+ timer && (clearTimeout(timer), timer = null);
1237
+ },
1238
+ start() {
1239
+ timer && clearTimeout(timer);
1240
+ timer = setTimeout(done, seconds * 1e3, arguments);
1241
+ }
1242
+ };
1243
+ function done(args) {
1244
+ fn.apply(null, args);
1245
+ timer = null;
1246
+ }
1247
+ }
1248
+ const noop = () => {};
1249
+ function Subscribe(postgres, options) {
1250
+ const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {};
1251
+ let connection, stream, ended = false;
1252
+ const sql = subscribe.sql = postgres({
1253
+ ...options,
1254
+ transform: {
1255
+ column: {},
1256
+ value: {},
1257
+ row: {}
1258
+ },
1259
+ max: 1,
1260
+ fetch_types: false,
1261
+ idle_timeout: null,
1262
+ max_lifetime: null,
1263
+ connection: {
1264
+ ...options.connection,
1265
+ replication: "database"
1266
+ },
1267
+ onclose: async function() {
1268
+ if (ended) return;
1269
+ stream = null;
1270
+ state.pid = state.secret = void 0;
1271
+ connected(await init(sql, slot, options.publications));
1272
+ subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe()));
1273
+ },
1274
+ no_subscribe: true
1275
+ });
1276
+ const end = sql.end, close = sql.close;
1277
+ sql.end = async () => {
1278
+ ended = true;
1279
+ stream && await new Promise((r) => (stream.once("close", r), stream.end()));
1280
+ return end();
1281
+ };
1282
+ sql.close = async () => {
1283
+ stream && await new Promise((r) => (stream.once("close", r), stream.end()));
1284
+ return close();
1285
+ };
1286
+ return subscribe;
1287
+ async function subscribe(event, fn, onsubscribe = noop, onerror = noop) {
1288
+ event = parseEvent(event);
1289
+ if (!connection) connection = init(sql, slot, options.publications);
1290
+ const subscriber = {
1291
+ fn,
1292
+ onsubscribe
1293
+ };
1294
+ const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, new Set([subscriber])).get(event);
1295
+ const unsubscribe = () => {
1296
+ fns.delete(subscriber);
1297
+ fns.size === 0 && subscribers.delete(event);
1298
+ };
1299
+ return connection.then((x) => {
1300
+ connected(x);
1301
+ onsubscribe();
1302
+ stream && stream.on("error", onerror);
1303
+ return {
1304
+ unsubscribe,
1305
+ state,
1306
+ sql
1307
+ };
1308
+ });
1309
+ }
1310
+ function connected(x) {
1311
+ stream = x.stream;
1312
+ state.pid = x.state.pid;
1313
+ state.secret = x.state.secret;
1314
+ }
1315
+ async function init(sql, slot, publications) {
1316
+ if (!publications) throw new Error("Missing publication names");
1317
+ const xs = await sql.unsafe(`CREATE_REPLICATION_SLOT ${slot} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`);
1318
+ const [x] = xs;
1319
+ const stream = await sql.unsafe(`START_REPLICATION SLOT ${slot} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')`).writable();
1320
+ const state = { lsn: Buffer.concat(x.consistent_point.split("/").map((x) => Buffer.from(("00000000" + x).slice(-8), "hex"))) };
1321
+ stream.on("data", data);
1322
+ stream.on("error", error);
1323
+ stream.on("close", sql.close);
1324
+ return {
1325
+ stream,
1326
+ state: xs.state
1327
+ };
1328
+ function error(e) {
1329
+ console.error("Unexpected error during logical streaming - reconnecting", e);
1330
+ }
1331
+ function data(x) {
1332
+ if (x[0] === 119) parse(x.subarray(25), state, sql.options.parsers, handle, options.transform);
1333
+ else if (x[0] === 107 && x[17]) {
1334
+ state.lsn = x.subarray(1, 9);
1335
+ pong();
1336
+ }
1337
+ }
1338
+ function handle(a, b) {
1339
+ const path = b.relation.schema + "." + b.relation.table;
1340
+ call("*", a, b);
1341
+ call("*:" + path, a, b);
1342
+ b.relation.keys.length && call("*:" + path + "=" + b.relation.keys.map((x) => a[x.name]), a, b);
1343
+ call(b.command, a, b);
1344
+ call(b.command + ":" + path, a, b);
1345
+ b.relation.keys.length && call(b.command + ":" + path + "=" + b.relation.keys.map((x) => a[x.name]), a, b);
1346
+ }
1347
+ function pong() {
1348
+ const x = Buffer.alloc(34);
1349
+ x[0] = "r".charCodeAt(0);
1350
+ x.fill(state.lsn, 1);
1351
+ x.writeBigInt64BE(BigInt(Date.now() - Date.UTC(2e3, 0, 1)) * BigInt(1e3), 25);
1352
+ stream.write(x);
1353
+ }
1354
+ }
1355
+ function call(x, a, b) {
1356
+ subscribers.has(x) && subscribers.get(x).forEach(({ fn }) => fn(a, b, x));
1357
+ }
1358
+ }
1359
+ function Time(x) {
1360
+ return new Date(Date.UTC(2e3, 0, 1) + Number(x / BigInt(1e3)));
1361
+ }
1362
+ function parse(x, state, parsers, handle, transform) {
1363
+ const char = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc);
1364
+ Object.entries({
1365
+ R: (x) => {
1366
+ let i = 1;
1367
+ const r = state[x.readUInt32BE(i)] = {
1368
+ schema: x.toString("utf8", i += 4, i = x.indexOf(0, i)) || "pg_catalog",
1369
+ table: x.toString("utf8", i + 1, i = x.indexOf(0, i + 1)),
1370
+ columns: Array(x.readUInt16BE(i += 2)),
1371
+ keys: []
1372
+ };
1373
+ i += 2;
1374
+ let columnIndex = 0, column;
1375
+ while (i < x.length) {
1376
+ column = r.columns[columnIndex++] = {
1377
+ key: x[i++],
1378
+ name: transform.column.from ? transform.column.from(x.toString("utf8", i, i = x.indexOf(0, i))) : x.toString("utf8", i, i = x.indexOf(0, i)),
1379
+ type: x.readUInt32BE(i += 1),
1380
+ parser: parsers[x.readUInt32BE(i)],
1381
+ atttypmod: x.readUInt32BE(i += 4)
1382
+ };
1383
+ column.key && r.keys.push(column);
1384
+ i += 4;
1385
+ }
1386
+ },
1387
+ Y: () => {},
1388
+ O: () => {},
1389
+ B: (x) => {
1390
+ state.date = Time(x.readBigInt64BE(9));
1391
+ state.lsn = x.subarray(1, 9);
1392
+ },
1393
+ I: (x) => {
1394
+ let i = 1;
1395
+ const relation = state[x.readUInt32BE(i)];
1396
+ const { row } = tuples(x, relation.columns, i += 7, transform);
1397
+ handle(row, {
1398
+ command: "insert",
1399
+ relation
1400
+ });
1401
+ },
1402
+ D: (x) => {
1403
+ let i = 1;
1404
+ const relation = state[x.readUInt32BE(i)];
1405
+ i += 4;
1406
+ const key = x[i] === 75;
1407
+ handle(key || x[i] === 79 ? tuples(x, relation.columns, i += 3, transform).row : null, {
1408
+ command: "delete",
1409
+ relation,
1410
+ key
1411
+ });
1412
+ },
1413
+ U: (x) => {
1414
+ let i = 1;
1415
+ const relation = state[x.readUInt32BE(i)];
1416
+ i += 4;
1417
+ const key = x[i] === 75;
1418
+ const xs = key || x[i] === 79 ? tuples(x, relation.columns, i += 3, transform) : null;
1419
+ xs && (i = xs.i);
1420
+ const { row } = tuples(x, relation.columns, i + 3, transform);
1421
+ handle(row, {
1422
+ command: "update",
1423
+ relation,
1424
+ key,
1425
+ old: xs && xs.row
1426
+ });
1427
+ },
1428
+ T: () => {},
1429
+ C: () => {}
1430
+ }).reduce(char, {})[x[0]](x);
1431
+ }
1432
+ function tuples(x, columns, xi, transform) {
1433
+ let type, column, value;
1434
+ const row = transform.raw ? new Array(columns.length) : {};
1435
+ for (let i = 0; i < columns.length; i++) {
1436
+ type = x[xi++];
1437
+ column = columns[i];
1438
+ 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)));
1439
+ 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;
1440
+ }
1441
+ return {
1442
+ i: xi,
1443
+ row: transform.row.from ? transform.row.from(row) : row
1444
+ };
1445
+ }
1446
+ function parseEvent(x) {
1447
+ const xs = x.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) || [];
1448
+ if (!xs) throw new Error("Malformed subscribe pattern: " + x);
1449
+ const [, command, path, key] = xs;
1450
+ return (command || "*") + (path ? ":" + (path.indexOf(".") === -1 ? "public." + path : path) : "") + (key ? "=" + key : "");
1451
+ }
1452
+ function largeObject(sql, oid, mode = 393216) {
1453
+ return new Promise(async (resolve, reject) => {
1454
+ await sql.begin(async (sql) => {
1455
+ let finish;
1456
+ !oid && ([{oid}] = await sql`select lo_creat(-1) as oid`);
1457
+ const [{ fd }] = await sql`select lo_open(${oid}, ${mode}) as fd`;
1458
+ const lo = {
1459
+ writable,
1460
+ readable,
1461
+ close: () => sql`select lo_close(${fd})`.then(finish),
1462
+ tell: () => sql`select lo_tell64(${fd})`,
1463
+ read: (x) => sql`select loread(${fd}, ${x}) as data`,
1464
+ write: (x) => sql`select lowrite(${fd}, ${x})`,
1465
+ truncate: (x) => sql`select lo_truncate64(${fd}, ${x})`,
1466
+ seek: (x, whence = 0) => sql`select lo_lseek64(${fd}, ${x}, ${whence})`,
1467
+ size: () => sql`
1468
+ select
1469
+ lo_lseek64(${fd}, location, 0) as position,
1470
+ seek.size
1471
+ from (
1472
+ select
1473
+ lo_lseek64($1, 0, 2) as size,
1474
+ tell.location
1475
+ from (select lo_tell64($1) as location) tell
1476
+ ) seek
1477
+ `
1478
+ };
1479
+ resolve(lo);
1480
+ return new Promise(async (r) => finish = r);
1481
+ async function readable({ highWaterMark = 2048 * 8, start = 0, end = Infinity } = {}) {
1482
+ let max = end - start;
1483
+ start && await lo.seek(start);
1484
+ return new Stream.Readable({
1485
+ highWaterMark,
1486
+ async read(size) {
1487
+ const l = size > max ? size - max : size;
1488
+ max -= size;
1489
+ const [{ data }] = await lo.read(l);
1490
+ this.push(data);
1491
+ if (data.length < size) this.push(null);
1492
+ }
1493
+ });
1494
+ }
1495
+ async function writable({ highWaterMark = 2048 * 8, start = 0 } = {}) {
1496
+ start && await lo.seek(start);
1497
+ return new Stream.Writable({
1498
+ highWaterMark,
1499
+ write(chunk, encoding, callback) {
1500
+ lo.write(chunk).then(() => callback(), callback);
1501
+ }
1502
+ });
1503
+ }
1504
+ }).catch(reject);
1505
+ });
1506
+ }
1507
+ Object.assign(Postgres, {
1508
+ PostgresError,
1509
+ toPascal,
1510
+ pascal,
1511
+ toCamel,
1512
+ camel,
1513
+ toKebab,
1514
+ kebab,
1515
+ fromPascal,
1516
+ fromCamel,
1517
+ fromKebab,
1518
+ BigInt: {
1519
+ to: 20,
1520
+ from: [20],
1521
+ parse: (x) => BigInt(x),
1522
+ serialize: (x) => x.toString()
1523
+ }
1524
+ });
1525
+ var src_default = Postgres;
1526
+ function Postgres(a, b) {
1527
+ const options = parseOptions(a, b), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options });
1528
+ let ending = false;
1529
+ 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 = {
1530
+ connecting,
1531
+ reserved,
1532
+ closed,
1533
+ ended,
1534
+ open,
1535
+ busy,
1536
+ full
1537
+ };
1538
+ const connections = [...Array(options.max)].map(() => connection_default(options, queues, {
1539
+ onopen,
1540
+ onend,
1541
+ onclose
1542
+ }));
1543
+ const sql = Sql(handler);
1544
+ Object.assign(sql, {
1545
+ get parameters() {
1546
+ return options.parameters;
1547
+ },
1548
+ largeObject: largeObject.bind(null, sql),
1549
+ subscribe,
1550
+ CLOSE,
1551
+ END: CLOSE,
1552
+ PostgresError,
1553
+ options,
1554
+ reserve,
1555
+ listen,
1556
+ begin,
1557
+ close,
1558
+ end
1559
+ });
1560
+ return sql;
1561
+ function Sql(handler) {
1562
+ handler.debug = options.debug;
1563
+ Object.entries(options.types).reduce((acc, [name, type]) => {
1564
+ acc[name] = (x) => new Parameter(x, type.to);
1565
+ return acc;
1566
+ }, typed);
1567
+ Object.assign(sql, {
1568
+ types: typed,
1569
+ typed,
1570
+ unsafe,
1571
+ notify,
1572
+ array,
1573
+ json,
1574
+ file
1575
+ });
1576
+ return sql;
1577
+ function typed(value, type) {
1578
+ return new Parameter(value, type);
1579
+ }
1580
+ function sql(strings, ...args) {
1581
+ return strings && Array.isArray(strings.raw) ? new Query(strings, args, handler, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args);
1582
+ }
1583
+ function unsafe(string, args = [], options = {}) {
1584
+ arguments.length === 2 && !Array.isArray(args) && (options = args, args = []);
1585
+ return new Query([string], args, handler, cancel, {
1586
+ prepare: false,
1587
+ ...options,
1588
+ simple: "simple" in options ? options.simple : args.length === 0
1589
+ });
1590
+ }
1591
+ function file(path, args = [], options = {}) {
1592
+ arguments.length === 2 && !Array.isArray(args) && (options = args, args = []);
1593
+ return new Query([], args, (query) => {
1594
+ fs.readFile(path, "utf8", (err, string) => {
1595
+ if (err) return query.reject(err);
1596
+ query.strings = [string];
1597
+ handler(query);
1598
+ });
1599
+ }, cancel, {
1600
+ ...options,
1601
+ simple: "simple" in options ? options.simple : args.length === 0
1602
+ });
1603
+ }
1604
+ }
1605
+ async function listen(name, fn, onlisten) {
1606
+ const listener = {
1607
+ fn,
1608
+ onlisten
1609
+ };
1610
+ const sql = listen.sql || (listen.sql = Postgres({
1611
+ ...options,
1612
+ max: 1,
1613
+ idle_timeout: null,
1614
+ max_lifetime: null,
1615
+ fetch_types: false,
1616
+ onclose() {
1617
+ Object.entries(listen.channels).forEach(([name, { listeners }]) => {
1618
+ delete listen.channels[name];
1619
+ Promise.all(listeners.map((l) => listen(name, l.fn, l.onlisten).catch(() => {})));
1620
+ });
1621
+ },
1622
+ onnotify(c, x) {
1623
+ c in listen.channels && listen.channels[c].listeners.forEach((l) => l.fn(x));
1624
+ }
1625
+ }));
1626
+ const channels = listen.channels || (listen.channels = {});
1627
+ if (name in channels) {
1628
+ channels[name].listeners.push(listener);
1629
+ const result = await channels[name].result;
1630
+ listener.onlisten && listener.onlisten();
1631
+ return {
1632
+ state: result.state,
1633
+ unlisten
1634
+ };
1635
+ }
1636
+ channels[name] = {
1637
+ result: sql`listen ${sql.unsafe("\"" + name.replace(/"/g, "\"\"") + "\"")}`,
1638
+ listeners: [listener]
1639
+ };
1640
+ const result = await channels[name].result;
1641
+ listener.onlisten && listener.onlisten();
1642
+ return {
1643
+ state: result.state,
1644
+ unlisten
1645
+ };
1646
+ async function unlisten() {
1647
+ if (name in channels === false) return;
1648
+ channels[name].listeners = channels[name].listeners.filter((x) => x !== listener);
1649
+ if (channels[name].listeners.length) return;
1650
+ delete channels[name];
1651
+ return sql`unlisten ${sql.unsafe("\"" + name.replace(/"/g, "\"\"") + "\"")}`;
1652
+ }
1653
+ }
1654
+ async function notify(channel, payload) {
1655
+ return await sql`select pg_notify(${channel}, ${"" + payload})`;
1656
+ }
1657
+ async function reserve() {
1658
+ const queue = queue_default();
1659
+ const c = open.length ? open.shift() : await new Promise((resolve, reject) => {
1660
+ const query = {
1661
+ reserve: resolve,
1662
+ reject
1663
+ };
1664
+ queries.push(query);
1665
+ closed.length && connect(closed.shift(), query);
1666
+ });
1667
+ move(c, reserved);
1668
+ c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved);
1669
+ c.reserved.release = true;
1670
+ const sql = Sql(handler);
1671
+ sql.release = () => {
1672
+ c.reserved = null;
1673
+ onopen(c);
1674
+ };
1675
+ return sql;
1676
+ function handler(q) {
1677
+ c.queue === full ? queue.push(q) : c.execute(q) || move(c, full);
1678
+ }
1679
+ }
1680
+ async function begin(options, fn) {
1681
+ !fn && (fn = options, options = "");
1682
+ const queries = queue_default();
1683
+ let savepoints = 0, connection, prepare = null;
1684
+ try {
1685
+ await sql.unsafe("begin " + options.replace(/[^a-z ]/gi, ""), [], { onexecute }).execute();
1686
+ return await Promise.race([scope(connection, fn), new Promise((_, reject) => connection.onclose = reject)]);
1687
+ } catch (error) {
1688
+ throw error;
1689
+ }
1690
+ async function scope(c, fn, name) {
1691
+ const sql = Sql(handler);
1692
+ sql.savepoint = savepoint;
1693
+ sql.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi);
1694
+ let uncaughtError, result;
1695
+ name && await sql`savepoint ${sql(name)}`;
1696
+ try {
1697
+ result = await new Promise((resolve, reject) => {
1698
+ const x = fn(sql);
1699
+ Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject);
1700
+ });
1701
+ if (uncaughtError) throw uncaughtError;
1702
+ } catch (e) {
1703
+ await (name ? sql`rollback to ${sql(name)}` : sql`rollback`);
1704
+ throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e;
1705
+ }
1706
+ if (!name) prepare ? await sql`prepare transaction '${sql.unsafe(prepare)}'` : await sql`commit`;
1707
+ return result;
1708
+ function savepoint(name, fn) {
1709
+ if (name && Array.isArray(name.raw)) return savepoint((sql) => sql.apply(sql, arguments));
1710
+ arguments.length === 1 && (fn = name, name = null);
1711
+ return scope(c, fn, "s" + savepoints++ + (name ? "_" + name : ""));
1712
+ }
1713
+ function handler(q) {
1714
+ q.catch((e) => uncaughtError || (uncaughtError = e));
1715
+ c.queue === full ? queries.push(q) : c.execute(q) || move(c, full);
1716
+ }
1717
+ }
1718
+ function onexecute(c) {
1719
+ connection = c;
1720
+ move(c, reserved);
1721
+ c.reserved = () => queries.length ? c.execute(queries.shift()) : move(c, reserved);
1722
+ }
1723
+ }
1724
+ function move(c, queue) {
1725
+ c.queue.remove(c);
1726
+ queue.push(c);
1727
+ c.queue = queue;
1728
+ queue === open ? c.idleTimer.start() : c.idleTimer.cancel();
1729
+ return c;
1730
+ }
1731
+ function json(x) {
1732
+ return new Parameter(x, 3802);
1733
+ }
1734
+ function array(x, type) {
1735
+ if (!Array.isArray(x)) return array(Array.from(arguments));
1736
+ return new Parameter(x, type || (x.length ? inferType(x) || 25 : 0), options.shared.typeArrayMap);
1737
+ }
1738
+ function handler(query) {
1739
+ if (ending) return query.reject(Errors.connection("CONNECTION_ENDED", options, options));
1740
+ if (open.length) return go(open.shift(), query);
1741
+ if (closed.length) return connect(closed.shift(), query);
1742
+ busy.length ? go(busy.shift(), query) : queries.push(query);
1743
+ }
1744
+ function go(c, query) {
1745
+ return c.execute(query) ? move(c, busy) : move(c, full);
1746
+ }
1747
+ function cancel(query) {
1748
+ return new Promise((resolve, reject) => {
1749
+ query.state ? query.active ? connection_default(options).cancel(query.state, resolve, reject) : query.cancelled = {
1750
+ resolve,
1751
+ reject
1752
+ } : (queries.remove(query), query.cancelled = true, query.reject(Errors.generic("57014", "canceling statement due to user request")), resolve());
1753
+ });
1754
+ }
1755
+ async function end({ timeout = null } = {}) {
1756
+ if (ending) return ending;
1757
+ await 1;
1758
+ let timer;
1759
+ return ending = Promise.race([new Promise((r) => timeout !== null && (timer = setTimeout(destroy, timeout * 1e3, r))), Promise.all(connections.map((c) => c.end()).concat(listen.sql ? listen.sql.end({ timeout: 0 }) : [], subscribe.sql ? subscribe.sql.end({ timeout: 0 }) : []))]).then(() => clearTimeout(timer));
1760
+ }
1761
+ async function close() {
1762
+ await Promise.all(connections.map((c) => c.end()));
1763
+ }
1764
+ async function destroy(resolve) {
1765
+ await Promise.all(connections.map((c) => c.terminate()));
1766
+ while (queries.length) queries.shift().reject(Errors.connection("CONNECTION_DESTROYED", options));
1767
+ resolve();
1768
+ }
1769
+ function connect(c, query) {
1770
+ move(c, connecting);
1771
+ c.connect(query);
1772
+ return c;
1773
+ }
1774
+ function onend(c) {
1775
+ move(c, ended);
1776
+ }
1777
+ function onopen(c) {
1778
+ if (queries.length === 0) return move(c, open);
1779
+ let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true;
1780
+ while (ready && queries.length && max-- > 0) {
1781
+ const query = queries.shift();
1782
+ if (query.reserve) return query.reserve(c);
1783
+ ready = c.execute(query);
1784
+ }
1785
+ ready ? move(c, busy) : move(c, full);
1786
+ }
1787
+ function onclose(c, e) {
1788
+ move(c, closed);
1789
+ c.reserved = null;
1790
+ c.onclose && (c.onclose(e), c.onclose = null);
1791
+ options.onclose && options.onclose(c.id);
1792
+ queries.length && connect(c, queries.shift());
1793
+ }
1794
+ }
1795
+ function parseOptions(a, b) {
1796
+ if (a && a.shared) return a;
1797
+ const env = process.env, o = (!a || typeof a === "string" ? b : a) || {}, { url, multihost } = parseUrl(a), query = [...url.searchParams].reduce((a, [b, c]) => (a[b] = c, a), {}), 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();
1798
+ o.no_prepare && (o.prepare = false);
1799
+ query.sslmode && (query.ssl = query.sslmode, delete query.sslmode);
1800
+ "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout);
1801
+ query.sslrootcert === "system" && (query.ssl = "verify-full");
1802
+ const ints = [
1803
+ "idle_timeout",
1804
+ "connect_timeout",
1805
+ "max_lifetime",
1806
+ "max_pipeline",
1807
+ "backoff",
1808
+ "keep_alive"
1809
+ ];
1810
+ const defaults = {
1811
+ max: globalThis.Cloudflare ? 3 : 10,
1812
+ ssl: false,
1813
+ sslnegotiation: null,
1814
+ idle_timeout: null,
1815
+ connect_timeout: 30,
1816
+ max_lifetime,
1817
+ max_pipeline: 100,
1818
+ backoff,
1819
+ keep_alive: 60,
1820
+ prepare: true,
1821
+ debug: false,
1822
+ fetch_types: true,
1823
+ publications: "alltables",
1824
+ target_session_attrs: null
1825
+ };
1826
+ return {
1827
+ host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]),
1828
+ port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)),
1829
+ path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port,
1830
+ database: o.database || o.db || (url.pathname || "").slice(1) || env.PGDATABASE || user,
1831
+ user,
1832
+ pass: o.pass || o.password || url.password || env.PGPASSWORD || "",
1833
+ ...Object.entries(defaults).reduce((acc, [k, d]) => {
1834
+ const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env["PG" + k.toUpperCase()] || d;
1835
+ acc[k] = typeof value === "string" && ints.includes(k) ? +value : value;
1836
+ return acc;
1837
+ }, {}),
1838
+ connection: {
1839
+ application_name: env.PGAPPNAME || "postgres.js",
1840
+ ...o.connection,
1841
+ ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {})
1842
+ },
1843
+ types: o.types || {},
1844
+ target_session_attrs: tsa(o, url, env),
1845
+ onnotice: o.onnotice,
1846
+ onnotify: o.onnotify,
1847
+ onclose: o.onclose,
1848
+ onparameter: o.onparameter,
1849
+ socket: o.socket,
1850
+ transform: parseTransform(o.transform || { undefined: void 0 }),
1851
+ parameters: {},
1852
+ shared: {
1853
+ retries: 0,
1854
+ typeArrayMap: {}
1855
+ },
1856
+ ...mergeUserTypes(o.types)
1857
+ };
1858
+ }
1859
+ function tsa(o, url, env) {
1860
+ const x = o.target_session_attrs || url.searchParams.get("target_session_attrs") || env.PGTARGETSESSIONATTRS;
1861
+ if (!x || [
1862
+ "read-write",
1863
+ "read-only",
1864
+ "primary",
1865
+ "standby",
1866
+ "prefer-standby"
1867
+ ].includes(x)) return x;
1868
+ throw new Error("target_session_attrs " + x + " is not supported");
1869
+ }
1870
+ function backoff(retries) {
1871
+ return (.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20);
1872
+ }
1873
+ function max_lifetime() {
1874
+ return 60 * (30 + Math.random() * 30);
1875
+ }
1876
+ function parseTransform(x) {
1877
+ return {
1878
+ undefined: x.undefined,
1879
+ column: {
1880
+ from: typeof x.column === "function" ? x.column : x.column && x.column.from,
1881
+ to: x.column && x.column.to
1882
+ },
1883
+ value: {
1884
+ from: typeof x.value === "function" ? x.value : x.value && x.value.from,
1885
+ to: x.value && x.value.to
1886
+ },
1887
+ row: {
1888
+ from: typeof x.row === "function" ? x.row : x.row && x.row.from,
1889
+ to: x.row && x.row.to
1890
+ }
1891
+ };
1892
+ }
1893
+ function parseUrl(url) {
1894
+ if (!url || typeof url !== "string") return { url: { searchParams: /* @__PURE__ */ new Map() } };
1895
+ let host = url;
1896
+ host = host.slice(host.indexOf("://") + 3).split(/[?/]/)[0];
1897
+ host = decodeURIComponent(host.slice(host.indexOf("@") + 1));
1898
+ const urlObj = new URL(url.replace(host, host.split(",")[0]));
1899
+ return {
1900
+ url: {
1901
+ username: decodeURIComponent(urlObj.username),
1902
+ password: decodeURIComponent(urlObj.password),
1903
+ host: urlObj.host,
1904
+ hostname: urlObj.hostname,
1905
+ port: urlObj.port,
1906
+ pathname: urlObj.pathname,
1907
+ searchParams: urlObj.searchParams
1908
+ },
1909
+ multihost: host.indexOf(",") > -1 && host
1910
+ };
1911
+ }
1912
+ function osUsername() {
1913
+ try {
1914
+ return os.userInfo().username;
1915
+ } catch (_) {
1916
+ return process.env.USERNAME || process.env.USER || process.env.LOGNAME;
1917
+ }
1918
+ }
1919
+ //#endregion
1920
+ export { src_default as default };