@coffre/db 0.14.5 → 0.15.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 (214) hide show
  1. package/README.md +2 -1
  2. package/dist/change-records-_fKvahvs.js +55 -0
  3. package/dist/connect.d.ts +22 -10
  4. package/dist/connect.js +74 -12
  5. package/dist/database-CVteLhp1.d.ts +410 -0
  6. package/dist/{database-BadNeeN-.js → database-D55ENPX-.js} +46 -25
  7. package/dist/dialect.d.ts +4 -3
  8. package/dist/dialect.js +14 -5
  9. package/dist/grants.d.ts +4 -4
  10. package/dist/grants.js +4 -4
  11. package/dist/hyperdrive.d.ts +48 -23
  12. package/dist/hyperdrive.js +168 -91
  13. package/dist/index.d.ts +3 -3
  14. package/dist/index.js +1 -1
  15. package/dist/log-DaD7fyUq.d.ts +722 -0
  16. package/dist/log.d.ts +2 -622
  17. package/dist/log.js +178 -13
  18. package/dist/migrate.d.ts +43 -3
  19. package/dist/migrate.js +149 -29
  20. package/dist/migrations/postgres/0022_log_015.sql +672 -0
  21. package/dist/migrations/postgres/0023_change_path.sql +153 -0
  22. package/dist/migrations/postgres/0024_use_015.sql +556 -0
  23. package/dist/migrations/postgres/0025_app_change.sql +221 -0
  24. package/dist/migrations/postgres/0026_issue_lock.sql +106 -0
  25. package/dist/migrations/postgres/0027_retention.sql +118 -0
  26. package/dist/migrations/postgres/0028_use_stalls.sql +594 -0
  27. package/dist/migrations/postgres/0029_use_objects.sql +887 -0
  28. package/dist/migrations/postgres/0030_unarchive_restores.sql +259 -0
  29. package/dist/migrations/postgres/0031_app_read.sql +65 -0
  30. package/dist/migrations/postgres/0032_secrets_live_index.sql +4 -0
  31. package/dist/migrations/postgres/0033_use_generations.sql +582 -0
  32. package/dist/migrations/postgres/0034_vault_credentials.sql +153 -0
  33. package/dist/migrations/postgres/0035_first_days.sql +3 -0
  34. package/dist/migrations/postgres/0036_vault_issues.sql +91 -0
  35. package/dist/migrations/postgres/0037_vault_bindings.sql +271 -0
  36. package/dist/migrations/postgres/0040_binding_origin.sql +159 -0
  37. package/dist/migrations/postgres/0041_cutover.sql +132 -0
  38. package/dist/migrations/postgres/0042_sign_in_index.sql +7 -0
  39. package/dist/migrations/postgres/0043_issue_revoke_index.sql +4 -0
  40. package/dist/migrations/postgres/0044_use_by_name.sql +705 -0
  41. package/dist/migrations/postgres/0045_decide_first.sql +878 -0
  42. package/dist/migrations/postgres/0046_way_in_uses.sql +1149 -0
  43. package/dist/migrations/postgres/0047_cutover_finish.sql +268 -0
  44. package/dist/migrations/postgres/0048_use_batch.sql +59 -0
  45. package/dist/migrations/postgres/0049_reads.sql +171 -0
  46. package/dist/migrations/postgres/meta/0022_snapshot.json +3831 -0
  47. package/dist/migrations/postgres/meta/0023_snapshot.json +3831 -0
  48. package/dist/migrations/postgres/meta/0024_snapshot.json +3831 -0
  49. package/dist/migrations/postgres/meta/0025_snapshot.json +3831 -0
  50. package/dist/migrations/postgres/meta/0026_snapshot.json +3831 -0
  51. package/dist/migrations/postgres/meta/0027_snapshot.json +3853 -0
  52. package/dist/migrations/postgres/meta/0028_snapshot.json +3853 -0
  53. package/dist/migrations/postgres/meta/0029_snapshot.json +3859 -0
  54. package/dist/migrations/postgres/meta/0030_snapshot.json +3859 -0
  55. package/dist/migrations/postgres/meta/0031_snapshot.json +3859 -0
  56. package/dist/migrations/postgres/meta/0032_snapshot.json +3875 -0
  57. package/dist/migrations/postgres/meta/0033_snapshot.json +3875 -0
  58. package/dist/migrations/postgres/meta/0034_snapshot.json +3875 -0
  59. package/dist/migrations/postgres/meta/0035_snapshot.json +3875 -0
  60. package/dist/migrations/postgres/meta/0036_snapshot.json +3875 -0
  61. package/dist/migrations/postgres/meta/0037_snapshot.json +3875 -0
  62. package/dist/migrations/postgres/meta/0038_snapshot.json +3881 -0
  63. package/dist/migrations/postgres/meta/0039_snapshot.json +3881 -0
  64. package/dist/migrations/postgres/meta/0040_snapshot.json +3931 -0
  65. package/dist/migrations/postgres/meta/0041_snapshot.json +3981 -0
  66. package/dist/migrations/postgres/meta/0042_snapshot.json +3981 -0
  67. package/dist/migrations/postgres/meta/0043_snapshot.json +3981 -0
  68. package/dist/migrations/postgres/meta/0044_snapshot.json +3991 -0
  69. package/dist/migrations/postgres/meta/0045_snapshot.json +3997 -0
  70. package/dist/migrations/postgres/meta/0046_snapshot.json +3997 -0
  71. package/dist/migrations/postgres/meta/0047_snapshot.json +4234 -0
  72. package/dist/migrations/postgres/meta/_journal.json +182 -0
  73. package/dist/migrations/sqlite/0018_log_015.sql +84 -0
  74. package/dist/migrations/sqlite/0019_retention.sql +2 -0
  75. package/dist/migrations/sqlite/0020_ended_references.sql +1 -0
  76. package/dist/migrations/sqlite/0021_secrets_live_index.sql +1 -0
  77. package/dist/migrations/sqlite/0022_binding_origin.sql +1 -0
  78. package/dist/migrations/sqlite/0023_sign_in_index.sql +2 -0
  79. package/dist/migrations/sqlite/0024_issue_revoke_index.sql +2 -0
  80. package/dist/migrations/sqlite/0025_way_in_uses.sql +42 -0
  81. package/dist/migrations/sqlite/0026_cutover_finish.sql +11 -0
  82. package/dist/migrations/sqlite/0027_reads.sql +38 -0
  83. package/dist/migrations/sqlite/meta/0018_snapshot.json +3529 -0
  84. package/dist/migrations/sqlite/meta/0019_snapshot.json +3538 -0
  85. package/dist/migrations/sqlite/meta/0020_snapshot.json +3545 -0
  86. package/dist/migrations/sqlite/meta/0021_snapshot.json +3553 -0
  87. package/dist/migrations/sqlite/meta/0022_snapshot.json +3560 -0
  88. package/dist/migrations/sqlite/meta/0023_snapshot.json +3579 -0
  89. package/dist/migrations/sqlite/meta/0024_snapshot.json +3598 -0
  90. package/dist/migrations/sqlite/meta/0025_snapshot.json +3609 -0
  91. package/dist/migrations/sqlite/meta/0026_snapshot.json +3616 -0
  92. package/dist/migrations/sqlite/meta/0027_snapshot.json +3834 -0
  93. package/dist/migrations/sqlite/meta/_journal.json +70 -0
  94. package/dist/platform-Y3gICK6n.d.ts +58 -0
  95. package/dist/portable.d.ts +2 -2
  96. package/dist/postgres-BI3xTnyw.js +1718 -0
  97. package/dist/postgres-platform-node.d.ts +14 -0
  98. package/dist/postgres-platform-node.js +21 -0
  99. package/dist/postgres-platform-workerd.d.ts +61 -0
  100. package/dist/postgres-platform-workerd.js +163 -0
  101. package/dist/{schema-BfQEBqFv.d.ts → schema-DgoPqqsI.d.ts} +1326 -7
  102. package/dist/schema-sqlite.d.ts +1306 -6
  103. package/dist/schema-sqlite.js +154 -18
  104. package/dist/schema-version.d.ts +1 -1
  105. package/dist/schema-version.js +254 -2
  106. package/dist/schema.d.ts +2 -2
  107. package/dist/schema.js +226 -20
  108. package/package.json +13 -5
  109. package/src/active-subject.ts +9 -0
  110. package/src/change-records.ts +38 -0
  111. package/src/connect.ts +67 -13
  112. package/src/database.ts +67 -51
  113. package/src/dialect.ts +17 -8
  114. package/src/grants.ts +3 -3
  115. package/src/hyperdrive.ts +181 -104
  116. package/src/log.ts +196 -15
  117. package/src/migrate.ts +157 -30
  118. package/src/migrations/postgres/0022_log_015.sql +672 -0
  119. package/src/migrations/postgres/0023_change_path.sql +153 -0
  120. package/src/migrations/postgres/0024_use_015.sql +556 -0
  121. package/src/migrations/postgres/0025_app_change.sql +221 -0
  122. package/src/migrations/postgres/0026_issue_lock.sql +106 -0
  123. package/src/migrations/postgres/0027_retention.sql +118 -0
  124. package/src/migrations/postgres/0028_use_stalls.sql +594 -0
  125. package/src/migrations/postgres/0029_use_objects.sql +887 -0
  126. package/src/migrations/postgres/0030_unarchive_restores.sql +259 -0
  127. package/src/migrations/postgres/0031_app_read.sql +65 -0
  128. package/src/migrations/postgres/0032_secrets_live_index.sql +4 -0
  129. package/src/migrations/postgres/0033_use_generations.sql +582 -0
  130. package/src/migrations/postgres/0034_vault_credentials.sql +153 -0
  131. package/src/migrations/postgres/0035_first_days.sql +3 -0
  132. package/src/migrations/postgres/0036_vault_issues.sql +91 -0
  133. package/src/migrations/postgres/0037_vault_bindings.sql +271 -0
  134. package/src/migrations/postgres/0040_binding_origin.sql +159 -0
  135. package/src/migrations/postgres/0041_cutover.sql +132 -0
  136. package/src/migrations/postgres/0042_sign_in_index.sql +7 -0
  137. package/src/migrations/postgres/0043_issue_revoke_index.sql +4 -0
  138. package/src/migrations/postgres/0044_use_by_name.sql +705 -0
  139. package/src/migrations/postgres/0045_decide_first.sql +878 -0
  140. package/src/migrations/postgres/0046_way_in_uses.sql +1149 -0
  141. package/src/migrations/postgres/0047_cutover_finish.sql +268 -0
  142. package/src/migrations/postgres/0048_use_batch.sql +59 -0
  143. package/src/migrations/postgres/0049_reads.sql +171 -0
  144. package/src/migrations/postgres/meta/0022_snapshot.json +3831 -0
  145. package/src/migrations/postgres/meta/0023_snapshot.json +3831 -0
  146. package/src/migrations/postgres/meta/0024_snapshot.json +3831 -0
  147. package/src/migrations/postgres/meta/0025_snapshot.json +3831 -0
  148. package/src/migrations/postgres/meta/0026_snapshot.json +3831 -0
  149. package/src/migrations/postgres/meta/0027_snapshot.json +3853 -0
  150. package/src/migrations/postgres/meta/0028_snapshot.json +3853 -0
  151. package/src/migrations/postgres/meta/0029_snapshot.json +3859 -0
  152. package/src/migrations/postgres/meta/0030_snapshot.json +3859 -0
  153. package/src/migrations/postgres/meta/0031_snapshot.json +3859 -0
  154. package/src/migrations/postgres/meta/0032_snapshot.json +3875 -0
  155. package/src/migrations/postgres/meta/0033_snapshot.json +3875 -0
  156. package/src/migrations/postgres/meta/0034_snapshot.json +3875 -0
  157. package/src/migrations/postgres/meta/0035_snapshot.json +3875 -0
  158. package/src/migrations/postgres/meta/0036_snapshot.json +3875 -0
  159. package/src/migrations/postgres/meta/0037_snapshot.json +3875 -0
  160. package/src/migrations/postgres/meta/0038_snapshot.json +3881 -0
  161. package/src/migrations/postgres/meta/0039_snapshot.json +3881 -0
  162. package/src/migrations/postgres/meta/0040_snapshot.json +3931 -0
  163. package/src/migrations/postgres/meta/0041_snapshot.json +3981 -0
  164. package/src/migrations/postgres/meta/0042_snapshot.json +3981 -0
  165. package/src/migrations/postgres/meta/0043_snapshot.json +3981 -0
  166. package/src/migrations/postgres/meta/0044_snapshot.json +3991 -0
  167. package/src/migrations/postgres/meta/0045_snapshot.json +3997 -0
  168. package/src/migrations/postgres/meta/0046_snapshot.json +3997 -0
  169. package/src/migrations/postgres/meta/0047_snapshot.json +4234 -0
  170. package/src/migrations/postgres/meta/_journal.json +182 -0
  171. package/src/migrations/sqlite/0018_log_015.sql +84 -0
  172. package/src/migrations/sqlite/0019_retention.sql +2 -0
  173. package/src/migrations/sqlite/0020_ended_references.sql +1 -0
  174. package/src/migrations/sqlite/0021_secrets_live_index.sql +1 -0
  175. package/src/migrations/sqlite/0022_binding_origin.sql +1 -0
  176. package/src/migrations/sqlite/0023_sign_in_index.sql +2 -0
  177. package/src/migrations/sqlite/0024_issue_revoke_index.sql +2 -0
  178. package/src/migrations/sqlite/0025_way_in_uses.sql +42 -0
  179. package/src/migrations/sqlite/0026_cutover_finish.sql +11 -0
  180. package/src/migrations/sqlite/0027_reads.sql +38 -0
  181. package/src/migrations/sqlite/meta/0018_snapshot.json +3529 -0
  182. package/src/migrations/sqlite/meta/0019_snapshot.json +3538 -0
  183. package/src/migrations/sqlite/meta/0020_snapshot.json +3545 -0
  184. package/src/migrations/sqlite/meta/0021_snapshot.json +3553 -0
  185. package/src/migrations/sqlite/meta/0022_snapshot.json +3560 -0
  186. package/src/migrations/sqlite/meta/0023_snapshot.json +3579 -0
  187. package/src/migrations/sqlite/meta/0024_snapshot.json +3598 -0
  188. package/src/migrations/sqlite/meta/0025_snapshot.json +3609 -0
  189. package/src/migrations/sqlite/meta/0026_snapshot.json +3616 -0
  190. package/src/migrations/sqlite/meta/0027_snapshot.json +3834 -0
  191. package/src/migrations/sqlite/meta/_journal.json +70 -0
  192. package/src/postgres-js/README.md +183 -0
  193. package/src/postgres-js/UNLICENSE +24 -0
  194. package/src/postgres-js/bytes.ts +89 -0
  195. package/src/postgres-js/connection.ts +882 -0
  196. package/src/postgres-js/errors.ts +84 -0
  197. package/src/postgres-js/index.ts +516 -0
  198. package/src/postgres-js/platform.node.ts +29 -0
  199. package/src/postgres-js/platform.ts +60 -0
  200. package/src/postgres-js/platform.workerd.ts +225 -0
  201. package/src/postgres-js/query.ts +123 -0
  202. package/src/postgres-js/queue.ts +42 -0
  203. package/src/postgres-js/result.ts +46 -0
  204. package/src/postgres-js/types.ts +52 -0
  205. package/src/postgres.ts +375 -26
  206. package/src/schema-version.ts +2 -2
  207. package/src/schema.sqlite.ts +198 -7
  208. package/src/schema.ts +291 -6
  209. package/src/verify-runtime.ts +18 -29
  210. package/LICENSE +0 -21
  211. package/dist/database-wq1AVRAP.d.ts +0 -73
  212. package/dist/postgres-Bmar8y0q.js +0 -29
  213. package/dist/relations-BfR3JjT1.js +0 -38
  214. package/src/relations.ts +0 -40
@@ -0,0 +1,1718 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { isIP } from "node:net";
3
+ import { checkServerIdentity } from "node:tls";
4
+ import { Buffer as Buffer$1 } from "node:buffer";
5
+ import * as platform from "#postgres/platform";
6
+ //#region src/postgres-js/bytes.ts
7
+ const SIZE = 256;
8
+ /**
9
+ * The message being written: started with its type (`b.typed('Q')`), or
10
+ * none (`b.untyped()`, for the startup's and the SSLRequest's), then its
11
+ * fields, then `end()`, which writes its length and hands it over. One at a
12
+ * time, each written whole before the next starts.
13
+ */
14
+ var Writer = class {
15
+ #buffer = Buffer$1.allocUnsafe(SIZE);
16
+ /** Where the next field goes. */
17
+ i = 0;
18
+ /** A message of `type`, a letter: its length, written by `end()`, follows it. */
19
+ typed(type) {
20
+ this.#buffer[0] = type.charCodeAt(0);
21
+ this.i = 5;
22
+ return this;
23
+ }
24
+ untyped() {
25
+ this.i = 0;
26
+ return this;
27
+ }
28
+ /** Skip `n` bytes, to be written later (`i32(x, at)`). */
29
+ inc(n) {
30
+ this.i += n;
31
+ return this;
32
+ }
33
+ str(x) {
34
+ const length = Buffer$1.byteLength(x);
35
+ this.#fit(length);
36
+ this.i += this.#buffer.write(x, this.i, length, "utf8");
37
+ return this;
38
+ }
39
+ i16(x) {
40
+ this.#fit(2);
41
+ this.#buffer.writeUInt16BE(x, this.i);
42
+ this.i += 2;
43
+ return this;
44
+ }
45
+ /** `x` next, or at `at`, a place skipped before. */
46
+ i32(x, at) {
47
+ if (at !== void 0) {
48
+ this.#buffer.writeUInt32BE(x, at);
49
+ return this;
50
+ }
51
+ this.#fit(4);
52
+ this.#buffer.writeUInt32BE(x, this.i);
53
+ this.i += 4;
54
+ return this;
55
+ }
56
+ /** `n` zero bytes. */
57
+ z(n) {
58
+ this.#fit(n);
59
+ this.#buffer.fill(0, this.i, this.i + n);
60
+ this.i += n;
61
+ return this;
62
+ }
63
+ /** The message, its length written at `at`: 1 after a type, 0 for an untyped one. */
64
+ end(at = 1) {
65
+ this.#buffer.writeUInt32BE(this.i - at, at);
66
+ const out = this.#buffer.subarray(0, this.i);
67
+ this.i = 0;
68
+ this.#buffer = Buffer$1.allocUnsafe(SIZE);
69
+ return out;
70
+ }
71
+ #fit(n) {
72
+ if (this.#buffer.length - this.i < n) {
73
+ const prev = this.#buffer;
74
+ this.#buffer = Buffer$1.allocUnsafe(prev.length + (prev.length >> 1) + n);
75
+ prev.copy(this.#buffer);
76
+ }
77
+ }
78
+ };
79
+ const b = new Writer();
80
+ //#endregion
81
+ //#region src/postgres-js/errors.ts
82
+ /** An ErrorResponse's fields, by their code. `data type_name` is upstream's spelling, kept. */
83
+ const FIELDS = {
84
+ 83: "severity_local",
85
+ 86: "severity",
86
+ 67: "code",
87
+ 77: "message",
88
+ 68: "detail",
89
+ 72: "hint",
90
+ 80: "position",
91
+ 112: "internal_position",
92
+ 113: "internal_query",
93
+ 87: "where",
94
+ 115: "schema_name",
95
+ 116: "table_name",
96
+ 99: "column_name",
97
+ 100: "data type_name",
98
+ 110: "constraint_name",
99
+ 70: "file",
100
+ 76: "line",
101
+ 82: "routine"
102
+ };
103
+ /** An error Postgres answered, with its fields: `code` (the SQLSTATE), `detail`, `constraint_name`… */
104
+ var PostgresError = class extends Error {
105
+ constructor(fields) {
106
+ super(fields.message);
107
+ this.name = this.constructor.name;
108
+ Object.assign(this, fields);
109
+ }
110
+ };
111
+ /** The connection lost, never made or ended (`CONNECTION_CLOSED`, `CONNECT_TIMEOUT`…), naming where it was to. */
112
+ function connection(code, options) {
113
+ const where = options.path ?? options.host + ":" + options.port;
114
+ const error = Object.assign(/* @__PURE__ */ new Error("write " + code + " " + where), {
115
+ code,
116
+ errno: code,
117
+ address: options.path ?? options.host,
118
+ ...options.path ? {} : { port: options.port }
119
+ });
120
+ Error.captureStackTrace(error, connection);
121
+ return error;
122
+ }
123
+ function postgres$1(fields) {
124
+ const error = new PostgresError(fields);
125
+ Error.captureStackTrace(error, postgres$1);
126
+ return error;
127
+ }
128
+ function generic(code, message) {
129
+ const error = Object.assign(/* @__PURE__ */ new Error(code + ": " + message), { code });
130
+ Error.captureStackTrace(error, generic);
131
+ return error;
132
+ }
133
+ function notSupported(name) {
134
+ const error = Object.assign(/* @__PURE__ */ new Error(name + " (B) is not supported"), {
135
+ code: "MESSAGE_NOT_SUPPORTED",
136
+ name
137
+ });
138
+ Error.captureStackTrace(error, notSupported);
139
+ return error;
140
+ }
141
+ //#endregion
142
+ //#region src/postgres-js/queue.ts
143
+ /** A queue that takes from either end, and lets go of what it took. */
144
+ var Queue = class {
145
+ #xs = [];
146
+ #index = 0;
147
+ get length() {
148
+ return this.#xs.length - this.#index;
149
+ }
150
+ push(x) {
151
+ this.#xs.push(x);
152
+ return x;
153
+ }
154
+ remove(x) {
155
+ const index = this.#xs.indexOf(x);
156
+ if (index === -1) return null;
157
+ this.#xs.splice(index, 1);
158
+ return x;
159
+ }
160
+ pop() {
161
+ if (this.#xs.length === this.#index) return void 0;
162
+ const out = this.#xs.pop();
163
+ if (this.#index === this.#xs.length) this.#clear();
164
+ return out;
165
+ }
166
+ shift() {
167
+ const out = this.#xs[this.#index++];
168
+ if (this.#index === this.#xs.length) this.#clear();
169
+ else this.#xs[this.#index - 1] = void 0;
170
+ return out;
171
+ }
172
+ #clear() {
173
+ this.#index = 0;
174
+ this.#xs = [];
175
+ }
176
+ };
177
+ //#endregion
178
+ //#region src/postgres-js/result.ts
179
+ /**
180
+ * A statement's rows, with what its CommandComplete said beside them: `count`
181
+ * (rows inserted, updated, deleted or returned), `command`, and `state`, the
182
+ * backend that ran it. Not enumerable, so that a result spreads as its rows.
183
+ */
184
+ var Result = class extends Array {
185
+ constructor() {
186
+ super();
187
+ Object.defineProperties(this, {
188
+ count: {
189
+ value: null,
190
+ writable: true
191
+ },
192
+ state: {
193
+ value: null,
194
+ writable: true
195
+ },
196
+ command: {
197
+ value: null,
198
+ writable: true
199
+ },
200
+ columns: {
201
+ value: null,
202
+ writable: true
203
+ },
204
+ statement: {
205
+ value: null,
206
+ writable: true
207
+ }
208
+ });
209
+ }
210
+ /** What `map`, `filter` and the like make: a plain array. */
211
+ static get [Symbol.species]() {
212
+ return Array;
213
+ }
214
+ };
215
+ //#endregion
216
+ //#region src/postgres-js/types.ts
217
+ /**
218
+ * The types read and written by default, as upstream's `types.js`: each one's
219
+ * oid when sent (`to`), the oids read as it (`from`), and how.
220
+ */
221
+ const TYPES = [
222
+ {
223
+ to: 25,
224
+ from: [],
225
+ serialize: (x) => String(x)
226
+ },
227
+ {
228
+ to: 0,
229
+ from: [
230
+ 21,
231
+ 23,
232
+ 26,
233
+ 700,
234
+ 701
235
+ ],
236
+ serialize: (x) => String(x),
237
+ parse: (x) => +x
238
+ },
239
+ {
240
+ to: 114,
241
+ from: [114, 3802],
242
+ serialize: (x) => JSON.stringify(x),
243
+ parse: (x) => JSON.parse(x)
244
+ },
245
+ {
246
+ to: 16,
247
+ from: [16],
248
+ serialize: (x) => x === true ? "t" : "f",
249
+ parse: (x) => x === "t"
250
+ },
251
+ {
252
+ to: 1184,
253
+ from: [
254
+ 1082,
255
+ 1114,
256
+ 1184
257
+ ],
258
+ serialize: (x) => (x instanceof Date ? x : new Date(x)).toISOString(),
259
+ parse: (x) => new Date(x)
260
+ },
261
+ {
262
+ to: 17,
263
+ from: [17],
264
+ serialize: (x) => "\\x" + Buffer$1.from(x).toString("hex"),
265
+ parse: (x) => Buffer$1.from(x.slice(2), "hex")
266
+ }
267
+ ];
268
+ /** A client's own parsers and serializers, made from the defaults: it may change them (`options.parsers[oid] = …`). */
269
+ function defaultTypes() {
270
+ const parsers = {};
271
+ const serializers = {};
272
+ for (const type of TYPES) {
273
+ for (const oid of type.from) parsers[oid] = type.parse;
274
+ serializers[type.to] = type.serialize;
275
+ for (const oid of type.from) serializers[oid] = type.serialize;
276
+ }
277
+ return {
278
+ parsers,
279
+ serializers
280
+ };
281
+ }
282
+ /**
283
+ * The type a value is sent as, which a parameter's serializer goes by: 0,
284
+ * none, for the server to type its text, but for a date, bytes, a boolean or
285
+ * a bigint. An array goes by its first element (porsager/postgres#1225; coffre
286
+ * sends arrays as their text, `asPgSends` in postgres.ts).
287
+ */
288
+ function inferType(x) {
289
+ return x instanceof Date ? 1184 : x instanceof Uint8Array ? 17 : x === true || x === false ? 16 : typeof x === "bigint" ? 20 : Array.isArray(x) ? inferType(x[0]) : 0;
290
+ }
291
+ //#endregion
292
+ //#region src/postgres-js/connection.ts
293
+ const isReservation = (waiting) => "reserve" in waiting;
294
+ let uid = 1;
295
+ const Sync = b.typed("S").end();
296
+ const Flush = b.typed("H").end();
297
+ const SSLRequest = b.untyped().inc(4).i32(80877103).end(0);
298
+ const ExecuteOnly = b.typed("E").str("\0").i32(0).end();
299
+ const ExecuteUnnamed = Buffer$1.concat([ExecuteOnly, Sync]);
300
+ const BindNothing = b.typed("B").str("\0").str("\0").i16(0).i16(0).i16(0).end();
301
+ const DescribeUnnamed = b.typed("D").str("S").str("\0").end();
302
+ const noop = () => {};
303
+ /** A connection, closed, in `queue`, the pool's queue of closed ones. */
304
+ function createConnection(options, queue, { onopen, onend, onclose }) {
305
+ const { sslnegotiation, ssl, max, user, database, parsers, serializers, onnotice, max_pipeline, keep_alive, backoff } = options;
306
+ const sent = new Queue();
307
+ const id = uid++;
308
+ const backend = {
309
+ pid: null,
310
+ secret: null
311
+ };
312
+ const idleTimer = timer(end, options.idle_timeout);
313
+ const lifeTimer = timer(end, options.max_lifetime);
314
+ const connectTimer = timer(connectTimedOut, options.connect_timeout);
315
+ let socket = null;
316
+ let errorResponse = null;
317
+ let result = new Result();
318
+ let results = null;
319
+ let incoming = Buffer$1.alloc(0);
320
+ let incomings = null;
321
+ let closedTime = 0;
322
+ let remaining = 0;
323
+ let length = 0;
324
+ let delay = 0;
325
+ let rows = 0;
326
+ let serverSignature = null;
327
+ let nextWriteTimer = null;
328
+ let terminated = false;
329
+ /** A dial asked for after a close (`reconnect`), not made yet: a forced terminate takes it back. */
330
+ let redial = null;
331
+ let initial = null;
332
+ let ending = null;
333
+ let chunk = null;
334
+ let ended = null;
335
+ let nonce = null;
336
+ /** The statement answering now; those sent after it, pipelined, wait in `sent`. */
337
+ let query = null;
338
+ const connection$1 = {
339
+ queue,
340
+ idleTimer,
341
+ reserved: null,
342
+ onclose: null,
343
+ connect(first) {
344
+ initial = first;
345
+ reconnect();
346
+ },
347
+ terminate,
348
+ execute,
349
+ end,
350
+ release,
351
+ id
352
+ };
353
+ queue.push(connection$1);
354
+ return connection$1;
355
+ async function createSocket() {
356
+ let x;
357
+ try {
358
+ x = options.socket ? await options.socket() : platform.tcp(options.path ? { path: options.path } : {
359
+ host: options.host,
360
+ port: options.port,
361
+ tls: ssl !== false
362
+ }, ssl ? () => void secure().catch(openingFailed) : connected);
363
+ } catch (e) {
364
+ error(e);
365
+ closed(true);
366
+ return null;
367
+ }
368
+ x.on("error", error);
369
+ x.on("close", closed);
370
+ x.on("drain", drain);
371
+ return x;
372
+ }
373
+ function execute(q) {
374
+ if (terminated) {
375
+ queryError(q, connection("CONNECTION_DESTROYED", options));
376
+ return false;
377
+ }
378
+ let message;
379
+ try {
380
+ build(q);
381
+ message = toBuffer(q);
382
+ if (typeof options.debug === "function") {
383
+ if (q.begin !== null) options.debug(id, q.begin, [], []);
384
+ for (const member of q.group ?? [q]) options.debug(id, member.text, member.args, member.statement.types);
385
+ }
386
+ } catch (e) {
387
+ queryError(q, e);
388
+ if (query === null) {
389
+ query = q;
390
+ write(Sync);
391
+ }
392
+ return true;
393
+ }
394
+ if (query) sent.push(q);
395
+ else query = q;
396
+ return write(message) && !q.describeFirst && q.begin === null && sent.length < max_pipeline;
397
+ }
398
+ function toBuffer(q) {
399
+ if (q.parameters.length >= 65534) throw generic("MAX_PARAMETERS_EXCEEDED", "Max number of parameters (65534) exceeded");
400
+ if (q.options.simple) return b.typed("Q").str((q.begin === null ? "" : q.begin + ";\n") + q.statement.string + "\0").end();
401
+ if (q.group !== null) return Buffer$1.concat([...q.group.flatMap((member) => [
402
+ Parse(member),
403
+ DescribeUnnamed,
404
+ Bind(member.parameters, member.statement.types),
405
+ ExecuteOnly
406
+ ]), Sync]);
407
+ const statement = q.describeFirst ? [
408
+ Parse(q),
409
+ DescribeUnnamed,
410
+ Flush
411
+ ] : [
412
+ Parse(q),
413
+ DescribeUnnamed,
414
+ bound(q)
415
+ ];
416
+ return Buffer$1.concat(q.begin === null ? statement : [
417
+ b.typed("P").str("\0").str(q.begin + "\0").i16(0).end(),
418
+ BindNothing,
419
+ ExecuteOnly,
420
+ ...statement
421
+ ]);
422
+ }
423
+ /** The statement's values, bound, and its execution: what follows its Parse once the values can be written. */
424
+ function bound(q) {
425
+ return Buffer$1.concat([Bind(q.parameters, q.statement.types), ExecuteUnnamed]);
426
+ }
427
+ function build(q) {
428
+ if (q.group !== null) {
429
+ for (const [index, member] of q.group.entries()) {
430
+ q.member = index;
431
+ built(member);
432
+ q.parameters = member.parameters;
433
+ if (member.parameters.length >= 65534) throw generic("MAX_PARAMETERS_EXCEEDED", "Max number of parameters (65534) exceeded");
434
+ if (typedByServer(member.parameters, member.statement.types)) throw generic("GROUP_UNTYPED", "A statement of a group has a value whose type only the server can say");
435
+ }
436
+ return startMember(q, 0);
437
+ }
438
+ built(q);
439
+ q.describeFirst = q.parameters.length > 0 && typedByServer(q.parameters, q.statement.types);
440
+ }
441
+ /** A statement's values as sent, and their types as the client knows them (0 for the server to say). */
442
+ function built(statement) {
443
+ const parameters = [];
444
+ const types = [];
445
+ for (const x of statement.args) {
446
+ if (x === void 0) throw generic("UNDEFINED_VALUE", "Undefined values are not allowed");
447
+ parameters.push(x);
448
+ types.push(inferType(x));
449
+ }
450
+ statement.parameters = parameters;
451
+ statement.statement = {
452
+ string: statement.text,
453
+ types,
454
+ columns: null
455
+ };
456
+ }
457
+ /** A group's statement `index`, the one answering from now: its rows are read as it describes them. */
458
+ function startMember(q, index) {
459
+ const member = q.group[index];
460
+ q.member = index;
461
+ q.statement = member.statement;
462
+ q.arrays = member.arrays;
463
+ q.parameters = member.parameters;
464
+ }
465
+ function write(x) {
466
+ chunk = chunk ? Buffer$1.concat([chunk, x]) : Buffer$1.from(x);
467
+ if (chunk.length >= 1024) return nextWrite();
468
+ if (nextWriteTimer === null) nextWriteTimer = platform.setImmediate(nextWrite);
469
+ return true;
470
+ }
471
+ function nextWrite() {
472
+ const x = socket.write(chunk);
473
+ if (nextWriteTimer !== null) platform.clearImmediate(nextWriteTimer);
474
+ chunk = nextWriteTimer = null;
475
+ return x;
476
+ }
477
+ function connectTimedOut() {
478
+ errored(connection("CONNECT_TIMEOUT", options));
479
+ socket.destroy();
480
+ }
481
+ async function secure() {
482
+ if (sslnegotiation !== "direct") {
483
+ const at = socket;
484
+ write(SSLRequest);
485
+ await new Promise((resolve) => at.once("data", () => resolve()));
486
+ if (socket !== at) return;
487
+ }
488
+ const tls = { servername: options.socket || options.path || platform.isIP(options.host) ? void 0 : options.host };
489
+ if (sslnegotiation === "direct") tls.ALPNProtocols = ["postgresql"];
490
+ if (ssl) Object.assign(tls, ssl);
491
+ const plain = socket;
492
+ plain.removeAllListeners();
493
+ try {
494
+ socket = platform.startTls(plain, tls);
495
+ } catch (e) {
496
+ plain.on("close", closed);
497
+ throw e;
498
+ }
499
+ socket.on("secureConnect", connected);
500
+ socket.on("error", error);
501
+ socket.on("close", closed);
502
+ socket.on("drain", drain);
503
+ }
504
+ function drain() {
505
+ if (!query && !connection$1.reserved) onopen(connection$1);
506
+ }
507
+ function data(x) {
508
+ if (incomings) {
509
+ incomings.push(x);
510
+ remaining -= x.length;
511
+ if (remaining > 0) return;
512
+ }
513
+ incoming = incomings ? Buffer$1.concat(incomings, length - remaining) : incoming.length === 0 ? x : Buffer$1.concat([incoming, x], incoming.length + x.length);
514
+ while (incoming.length > 4) {
515
+ length = incoming.readUInt32BE(1);
516
+ if (length >= incoming.length) {
517
+ remaining = length - incoming.length;
518
+ incomings = [incoming];
519
+ break;
520
+ }
521
+ try {
522
+ handle(incoming.subarray(0, length + 1));
523
+ } catch (e) {
524
+ if (query?.describeFirst) write(Sync);
525
+ errored(e);
526
+ }
527
+ incoming = incoming.subarray(length + 1);
528
+ remaining = 0;
529
+ incomings = null;
530
+ }
531
+ }
532
+ async function connect() {
533
+ terminated = false;
534
+ socket ??= await createSocket();
535
+ if (!socket) return;
536
+ connectTimer.start();
537
+ if (options.socket) return ssl ? secure().catch(openingFailed) : connected();
538
+ }
539
+ function reconnect() {
540
+ redial = setTimeout(() => {
541
+ redial = null;
542
+ connect();
543
+ }, closedTime ? Math.max(0, closedTime + delay - platform.now()) : 0);
544
+ }
545
+ function connected() {
546
+ try {
547
+ lifeTimer.start();
548
+ socket.on("data", data);
549
+ if (keep_alive) socket.setKeepAlive?.(true, 1e3 * keep_alive);
550
+ write(StartupMessage());
551
+ } catch (err) {
552
+ openingFailed(err);
553
+ }
554
+ }
555
+ function error(err) {
556
+ errored(err);
557
+ while (sent.length) queryError(sent.shift(), err);
558
+ }
559
+ function errored(err) {
560
+ if (query) queryError(query, err);
561
+ if (initial) {
562
+ queryError(initial, err);
563
+ initial = null;
564
+ }
565
+ }
566
+ function queryError(q, err) {
567
+ if (isReservation(q)) return q.reject(err);
568
+ const e = err && typeof err === "object" ? err : new Error(String(err));
569
+ let begin = false;
570
+ if (q.begin !== null && e instanceof PostgresError) {
571
+ const prefix = q.begin.length + 2;
572
+ const inStatement = q.options.simple && e.position !== void 0 && Number(e.position) > prefix;
573
+ if (inStatement) Object.defineProperty(e, "position", {
574
+ value: String(Number(e.position) - prefix),
575
+ enumerable: true
576
+ });
577
+ begin = !q.began && !inStatement;
578
+ }
579
+ if (!("query" in e) && !("parameters" in e)) {
580
+ const debug = Boolean(options.debug);
581
+ Object.defineProperties(e, {
582
+ stack: {
583
+ value: ("stack" in e ? String(e.stack) : "") + q.origin.replace(/.*\n/, "\n"),
584
+ enumerable: debug
585
+ },
586
+ query: {
587
+ value: begin ? q.begin : q.group === null ? q.text : q.group[q.member].text,
588
+ enumerable: debug
589
+ },
590
+ parameters: {
591
+ value: begin ? [] : q.parameters,
592
+ enumerable: debug
593
+ },
594
+ args: {
595
+ value: q.group === null ? q.args : q.group[q.member].args,
596
+ enumerable: debug
597
+ },
598
+ types: {
599
+ value: q.statement?.types,
600
+ enumerable: debug
601
+ }
602
+ });
603
+ }
604
+ q.reject(e);
605
+ }
606
+ function end() {
607
+ if (ending) return ending;
608
+ if (!connection$1.reserved) onend(connection$1);
609
+ if (!connection$1.reserved && !initial && !query && sent.length === 0) {
610
+ terminate();
611
+ return new Promise((resolve) => socket && socket.readyState !== "closed" ? socket.once("close", () => resolve()) : resolve());
612
+ }
613
+ return ending = new Promise((resolve) => ended = resolve);
614
+ }
615
+ function release() {
616
+ connection$1.reserved = null;
617
+ if (ending) terminate();
618
+ else onopen(connection$1);
619
+ }
620
+ function terminate(force = false) {
621
+ terminated = true;
622
+ if (query || initial || sent.length) error(connection("CONNECTION_DESTROYED", options));
623
+ platform.clearImmediate(nextWriteTimer);
624
+ if (socket) {
625
+ socket.removeListener("data", data);
626
+ socket.removeListener("connect", connected);
627
+ if (socket.readyState === "open" && !force) socket.end(b.typed("X").end());
628
+ else socket.destroy();
629
+ }
630
+ if (force && redial !== null) {
631
+ clearTimeout(redial);
632
+ redial = null;
633
+ }
634
+ if (ended) {
635
+ ended();
636
+ ending = ended = null;
637
+ }
638
+ }
639
+ async function closed(hadError) {
640
+ incoming = Buffer$1.alloc(0);
641
+ remaining = 0;
642
+ incomings = null;
643
+ platform.clearImmediate(nextWriteTimer);
644
+ idleTimer.cancel();
645
+ lifeTimer.cancel();
646
+ connectTimer.cancel();
647
+ socket?.removeAllListeners();
648
+ socket = null;
649
+ if (initial) errored(connection("CONNECTION_CLOSED", options));
650
+ if (!hadError && (query || sent.length)) error(connection("CONNECTION_CLOSED", options));
651
+ query = null;
652
+ errorResponse = null;
653
+ rows = 0;
654
+ result = new Result();
655
+ results = null;
656
+ chunk = null;
657
+ nextWriteTimer = null;
658
+ if (ended) {
659
+ ended();
660
+ ending = ended = null;
661
+ }
662
+ closedTime = platform.now();
663
+ if (hadError) options.shared.retries++;
664
+ delay = (typeof backoff === "function" ? backoff(options.shared.retries) : backoff) * 1e3;
665
+ onclose(connection$1, connection("CONNECTION_CLOSED", options));
666
+ }
667
+ function handle(x) {
668
+ switch (x[0]) {
669
+ case 68: return DataRow(x);
670
+ case 83: return ParameterStatus(x);
671
+ case 90: return ReadyForQuery(x);
672
+ case 67: return CommandComplete(x);
673
+ case 50: return BindComplete();
674
+ case 49: return;
675
+ case 116: return ParameterDescription(x);
676
+ case 84: return RowDescription(x);
677
+ case 82: return authenticate(x);
678
+ case 110: return NoData();
679
+ case 75: return BackendKeyData(x);
680
+ case 69: return ErrorResponse(x);
681
+ case 78: return NoticeResponse(x);
682
+ case 73: return;
683
+ case 65: return;
684
+ case 71: return CopyInResponse();
685
+ case 72:
686
+ case 87: return CopyOutResponse();
687
+ case 100: return;
688
+ case 99: return;
689
+ case 86: return errored(notSupported("FunctionCallResponse"));
690
+ case 118: return errored(notSupported("NegotiateProtocolVersion"));
691
+ default: console.error("Postgres.js : Unknown Message:", x[0]);
692
+ }
693
+ }
694
+ function DataRow(x) {
695
+ const q = query;
696
+ const columns = q.statement.columns;
697
+ let index = 7;
698
+ const row = q.arrays ? new Array(columns.length) : {};
699
+ for (let i = 0; i < columns.length; i++) {
700
+ const column = columns[i];
701
+ const length = x.readInt32BE(index);
702
+ index += 4;
703
+ const value = length === -1 ? null : column.parser === void 0 ? x.toString("utf8", index, index += length) : column.parser(x.toString("utf8", index, index += length));
704
+ if (Array.isArray(row)) row[i] = value;
705
+ else row[column.name] = value;
706
+ }
707
+ result[rows++] = row;
708
+ }
709
+ function ParameterStatus(x) {
710
+ const [k, v] = x.toString("utf8", 5, x.length - 1).split("\0");
711
+ options.parameters[k] = v;
712
+ }
713
+ function ReadyForQuery(x) {
714
+ if (query) {
715
+ if (errorResponse) errored(errorResponse);
716
+ else query.resolve(results || result);
717
+ } else if (errorResponse) errored(errorResponse);
718
+ query = results = errorResponse = null;
719
+ result = new Result();
720
+ connectTimer.cancel();
721
+ if (initial) {
722
+ if (!isReservation(initial)) execute(initial);
723
+ options.shared.retries = 0;
724
+ const opened = initial;
725
+ initial = null;
726
+ if (opened !== null && isReservation(opened)) opened.reserve(connection$1);
727
+ return;
728
+ }
729
+ if (sent.length) query = sent.shift();
730
+ if (query) return;
731
+ if (connection$1.reserved) connection$1.reserved.next();
732
+ else if (ending) terminate();
733
+ else onopen(connection$1);
734
+ }
735
+ function CommandComplete(x) {
736
+ if (query.begin !== null && !query.began) {
737
+ query.began = true;
738
+ return;
739
+ }
740
+ rows = 0;
741
+ for (let i = x.length - 1; i > 0; i--) {
742
+ if (x[i] === 32 && (x[i + 1] ?? 58) < 58 && result.count === null) result.count = +x.toString("utf8", i + 1, x.length - 1);
743
+ if (x[i - 1] >= 65) {
744
+ result.command = x.toString("utf8", 5, i);
745
+ result.state = backend;
746
+ break;
747
+ }
748
+ }
749
+ if (result.command === "BEGIN" && max !== 1 && !connection$1.reserved) return errored(generic("UNSAFE_TRANSACTION", "Only use sql.begin, sql.reserved or max: 1"));
750
+ const q = query;
751
+ if (q.group !== null) {
752
+ results ??= [result];
753
+ if (q.member + 1 < q.group.length) {
754
+ results.push(result = new Result());
755
+ startMember(q, q.member + 1);
756
+ }
757
+ return;
758
+ }
759
+ if (query.options.simple) return BindComplete();
760
+ }
761
+ function BindComplete() {
762
+ if (!result.statement) result.statement = query.statement;
763
+ result.columns = query.statement.columns;
764
+ }
765
+ function ParameterDescription(x) {
766
+ const q = query;
767
+ const types = q.statement.types;
768
+ const length = x.readUInt16BE(5);
769
+ for (let i = 0; i < length; ++i) if (!types[i]) types[i] = x.readUInt32BE(7 + i * 4);
770
+ if (q.describeFirst) {
771
+ write(bound(q));
772
+ q.describeFirst = false;
773
+ }
774
+ }
775
+ function RowDescription(x) {
776
+ const statement = query.statement;
777
+ if (result.command) {
778
+ results = results || [result];
779
+ results.push(result = new Result());
780
+ result.count = null;
781
+ statement.columns = null;
782
+ }
783
+ const length = x.readUInt16BE(5);
784
+ let index = 7;
785
+ let start;
786
+ const columns = statement.columns = Array(length);
787
+ for (let i = 0; i < length; ++i) {
788
+ start = index;
789
+ while (x[index++] !== 0);
790
+ columns[i] = {
791
+ name: x.toString("utf8", start, index - 1),
792
+ parser: parsers[x.readUInt32BE(index + 6)],
793
+ table: x.readUInt32BE(index),
794
+ number: x.readUInt16BE(index + 4),
795
+ type: x.readUInt32BE(index + 6)
796
+ };
797
+ index += 18;
798
+ }
799
+ result.statement = statement;
800
+ }
801
+ function authenticate(x) {
802
+ const at = socket;
803
+ Authentication(x, at).catch((err) => {
804
+ if (socket === at) openingFailed(err);
805
+ });
806
+ }
807
+ async function Authentication(x, at) {
808
+ const type = x.readUInt32BE(5);
809
+ switch (type) {
810
+ case 0: return;
811
+ case 3: return AuthenticationCleartextPassword();
812
+ case 5: return AuthenticationMD5Password(x, at);
813
+ case 10: return SASL();
814
+ case 11: return SASLContinue(x, at);
815
+ case 12: return SASLFinal(x);
816
+ default: throw generic("AUTH_TYPE_NOT_SUPPORTED", `Postgres asked for an authentication the client has not: type ${type}`);
817
+ }
818
+ }
819
+ function openingFailed(err) {
820
+ errored(err);
821
+ socket?.destroy();
822
+ }
823
+ function AuthenticationCleartextPassword() {
824
+ write(b.typed("p").str(options.pass).z(1).end());
825
+ }
826
+ async function AuthenticationMD5Password(x, at) {
827
+ const payload = "md5" + await platform.md5(Buffer$1.concat([Buffer$1.from(await platform.md5(options.pass + user)), x.subarray(9)]));
828
+ if (socket !== at) return;
829
+ write(b.typed("p").str(payload).z(1).end());
830
+ }
831
+ function SASL() {
832
+ nonce = platform.randomBytes(18).toString("base64");
833
+ b.typed("p").str("SCRAM-SHA-256\0");
834
+ const i = b.i;
835
+ write(b.inc(4).str("n,,n=*,r=" + nonce).i32(b.i - i - 4, i).end());
836
+ }
837
+ async function SASLContinue(x, at) {
838
+ const res = {};
839
+ for (const part of x.toString("utf8", 9).split(",")) res[part[0]] = part.slice(2);
840
+ const saltedPassword = await platform.pbkdf2(options.pass, Buffer$1.from(res.s, "base64"), parseInt(res.i), 32);
841
+ const clientKey = await platform.hmac(saltedPassword, "Client Key");
842
+ const auth = "n=*,r=" + nonce + ",r=" + res.r + ",s=" + res.s + ",i=" + res.i + ",c=biws,r=" + res.r;
843
+ const signature = (await platform.hmac(await platform.hmac(saltedPassword, "Server Key"), auth)).toString("base64");
844
+ const payload = "c=biws,r=" + res.r + ",p=" + xor(clientKey, await platform.hmac(await platform.sha256(clientKey), auth)).toString("base64");
845
+ if (socket !== at) return;
846
+ serverSignature = signature;
847
+ write(b.typed("p").str(payload).end());
848
+ }
849
+ function SASLFinal(x) {
850
+ if (x.toString("utf8", 9).split("\0", 1)[0].slice(2) === serverSignature) return;
851
+ errored(generic("SASL_SIGNATURE_MISMATCH", "The server did not return the correct signature"));
852
+ socket.destroy();
853
+ }
854
+ function NoData() {
855
+ result.statement = query.statement;
856
+ result.statement.columns = [];
857
+ }
858
+ function BackendKeyData(x) {
859
+ backend.pid = x.readUInt32BE(5);
860
+ backend.secret = x.readUInt32BE(9);
861
+ }
862
+ function ErrorResponse(x) {
863
+ if (query) {
864
+ if (query.describeFirst) write(Sync);
865
+ errorResponse = postgres$1(parseError(x));
866
+ } else errored(postgres$1(parseError(x)));
867
+ }
868
+ function CopyInResponse() {
869
+ write(b.typed("f").str("COPY is not supported by this client\0").end());
870
+ if (!query?.options.simple) write(Sync);
871
+ }
872
+ function CopyOutResponse() {
873
+ errorResponse ??= generic("COPY_NOT_SUPPORTED", "COPY is not supported by this client");
874
+ }
875
+ function NoticeResponse(x) {
876
+ if (onnotice) onnotice(parseError(x));
877
+ else console.log(parseError(x));
878
+ }
879
+ function Bind(parameters, types) {
880
+ let prev;
881
+ b.typed("B").str("\0").str("\0").i16(0).i16(parameters.length);
882
+ parameters.forEach((x, i) => {
883
+ if (x === null) return void b.i32(4294967295);
884
+ const type = types[i];
885
+ const serialize = serializers[type];
886
+ parameters[i] = x = serialize ? serialize(x) : String(x);
887
+ prev = b.i;
888
+ b.inc(4).str(x).i32(b.i - prev - 4, prev);
889
+ });
890
+ b.i16(0);
891
+ return b.end();
892
+ }
893
+ function Parse(q) {
894
+ const { string, types } = q.statement;
895
+ b.typed("P").str("\0").str(string + "\0").i16(q.parameters.length);
896
+ q.parameters.forEach((_, i) => b.i32(types[i] || 0));
897
+ return b.end();
898
+ }
899
+ function StartupMessage() {
900
+ return b.untyped().inc(4).i16(3).z(2).str(Object.entries({
901
+ user,
902
+ database,
903
+ client_encoding: "UTF8",
904
+ ...options.connection
905
+ }).filter(([, v]) => v).map(([k, v]) => k + "\0" + String(v)).join("\0")).z(2).end(0);
906
+ }
907
+ }
908
+ function parseError(x) {
909
+ const error = {};
910
+ let start = 5;
911
+ for (let i = 5; i < x.length - 1; i++) if (x[i] === 0) {
912
+ error[FIELDS[x[start]]] = x.toString("utf8", start + 1, i);
913
+ start = i + 1;
914
+ }
915
+ return error;
916
+ }
917
+ function xor(a, b) {
918
+ const length = Math.max(a.length, b.length);
919
+ const buffer = Buffer$1.allocUnsafe(length);
920
+ for (let i = 0; i < length; i++) buffer[i] = a[i] ^ b[i];
921
+ return buffer;
922
+ }
923
+ /** `fn`, `seconds` after each `start` unless cancelled; nothing at all for no seconds. */
924
+ function timer(fn, seconds) {
925
+ const s = typeof seconds === "function" ? seconds() : seconds;
926
+ if (!s) return {
927
+ cancel: noop,
928
+ start: noop
929
+ };
930
+ let handle = null;
931
+ return {
932
+ cancel() {
933
+ if (handle) {
934
+ clearTimeout(handle);
935
+ handle = null;
936
+ }
937
+ },
938
+ start() {
939
+ if (handle) clearTimeout(handle);
940
+ handle = setTimeout(() => {
941
+ fn();
942
+ handle = null;
943
+ }, s * 1e3);
944
+ }
945
+ };
946
+ }
947
+ /**
948
+ * Whether an unnamed statement must learn its parameters' types before it
949
+ * can send them. Strings, numbers and nulls go as text, typed by the server,
950
+ * in the same flush as the statement, as libpq and node-postgres send them;
951
+ * only an array or an object whose type is not known yet has a text that
952
+ * depends on the type. porsager/postgres#1225
953
+ */
954
+ function typedByServer(parameters, types) {
955
+ return parameters.some((x, i) => !types[i] && x !== null && typeof x === "object");
956
+ }
957
+ //#endregion
958
+ //#region src/postgres-js/query.ts
959
+ /**
960
+ * A statement, sent once awaited (`then`, `catch`, `finally`) or `execute`d,
961
+ * a task later, through the pool or the transaction that made it: its
962
+ * `handler`. A promise of its result, its rows as objects or, after
963
+ * `values()`, as arrays.
964
+ */
965
+ var Query = class extends Promise {
966
+ text;
967
+ args;
968
+ options;
969
+ #handler;
970
+ /** Where it was made, when the client debugs. */
971
+ #origin;
972
+ /** Its rows as arrays of values rather than objects. */
973
+ arrays = false;
974
+ executed = false;
975
+ parameters = [];
976
+ statement = null;
977
+ /** Whether its parameters' types are asked of the server before its values go (`typedByServer`, connection.ts). */
978
+ describeFirst = false;
979
+ /** A transaction's first statement: its BEGIN, sent ahead of it under its Sync (`begin`, index.ts); and whether it took. */
980
+ begin = null;
981
+ began = false;
982
+ /**
983
+ * Coffre: a group's statements, sent under one Sync and answered together, each its own result (`group`, index.ts),
984
+ * and the one answering now. Null for a statement of its own.
985
+ */
986
+ group = null;
987
+ member = 0;
988
+ resolve;
989
+ reject;
990
+ constructor(text, args, handler, options, debug) {
991
+ let resolve;
992
+ let reject;
993
+ super((a, b) => {
994
+ resolve = a;
995
+ reject = b;
996
+ });
997
+ this.text = text;
998
+ this.args = args;
999
+ this.options = options;
1000
+ this.#handler = handler;
1001
+ this.#origin = debug ? /* @__PURE__ */ new Error() : null;
1002
+ this.resolve = resolve;
1003
+ this.reject = reject;
1004
+ }
1005
+ /** Where it was made, for its error's stack: nothing unless the client debugs. */
1006
+ get origin() {
1007
+ return this.#origin?.stack ?? "";
1008
+ }
1009
+ /** What `then` and the like make: a plain promise, not another statement. */
1010
+ static get [Symbol.species]() {
1011
+ return Promise;
1012
+ }
1013
+ values() {
1014
+ this.arrays = true;
1015
+ return this;
1016
+ }
1017
+ execute() {
1018
+ this.#handle();
1019
+ return this;
1020
+ }
1021
+ then(onfulfilled, onrejected) {
1022
+ this.#handle();
1023
+ return super.then(onfulfilled, onrejected);
1024
+ }
1025
+ catch(onrejected) {
1026
+ this.#handle();
1027
+ return super.catch(onrejected);
1028
+ }
1029
+ finally(onfinally) {
1030
+ this.#handle();
1031
+ return super.finally(onfinally);
1032
+ }
1033
+ /** Sent once, a task after it is first asked for. */
1034
+ async #handle() {
1035
+ if (this.executed) return;
1036
+ this.executed = true;
1037
+ await null;
1038
+ this.#handler(this);
1039
+ }
1040
+ };
1041
+ //#endregion
1042
+ //#region src/postgres-js/index.ts
1043
+ /**
1044
+ * Coffre: whether a statement is a plain read, what a group may hold (`group`): one that starts `select`. A `select`
1045
+ * that writes through a function says so first, in a comment, which this does not take (`pruneSpentTokens` in
1046
+ * @coffre/server). The extended protocol takes one statement a message, so none rides behind it.
1047
+ */
1048
+ function plainRead(text) {
1049
+ return /^\s*select\b/i.test(text);
1050
+ }
1051
+ /** A pool of connections, opened as statements ask for them. */
1052
+ function postgres(given) {
1053
+ const options = settle(given);
1054
+ let ending = null;
1055
+ const queries = new Queue();
1056
+ const connecting = new Queue();
1057
+ const reserved = new Queue();
1058
+ const closed = new Queue();
1059
+ const ended = new Queue();
1060
+ const open = new Queue();
1061
+ const busy = new Queue();
1062
+ const full = new Queue();
1063
+ const connections = Array.from({ length: options.max }, () => createConnection(options, closed, {
1064
+ onopen,
1065
+ onend,
1066
+ onclose
1067
+ }));
1068
+ return {
1069
+ unsafe: unsafeOn(pooled),
1070
+ group,
1071
+ begin,
1072
+ reserve,
1073
+ end,
1074
+ options
1075
+ };
1076
+ function group(statements) {
1077
+ if (statements.length === 0) throw generic("EMPTY_GROUP", "A group needs a statement");
1078
+ const write = statements.find((statement) => !plainRead(statement.query));
1079
+ if (write !== void 0) throw generic("GROUP_NOT_READ", `A group holds plain reads alone, select …, not: ${write.query.slice(0, 80)}`);
1080
+ const query = new Query(statements.map((statement) => statement.query).join(";\n"), [], pooled, { simple: false }, Boolean(options.debug));
1081
+ query.group = statements.map(({ query: text, parameters = [], arrays = false }) => ({
1082
+ text,
1083
+ args: parameters,
1084
+ arrays,
1085
+ parameters: [],
1086
+ statement: null
1087
+ }));
1088
+ return query;
1089
+ }
1090
+ /** `unsafe`, sending each statement through `handler`. */
1091
+ function unsafeOn(handler) {
1092
+ return (text, args = [], { simple = args.length === 0 } = {}) => new Query(text, args, handler, { simple }, Boolean(options.debug));
1093
+ }
1094
+ /** A connection of the pool's own, held until given back: `reserve`'s, and a transaction's. */
1095
+ async function hold() {
1096
+ if (ending) throw connection("CONNECTION_ENDED", options);
1097
+ return move(open.length ? open.pop() : await new Promise((resolve, reject) => {
1098
+ const query = {
1099
+ reserve: resolve,
1100
+ reject
1101
+ };
1102
+ if (closed.length) connect(closed.shift(), query);
1103
+ else queries.push(query);
1104
+ }), reserved);
1105
+ }
1106
+ async function reserve() {
1107
+ const queue = new Queue();
1108
+ const c = await hold();
1109
+ c.reserved = { next: () => queue.length ? c.execute(queue.shift()) : move(c, reserved) };
1110
+ return {
1111
+ unsafe: unsafeOn(onReserved),
1112
+ release: () => c.release()
1113
+ };
1114
+ /** A statement on the connection held: sent, or queued until the connection can take more. */
1115
+ function onReserved(q) {
1116
+ if (c.queue === full) queue.push(q);
1117
+ else if (!c.execute(q)) move(c, full);
1118
+ }
1119
+ }
1120
+ async function begin(...args) {
1121
+ const [mode, fn] = args.length === 1 ? ["", args[0]] : args;
1122
+ const queries = new Queue();
1123
+ let savepoints = 0;
1124
+ /** The transaction's first statement, which carries its BEGIN (`toBuffer`, connection.ts), once asked. */
1125
+ let first = null;
1126
+ /** Every statement of the transaction's asked: it ends once each has answered. */
1127
+ const asked = /* @__PURE__ */ new Set();
1128
+ /** Its end is decided, COMMIT or ROLLBACK: what its work asks now is refused, unsent. */
1129
+ let decided = false;
1130
+ /** Asked of it once its end was decided, and refused, before its COMMIT went: its work is not all done, it rolls back. */
1131
+ let unfinished = null;
1132
+ /** Its COMMIT or ROLLBACK has gone: what is refused now changes nothing. */
1133
+ let closing = false;
1134
+ /** Why it failed, a savepoint's statements included: what a COMMIT Postgres answered with ROLLBACK says. */
1135
+ let failure;
1136
+ /**
1137
+ * Why nothing more of the transaction is sent, which would run outside it: its BEGIN failed, its connection closed,
1138
+ * or it has ended, and its connection is the pool's again (what its work left running may still ask).
1139
+ */
1140
+ let stopped = null;
1141
+ const stop = (error) => {
1142
+ stopped ??= error;
1143
+ while (queries.length) queries.shift().reject(stopped);
1144
+ };
1145
+ const c = await hold();
1146
+ const mine = { next: () => {
1147
+ if (first !== null && !first.began) {
1148
+ stop(generic("TRANSACTION_NOT_BEGUN", "The transaction did not begin, so its statements were not sent"));
1149
+ move(c, reserved);
1150
+ return;
1151
+ }
1152
+ move(c, reserved);
1153
+ while (queries.length) if (!c.execute(queries.shift())) return void move(c, full);
1154
+ } };
1155
+ c.reserved = mine;
1156
+ try {
1157
+ return await Promise.race([scope(fn), new Promise((_, reject) => c.onclose = (error) => {
1158
+ stop(error);
1159
+ reject(error);
1160
+ })]);
1161
+ } finally {
1162
+ stop(generic("TRANSACTION_ENDED", "The transaction has ended, so the statement was not sent"));
1163
+ c.onclose = null;
1164
+ if (c.reserved === mine) c.release();
1165
+ }
1166
+ async function scope(fn, name) {
1167
+ let uncaughtError;
1168
+ let result;
1169
+ const sql = {
1170
+ unsafe: unsafeOn(inTransaction),
1171
+ savepoint: (fn) => scope(fn, "s" + savepoints++)
1172
+ };
1173
+ const own = (text) => sql.unsafe(text);
1174
+ if (name) await own("savepoint " + quote(name));
1175
+ try {
1176
+ result = await new Promise((resolve, reject) => {
1177
+ const x = fn(sql);
1178
+ Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject);
1179
+ });
1180
+ if (!name) await settle();
1181
+ if (uncaughtError) throw uncaughtError;
1182
+ if (!name && unfinished) throw unfinished;
1183
+ } catch (e) {
1184
+ if (!name) await settle();
1185
+ if (!stopped && (name || first?.began)) await (name ? own("rollback to " + quote(name)) : last("rollback"));
1186
+ if (aborted(e)) throw (uncaughtError !== void 0 && !aborted(uncaughtError) ? uncaughtError : failure) ?? e;
1187
+ throw e;
1188
+ }
1189
+ if (!name && first !== null) {
1190
+ if ((await last("commit")).command === "ROLLBACK") throw failure ?? generic("TRANSACTION_ROLLED_BACK", "Postgres rolled the transaction back at its COMMIT");
1191
+ }
1192
+ return result;
1193
+ /** A statement of the transaction's: one that fails and is not waited for fails the transaction all the same. */
1194
+ function inTransaction(q) {
1195
+ if (decided) {
1196
+ const refused = stopped ?? generic("TRANSACTION_ENDED", "The transaction has ended, so the statement was not sent");
1197
+ if (!closing) unfinished ??= generic("TRANSACTION_UNFINISHED", "The transaction's work asked a statement once it had settled, so the transaction rolled back");
1198
+ q.catch(() => {});
1199
+ return q.reject(refused);
1200
+ }
1201
+ q.catch((e) => {
1202
+ uncaughtError ||= e;
1203
+ if (e instanceof PostgresError && !aborted(e)) failure = e;
1204
+ else failure ??= e;
1205
+ });
1206
+ asked.add(q);
1207
+ send(q);
1208
+ }
1209
+ }
1210
+ /**
1211
+ * Coffre: the end decided, nothing more of the work's is sent, and the transaction ends once what it asked has
1212
+ * answered, with a ROLLBACK if any of it failed. Upstream sent the COMMIT at once: what the work asked after it ran
1213
+ * outside the transaction, in autocommit, and a statement that failed unwaited left a COMMIT that Postgres
1214
+ * answered with ROLLBACK, which upstream took for success.
1215
+ */
1216
+ async function settle() {
1217
+ decided = true;
1218
+ await Promise.allSettled(asked);
1219
+ }
1220
+ /** The transaction's COMMIT or ROLLBACK, past the door that settle closed. */
1221
+ function last(text) {
1222
+ closing = true;
1223
+ return new Query(text, [], send, { simple: true }, Boolean(options.debug));
1224
+ }
1225
+ /** `q` on the transaction's connection: sent, or queued until the connection can take more. */
1226
+ function send(q) {
1227
+ if (stopped) return q.reject(stopped);
1228
+ if (first === null) {
1229
+ first = q;
1230
+ q.begin = "begin " + mode.replace(/[^a-z ]/gi, "");
1231
+ }
1232
+ if (c.queue === full) queries.push(q);
1233
+ else if (!c.execute(q) || q === first) move(c, full);
1234
+ }
1235
+ }
1236
+ function move(c, queue) {
1237
+ c.queue.remove(c);
1238
+ queue.push(c);
1239
+ c.queue = queue;
1240
+ if (queue === open) c.idleTimer.start();
1241
+ else c.idleTimer.cancel();
1242
+ return c;
1243
+ }
1244
+ /** A statement of the pool's: sent on an open connection, one opened for it, a busy one, or queued for the first free. */
1245
+ function pooled(query) {
1246
+ if (ending) return query.reject(connection("CONNECTION_ENDED", options));
1247
+ if (open.length) return void go(open.pop(), query);
1248
+ if (closed.length) return void connect(closed.shift(), query);
1249
+ if (busy.length) go(busy.shift(), query);
1250
+ else queries.push(query);
1251
+ }
1252
+ function go(c, query) {
1253
+ return c.execute(query) ? move(c, busy) : move(c, full);
1254
+ }
1255
+ async function end({ timeout = null } = {}) {
1256
+ if (ending) return ending;
1257
+ await null;
1258
+ let timer;
1259
+ return ending = Promise.race([new Promise((resolve) => {
1260
+ if (timeout !== null) timer = setTimeout(() => void destroy(resolve), timeout * 1e3);
1261
+ }), Promise.all(connections.map((c) => c.end())).then(() => void 0)]).then(() => clearTimeout(timer));
1262
+ }
1263
+ async function destroy(resolve) {
1264
+ await Promise.all(connections.map((c) => c.terminate(true)));
1265
+ while (queries.length) queries.shift().reject(connection("CONNECTION_DESTROYED", options));
1266
+ resolve();
1267
+ }
1268
+ function connect(c, query) {
1269
+ move(c, connecting);
1270
+ c.connect(query);
1271
+ return c;
1272
+ }
1273
+ function onend(c) {
1274
+ move(c, ended);
1275
+ }
1276
+ function onopen(c) {
1277
+ if (queries.length === 0) return void move(c, open);
1278
+ let max = Math.ceil(queries.length / (connecting.length + 1));
1279
+ let ready = true;
1280
+ while (ready && queries.length && max-- > 0) {
1281
+ const query = queries.shift();
1282
+ if ("reserve" in query) return void query.reserve(move(c, reserved));
1283
+ ready = c.execute(query);
1284
+ }
1285
+ if (ready) move(c, busy);
1286
+ else move(c, full);
1287
+ }
1288
+ function onclose(c, e) {
1289
+ move(c, closed);
1290
+ c.reserved = null;
1291
+ if (c.onclose) {
1292
+ c.onclose(e);
1293
+ c.onclose = null;
1294
+ }
1295
+ options.onclose?.(c.id);
1296
+ if (ending) {
1297
+ while (queries.length) queries.shift().reject(connection("CONNECTION_ENDED", options));
1298
+ return;
1299
+ }
1300
+ if (queries.length) connect(c, queries.shift());
1301
+ }
1302
+ }
1303
+ /** Postgres's "current transaction is aborted": a statement after one that failed. */
1304
+ const aborted = (error) => error instanceof PostgresError && error.code === "25P02";
1305
+ /** `options`, each one not given at its default. */
1306
+ function settle(options) {
1307
+ return {
1308
+ host: options.host ?? "localhost",
1309
+ port: options.port ?? 5432,
1310
+ path: options.path,
1311
+ database: options.database,
1312
+ user: options.user ?? "",
1313
+ pass: options.pass ?? "",
1314
+ ssl: options.ssl ?? false,
1315
+ sslnegotiation: options.sslnegotiation,
1316
+ max: options.max ?? 10,
1317
+ max_pipeline: options.max_pipeline ?? 100,
1318
+ idle_timeout: options.idle_timeout,
1319
+ connect_timeout: "connect_timeout" in options ? options.connect_timeout : 30,
1320
+ max_lifetime: "max_lifetime" in options ? options.max_lifetime : () => 60 * (30 + Math.random() * 30),
1321
+ backoff: options.backoff ?? ((retries) => (.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20)),
1322
+ keep_alive: "keep_alive" in options ? options.keep_alive : 60,
1323
+ debug: options.debug ?? false,
1324
+ connection: {
1325
+ application_name: "postgres.js",
1326
+ ...options.connection
1327
+ },
1328
+ onnotice: options.onnotice,
1329
+ onclose: options.onclose,
1330
+ socket: options.socket,
1331
+ ...defaultTypes(),
1332
+ parameters: {},
1333
+ shared: { retries: 0 }
1334
+ };
1335
+ }
1336
+ /** `name` as an identifier, quoted. */
1337
+ function quote(name) {
1338
+ return "\"" + name.replace(/"/g, "\"\"").replace(/\./g, "\".\"") + "\"";
1339
+ }
1340
+ //#endregion
1341
+ //#region src/postgres.ts
1342
+ /**
1343
+ * A client for `url`, as coffre opens every one: the driver's defaults (10
1344
+ * connections, every statement unnamed, as node-postgres sends them), but
1345
+ *
1346
+ * - notices dropped rather than logged;
1347
+ * - no connection closed for its age (`max_lifetime`), as node-postgres
1348
+ * closed none: a backup's session holds its snapshot while pg_dump reads.
1349
+ *
1350
+ * The driver reads no array type from `pg_type` (postgres.js's
1351
+ * `fetch_types`, a round trip more per connection), and would answer one as
1352
+ * its text: Postgres's own are taken as known instead (`ARRAYS`). Arrays and
1353
+ * dates go as node-postgres sends them (`asPgSends`).
1354
+ */
1355
+ function postgresClient(url, options = {}) {
1356
+ const { application_name, connection, ...rest } = options;
1357
+ const target = postgresOptions(url);
1358
+ return asPgSends(arrayTypes(postgres({
1359
+ onnotice: () => {},
1360
+ max_lifetime: null,
1361
+ ...target,
1362
+ ...rest,
1363
+ connection: {
1364
+ ...target.connection,
1365
+ ...application_name === void 0 ? {} : { application_name },
1366
+ ...connection
1367
+ }
1368
+ })));
1369
+ }
1370
+ /** A statement asked of a session that lost its connection, and with it its transaction, its locks and its settings. */
1371
+ var SessionLost = class extends Error {
1372
+ constructor() {
1373
+ super("the database session was lost: its connection closed, and with it its transaction, locks and settings");
1374
+ this.name = "SessionLost";
1375
+ }
1376
+ };
1377
+ /** What is asked of a session: each fails once it is lost. */
1378
+ const ASKED = /* @__PURE__ */ new Set([
1379
+ "unsafe",
1380
+ "begin",
1381
+ "reserve"
1382
+ ]);
1383
+ /**
1384
+ * One connection to `url`, kept as a session, as node-postgres's Client
1385
+ * kept one: what a statement sets (SET, BEGIN, a session's advisory lock)
1386
+ * holds for every statement after. A client of postgres.js would dial a new
1387
+ * connection for the next statement once its own closed, which holds none of
1388
+ * it: a migration going on without its lock, a probe meant to be rolled back
1389
+ * committed, a backup read outside its snapshot. A session does not: once
1390
+ * its connection has closed, by the server, the network or `end`, every
1391
+ * statement after fails, `SessionLost`.
1392
+ */
1393
+ function postgresSession(url, options = {}) {
1394
+ let lost = false;
1395
+ const client = postgresClient(url, {
1396
+ ...options,
1397
+ max: 1,
1398
+ onclose: (id) => (lost = true, options.onclose?.(id))
1399
+ });
1400
+ /** A statement refused: rejected, and still a statement, whose `values()` and `execute()` Drizzle and callers ask for. */
1401
+ const refused = () => {
1402
+ const answer = Promise.reject(new SessionLost());
1403
+ answer.catch(() => {});
1404
+ return Object.assign(answer, {
1405
+ values: () => answer,
1406
+ execute: () => answer
1407
+ });
1408
+ };
1409
+ return new Proxy(client, { get(target, key) {
1410
+ const value = Reflect.get(target, key, target);
1411
+ if (typeof value !== "function" || !ASKED.has(key)) return value;
1412
+ return (...args) => lost ? refused() : value.apply(target, args);
1413
+ } });
1414
+ }
1415
+ /**
1416
+ * `client`, sending a statement's values as node-postgres sends them: an
1417
+ * array as Postgres's text for one (`{"a","b"}`, bytes as `\\x…`), a date
1418
+ * as its ISO text and a plain object as its JSON, each for the server to
1419
+ * type, with the statement, in one round trip; `undefined` as NULL. Its
1420
+ * transactions', savepoints' and reserved connections' alike. The driver
1421
+ * would type an array by its first element, the element's type rather than
1422
+ * the array's, and so bind `[1, 2]` as one integer and mistype a `bytea[]`;
1423
+ * and it would ask the server first how to send an array of text.
1424
+ */
1425
+ function asPgSends(client) {
1426
+ return new Proxy(client, { get(target, key) {
1427
+ const value = Reflect.get(target, key, target);
1428
+ if (key === "unsafe") return (text, values, ...rest) => value.call(target, text, Array.isArray(values) ? values.map(sent) : values, ...rest);
1429
+ if (key === "group") return (statements) => value.call(target, statements.map((statement) => ({
1430
+ ...statement,
1431
+ parameters: statement.parameters?.map(sent)
1432
+ })));
1433
+ if (key === "begin" || key === "savepoint" || key === "reserve") return (...args) => {
1434
+ const work = args.at(-1);
1435
+ if (typeof work !== "function") return value.apply(target, args).then(asPgSends);
1436
+ return value.apply(target, [...args.slice(0, -1), (tx) => work(asPgSends(tx))]);
1437
+ };
1438
+ return value;
1439
+ } });
1440
+ }
1441
+ /**
1442
+ * A value as node-postgres sends it: an array, a date or a plain object (as
1443
+ * its JSON) as text, bytes of any view as bytes, `undefined` as NULL. What
1444
+ * else there is goes as it is.
1445
+ */
1446
+ function sent(value) {
1447
+ if (value === void 0) return null;
1448
+ if (Array.isArray(value)) return arrayText(value);
1449
+ if (value instanceof Date) return value.toISOString();
1450
+ const bytes = bytesOf(value);
1451
+ if (bytes !== null) return bytes;
1452
+ return plain(value) ? JSON.stringify(value) : value;
1453
+ }
1454
+ /** An object made as `{…}` is: no class of its own. */
1455
+ function plain(value) {
1456
+ if (typeof value !== "object" || value === null) return false;
1457
+ const prototype = Object.getPrototypeOf(value);
1458
+ return prototype === Object.prototype || prototype === null;
1459
+ }
1460
+ /** Bytes, from any view of them or their buffer, as a Uint8Array; null for anything else. */
1461
+ function bytesOf(value) {
1462
+ if (value instanceof Uint8Array) return value;
1463
+ if (ArrayBuffer.isView(value)) return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
1464
+ if (value instanceof ArrayBuffer) return Buffer.from(value);
1465
+ return null;
1466
+ }
1467
+ /** An array as Postgres's text for one, as node-postgres writes it: elements quoted, bytes as hex, nulls as NULL. */
1468
+ function arrayText(values) {
1469
+ return `{${values.map((value) => {
1470
+ if (value === null || value === void 0) return "NULL";
1471
+ if (Array.isArray(value)) return arrayText(value);
1472
+ const bytes = bytesOf(value);
1473
+ if (bytes !== null) return `\\\\x${Buffer.from(bytes).toString("hex")}`;
1474
+ return `"${(value instanceof Date ? value.toISOString() : typeof value === "object" ? JSON.stringify(value) : String(value)).replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
1475
+ }).join(",")}}`;
1476
+ }
1477
+ /**
1478
+ * Postgres's built-in types and their arrays, element and array oid, as
1479
+ * `fetch_types` would read them from `pg_type` at each connection: those a
1480
+ * hand-written statement may send or answer, as node-postgres knew them. An
1481
+ * array of any other type (ranges, geometry, `macaddr8`, a type of one's
1482
+ * own) is answered as Postgres's text for it: add it here to read it.
1483
+ */
1484
+ const ARRAYS = [
1485
+ [16, 1e3],
1486
+ [17, 1001],
1487
+ [18, 1002],
1488
+ [19, 1003],
1489
+ [20, 1016],
1490
+ [21, 1005],
1491
+ [23, 1007],
1492
+ [25, 1009],
1493
+ [26, 1028],
1494
+ [114, 199],
1495
+ [650, 651],
1496
+ [700, 1021],
1497
+ [701, 1022],
1498
+ [829, 1040],
1499
+ [869, 1041],
1500
+ [1042, 1014],
1501
+ [1043, 1015],
1502
+ [1082, 1182],
1503
+ [1083, 1183],
1504
+ [1114, 1115],
1505
+ [1184, 1185],
1506
+ [1186, 1187],
1507
+ [1266, 1270],
1508
+ [1700, 1231],
1509
+ [2950, 2951],
1510
+ [3802, 3807]
1511
+ ];
1512
+ /** `client`, which reads Postgres's arrays as node-postgres reads them, each element by its type's parser. */
1513
+ function arrayTypes(client) {
1514
+ const parsers = client.options.parsers;
1515
+ for (const [element, array] of ARRAYS) {
1516
+ const parse = parsers[element];
1517
+ parsers[array] = (text) => arrayOf(text, parse);
1518
+ }
1519
+ return client;
1520
+ }
1521
+ /**
1522
+ * Postgres's text for an array, `{a,"b,c",NULL,{1,2}}`, as its values: a
1523
+ * quoted element is text (`"NULL"` included), an unquoted NULL is null, and
1524
+ * explicit bounds (`[0:1]={…}`) are read past.
1525
+ */
1526
+ function arrayOf(text, parse) {
1527
+ let at = text.startsWith("[") ? text.indexOf("=") + 1 : 0;
1528
+ const list = () => {
1529
+ const values = [];
1530
+ at += 1;
1531
+ if (text[at] === "}") {
1532
+ at += 1;
1533
+ return values;
1534
+ }
1535
+ for (;;) {
1536
+ if (text[at] === "{") values.push(list());
1537
+ else if (text[at] === "\"") {
1538
+ let element = "";
1539
+ for (at += 1; text[at] !== "\""; at += 1) element += text[text[at] === "\\" ? ++at : at];
1540
+ at += 1;
1541
+ values.push(parse ? parse(element) : element);
1542
+ } else {
1543
+ const start = at;
1544
+ while (text[at] !== "," && text[at] !== "}") at += 1;
1545
+ const element = text.slice(start, at);
1546
+ values.push(element === "NULL" ? null : parse ? parse(element) : element);
1547
+ }
1548
+ if (text[at++] === "}") return values;
1549
+ }
1550
+ };
1551
+ return list();
1552
+ }
1553
+ /**
1554
+ * The Postgres types Drizzle maps from their text itself: dates and times,
1555
+ * and arrays of them and of numerics, as Drizzle's own drivers set them up,
1556
+ * postgres.js's (`construct`) and node-postgres's alike.
1557
+ */
1558
+ const TEXT_TYPES = [
1559
+ 1184,
1560
+ 1082,
1561
+ 1083,
1562
+ 1114,
1563
+ 1182,
1564
+ 1185,
1565
+ 1115,
1566
+ 1231
1567
+ ];
1568
+ /**
1569
+ * `client`, set up as Drizzle's own postgres.js driver sets one up: dates
1570
+ * and times come as Postgres's text, which each column maps, and JSON goes
1571
+ * as Drizzle writes it. For every statement of the client, `unsafe`'s
1572
+ * included: a client made a database (`createDatabase`) answers a raw
1573
+ * `now()` as text, not a Date.
1574
+ */
1575
+ function textTypes(client) {
1576
+ const identity = (value) => value;
1577
+ for (const type of TEXT_TYPES) {
1578
+ client.options.parsers[type] = identity;
1579
+ client.options.serializers[type] = identity;
1580
+ }
1581
+ client.options.serializers[114] = identity;
1582
+ client.options.serializers[3802] = identity;
1583
+ return client;
1584
+ }
1585
+ /**
1586
+ * The connection `url` names, as node-postgres and its pg-connection-string
1587
+ * read one. The driver reads no URL: it is given the parts. (Upstream
1588
+ * postgres.js read URLs otherwise: it sent every query parameter it did not
1589
+ * know to the server as a setting, which refused the connection over one it
1590
+ * did not know either, `sslrootcert` or `uselibpqcompat`; its
1591
+ * `sslmode=require` skipped the certificate check, where coffre's URLs, as
1592
+ * pg reads them, verify; and it checked an IP address against `localhost`.)
1593
+ *
1594
+ * TLS is:
1595
+ *
1596
+ * no sslmode, sslmode=disable none
1597
+ * sslmode=prefer, require, verify-ca, the certificate chain and the host verified
1598
+ * verify-full; ssl=true or 1
1599
+ * sslmode=no-verify TLS, nothing verified
1600
+ * uselibpqcompat=true libpq's modes: prefer and require verify nothing
1601
+ * (require with a sslrootcert, the chain), verify-ca
1602
+ * the chain, verify-full the chain and the host
1603
+ * sslrootcert=system Node's trusted CAs; only with verify-full or no sslmode
1604
+ * sslrootcert, sslcert, sslkey (files) read from disk, as pg does
1605
+ *
1606
+ * The host is verified against the URL's own, an IP address included.
1607
+ */
1608
+ function postgresOptions(url) {
1609
+ const hostless = /^[a-z]+:\/\/([^/?#@]*@)?\//i.test(url);
1610
+ if (/^[a-z]+:\/\/([^/?#@]*@)?[^/?#]*,/i.test(url)) throw new Error("a Postgres URL names one host: several, as libpq takes them, are not supported");
1611
+ let read;
1612
+ try {
1613
+ const parsed = new URL(hostless ? url.replace(/^([a-z]+:\/\/([^/?#@]*@)?)/i, "$1localhost") : url);
1614
+ const query = new Map([...parsed.searchParams].filter(([, value]) => value !== ""));
1615
+ const port = query.get("port") ?? (parsed.port || "5432");
1616
+ if (!/^\d{1,5}$/.test(port) || Number(port) === 0 || Number(port) > 65535) throw new Error("no port");
1617
+ read = {
1618
+ query,
1619
+ host: query.get("host") ?? decodeURIComponent(parsed.hostname.replace(/^\[(.*)\]$/, "$1")),
1620
+ port: Number(port),
1621
+ user: query.get("user") ?? decodeURIComponent(parsed.username),
1622
+ pass: query.get("password") ?? decodeURIComponent(parsed.password),
1623
+ database: decodeURIComponent(parsed.pathname.slice(1)) || void 0
1624
+ };
1625
+ } catch {
1626
+ throw new Error("invalid Postgres URL");
1627
+ }
1628
+ const { query, host, port, user, pass, database } = read;
1629
+ if (user === "") throw new Error("a Postgres URL names its user: postgresql://<user>@<host>/<database>");
1630
+ if (host.includes(",")) throw new Error("a Postgres URL names one host: several, as libpq takes them, are not supported");
1631
+ if (query.has("query_timeout")) throw new Error("a Postgres URL's query_timeout is not supported: statement_timeout bounds a statement in the server");
1632
+ const connectTimeout = query.get("connect_timeout");
1633
+ if (connectTimeout !== void 0 && !/^\d+$/.test(connectTimeout)) throw new Error("invalid Postgres URL");
1634
+ const mode = query.get("sslmode");
1635
+ if (mode !== void 0 && ![
1636
+ "disable",
1637
+ "allow",
1638
+ "prefer",
1639
+ "require",
1640
+ "verify-ca",
1641
+ "verify-full",
1642
+ "no-verify"
1643
+ ].includes(mode)) throw new Error(`a Postgres URL's sslmode is one of libpq's, not ${mode}`);
1644
+ if (![
1645
+ "postgres",
1646
+ "direct",
1647
+ void 0
1648
+ ].includes(query.get("sslnegotiation"))) throw new Error("a Postgres URL's sslnegotiation is postgres or direct");
1649
+ if (query.get("channel_binding") === "require") throw new Error("a Postgres URL's channel_binding=require is not supported: SCRAM goes without channel binding");
1650
+ const connection = {};
1651
+ for (const name of [
1652
+ "application_name",
1653
+ "fallback_application_name",
1654
+ "options",
1655
+ "statement_timeout",
1656
+ "lock_timeout",
1657
+ "idle_in_transaction_session_timeout"
1658
+ ]) {
1659
+ const value = query.get(name);
1660
+ if (value !== void 0) connection[name] = value;
1661
+ }
1662
+ const sslnegotiation = query.get("sslnegotiation") === "direct" ? "direct" : void 0;
1663
+ return {
1664
+ ...host.startsWith("/") ? { path: `${host}/.s.PGSQL.${port}` } : { host },
1665
+ port,
1666
+ user,
1667
+ pass,
1668
+ database,
1669
+ ssl: tlsFor(query, host, sslnegotiation !== void 0),
1670
+ ...sslnegotiation === void 0 ? {} : { sslnegotiation },
1671
+ ...connectTimeout === void 0 ? {} : { connect_timeout: Number(connectTimeout) },
1672
+ connection
1673
+ };
1674
+ }
1675
+ function tlsFor(query, host, direct) {
1676
+ const mode = query.get("sslmode");
1677
+ let rootcert = query.get("sslrootcert");
1678
+ if (rootcert === "system") {
1679
+ if (mode !== void 0 && mode !== "verify-full") throw new Error("sslrootcert=system requires sslmode=verify-full");
1680
+ if (!host || host.startsWith("/")) throw new Error("sslrootcert=system requires a Postgres hostname");
1681
+ rootcert = void 0;
1682
+ }
1683
+ const files = {
1684
+ cert: query.get("sslcert"),
1685
+ key: query.get("sslkey"),
1686
+ ca: rootcert
1687
+ };
1688
+ const flag = query.get("ssl");
1689
+ if (!(mode !== void 0 || Object.values(files).some((file) => file !== void 0) || query.get("sslrootcert") === "system" || flag === "true" || flag === "1" || direct) || mode === "disable") return false;
1690
+ const tls = {};
1691
+ for (const [name, file] of Object.entries(files)) if (file !== void 0) tls[name] = readFileSync(file).toString();
1692
+ const passphrase = query.get("sslpassword");
1693
+ if (passphrase !== void 0) tls.passphrase = passphrase;
1694
+ const libpq = query.get("uselibpqcompat") === "true";
1695
+ const verify = !libpq ? mode === "no-verify" ? "none" : "full" : mode === "prefer" || mode === "require" && tls.ca === void 0 ? "none" : mode === "require" || mode === "verify-ca" ? "chain" : "full";
1696
+ if (libpq && mode === "verify-ca" && tls.ca === void 0) throw new Error("sslmode=verify-ca requires a CA in sslrootcert: with a public CA, it lets anyone with a certificate from it pass as the database. Use sslmode=verify-full");
1697
+ if (verify === "none") return {
1698
+ ...tls,
1699
+ rejectUnauthorized: false
1700
+ };
1701
+ return {
1702
+ ...tls,
1703
+ rejectUnauthorized: true,
1704
+ checkServerIdentity: verify === "chain" ? () => void 0 : (_hostname, certificate) => checkServerIdentity(host, certificate),
1705
+ ...isIP(host) === 0 ? { servername: host } : {}
1706
+ };
1707
+ }
1708
+ /** `name` as a Postgres identifier, quoted, as node-postgres's `escapeIdentifier` writes one. */
1709
+ function quoteIdentifier(name) {
1710
+ return `"${name.replaceAll("\"", "\"\"")}"`;
1711
+ }
1712
+ /** `text` as a Postgres string literal, as node-postgres's `escapeLiteral` writes one: `E'…'` when it holds a backslash. */
1713
+ function quoteLiteral(text) {
1714
+ const quoted = `'${text.replaceAll("'", "''").replaceAll("\\", "\\\\")}'`;
1715
+ return text.includes("\\") ? ` E${quoted}` : quoted;
1716
+ }
1717
+ //#endregion
1718
+ export { quoteIdentifier as a, plainRead as c, postgresSession as i, postgresClient as n, quoteLiteral as o, postgresOptions as r, textTypes as s, SessionLost as t };