@akal/supaforge 0.0.31 → 0.0.32

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 (73) hide show
  1. package/README.md +1 -1
  2. package/dist/base-command.d.ts +1 -0
  3. package/dist/base-command.js +2 -2
  4. package/dist/{chunk-BHYLBKYD.js → chunk-2SELREHW.js} +5 -5
  5. package/dist/{chunk-5Z3SAIQS.js → chunk-3HGAV5CC.js} +97 -831
  6. package/dist/chunk-3HGAV5CC.js.map +1 -0
  7. package/dist/{chunk-XMYMIURR.js → chunk-4IVN7QVY.js} +119 -39
  8. package/dist/chunk-4IVN7QVY.js.map +1 -0
  9. package/dist/{chunk-NXRSAVRU.js → chunk-6LJERPUN.js} +28 -7
  10. package/dist/chunk-6LJERPUN.js.map +1 -0
  11. package/dist/{chunk-4OU7KO5Y.js → chunk-6Q7MHFBM.js} +2 -2
  12. package/dist/{chunk-PARSNTBD.js → chunk-7NAZGZPV.js} +56 -25
  13. package/dist/chunk-7NAZGZPV.js.map +1 -0
  14. package/dist/{chunk-VOXZWQ3N.js → chunk-BUOWHE36.js} +372 -9
  15. package/dist/chunk-BUOWHE36.js.map +1 -0
  16. package/dist/{chunk-TQJSQLWA.js → chunk-DMIWAJRB.js} +38 -10
  17. package/dist/chunk-DMIWAJRB.js.map +1 -0
  18. package/dist/{chunk-LQXF65MC.js → chunk-GEHPTPNZ.js} +3 -3
  19. package/dist/chunk-GEHPTPNZ.js.map +1 -0
  20. package/dist/chunk-GZREXCQZ.js +207 -0
  21. package/dist/chunk-GZREXCQZ.js.map +1 -0
  22. package/dist/{chunk-YVDSR4GM.js → chunk-MIRLB5JM.js} +51 -23
  23. package/dist/chunk-MIRLB5JM.js.map +1 -0
  24. package/dist/{chunk-KIFJGON5.js → chunk-NTUASFQ3.js} +2 -2
  25. package/dist/{chunk-5QQBTLWO.js → chunk-ORQJVE57.js} +3 -3
  26. package/dist/{chunk-VMTBLHN2.js → chunk-SC2XHGIS.js} +2 -2
  27. package/dist/{chunk-X6V2GGDZ.js → chunk-SQPCWGQO.js} +388 -64
  28. package/dist/chunk-SQPCWGQO.js.map +1 -0
  29. package/dist/chunk-UWAVXC57.js +916 -0
  30. package/dist/chunk-UWAVXC57.js.map +1 -0
  31. package/dist/commands/clone.js +10 -10
  32. package/dist/commands/diff.d.ts +16 -0
  33. package/dist/commands/diff.js +11 -12
  34. package/dist/commands/hukam.js +11 -12
  35. package/dist/commands/hukam.js.map +1 -1
  36. package/dist/commands/mcp.js +7 -8
  37. package/dist/commands/mcp.js.map +1 -1
  38. package/dist/commands/migrate/baseline.js +3 -3
  39. package/dist/commands/migrate/create.js +5 -6
  40. package/dist/commands/migrate/create.js.map +1 -1
  41. package/dist/commands/migrate/list.js +4 -4
  42. package/dist/commands/migrate/list.js.map +1 -1
  43. package/dist/commands/migrate/run.js +5 -6
  44. package/dist/commands/report.js +3 -3
  45. package/dist/commands/restore.js +11 -13
  46. package/dist/commands/restore.js.map +1 -1
  47. package/dist/commands/snapshot.js +6 -8
  48. package/dist/commands/snapshot.js.map +1 -1
  49. package/dist/commands/sync.js +11 -12
  50. package/dist/commands/sync.js.map +1 -1
  51. package/dist/index.d.ts +5 -0
  52. package/dist/index.js +16 -16
  53. package/package.json +2 -2
  54. package/dist/chunk-5Z3SAIQS.js.map +0 -1
  55. package/dist/chunk-H5MJ5DFX.js +0 -16
  56. package/dist/chunk-H5MJ5DFX.js.map +0 -1
  57. package/dist/chunk-LQXF65MC.js.map +0 -1
  58. package/dist/chunk-NXRSAVRU.js.map +0 -1
  59. package/dist/chunk-PARSNTBD.js.map +0 -1
  60. package/dist/chunk-RRMI5CZD.js +0 -376
  61. package/dist/chunk-RRMI5CZD.js.map +0 -1
  62. package/dist/chunk-SF3YA42C.js +0 -506
  63. package/dist/chunk-SF3YA42C.js.map +0 -1
  64. package/dist/chunk-TQJSQLWA.js.map +0 -1
  65. package/dist/chunk-VOXZWQ3N.js.map +0 -1
  66. package/dist/chunk-X6V2GGDZ.js.map +0 -1
  67. package/dist/chunk-XMYMIURR.js.map +0 -1
  68. package/dist/chunk-YVDSR4GM.js.map +0 -1
  69. /package/dist/{chunk-BHYLBKYD.js.map → chunk-2SELREHW.js.map} +0 -0
  70. /package/dist/{chunk-4OU7KO5Y.js.map → chunk-6Q7MHFBM.js.map} +0 -0
  71. /package/dist/{chunk-KIFJGON5.js.map → chunk-NTUASFQ3.js.map} +0 -0
  72. /package/dist/{chunk-5QQBTLWO.js.map → chunk-ORQJVE57.js.map} +0 -0
  73. /package/dist/{chunk-VMTBLHN2.js.map → chunk-SC2XHGIS.js.map} +0 -0
@@ -1,60 +1,17 @@
1
1
  import {
2
+ CONTAINER_RM_TIMEOUT_MS,
3
+ CONTAINER_START_TIMEOUT_MS,
2
4
  DB_CONNECT_TIMEOUT_MS,
3
- MIGRATIONS_TABLE
5
+ DB_PROBE_TIMEOUT_MS,
6
+ MIGRATIONS_TABLE,
7
+ RUNTIME_DETECT_TIMEOUT_MS,
8
+ bold,
9
+ cmd,
10
+ dim,
11
+ ok,
12
+ warn
4
13
  } from "./chunk-6WAMNZLO.js";
5
14
 
6
- // src/db.ts
7
- import pg from "pg";
8
- function resolveConnectTimeoutMs() {
9
- const raw = process.env.SUPAFORGE_CONNECT_TIMEOUT;
10
- if (raw) {
11
- const secs = Number(raw);
12
- if (Number.isFinite(secs) && secs > 0) return Math.round(secs * 1e3);
13
- }
14
- return DB_CONNECT_TIMEOUT_MS;
15
- }
16
- function pgClientConfig(dbUrl, queryTimeoutMs) {
17
- const config = {
18
- connectionString: dbUrl,
19
- connectionTimeoutMillis: resolveConnectTimeoutMs()
20
- };
21
- if (queryTimeoutMs !== void 0) {
22
- config.query_timeout = queryTimeoutMs;
23
- }
24
- return config;
25
- }
26
- var pools = /* @__PURE__ */ new Map();
27
- var POOL_MAX = 4;
28
- function poolFor(dbUrl) {
29
- const existing = pools.get(dbUrl);
30
- if (existing) return existing;
31
- const pool = new pg.Pool({
32
- ...pgClientConfig(dbUrl),
33
- max: POOL_MAX,
34
- allowExitOnIdle: true
35
- });
36
- pool.on("error", () => void 0);
37
- pools.set(dbUrl, pool);
38
- return pool;
39
- }
40
- var pgQuery = async (dbUrl, sql, params) => {
41
- const { rows } = await poolFor(dbUrl).query(sql, params);
42
- return rows;
43
- };
44
- async function inRolledBackTransaction(dbUrl, fn) {
45
- const client = await poolFor(dbUrl).connect();
46
- try {
47
- await client.query("BEGIN");
48
- try {
49
- return await fn(client);
50
- } finally {
51
- await client.query("ROLLBACK").catch(() => void 0);
52
- }
53
- } finally {
54
- client.release();
55
- }
56
- }
57
-
58
15
  // src/utils/error.ts
59
16
  var DB_URL_RE = /\b((?:postgres(?:ql)?|mysql|mariadb):\/\/)(\S+)/g;
60
17
  function redactUrls(message) {
@@ -105,13 +62,20 @@ var CONNECTION_ERROR_PATTERNS = [
105
62
  test: (m) => /ENOTFOUND|getaddrinfo/i.test(m),
106
63
  build: (host) => `Cannot resolve hostname ${host} \u2014 check the database URL in your config.`
107
64
  },
65
+ {
66
+ // Before the connection timeout: the server answered, and a query ran
67
+ // past its statement_timeout. Calling that a connection problem sent
68
+ // people to check a host and port that were fine.
69
+ test: (m) => /canceling statement due to statement timeout|57014/i.test(m),
70
+ build: (host) => `A query on ${host} was cancelled by statement_timeout \u2014 the server is reachable. Raise statement_timeout for this role or connection and try again.`
71
+ },
108
72
  {
109
73
  // Deliberately narrow. A bare /timeout/i also matches our own remediation
110
74
  // text — "set SUPAFORGE_DBDIFF_TIMEOUT=600" contains "TIMEOUT" — which is
111
75
  // how an accurate "Schema diff timed out after Ns" message was being
112
76
  // rewritten into a wrong "check the host and port" one (issue #29).
113
77
  // DiagnosticError below is the primary guard; this is defence in depth.
114
- test: (m) => /ETIMEDOUT|connection timed out|timeout expired|statement timeout/i.test(m),
78
+ test: (m) => /ETIMEDOUT|connection timed out|timeout expired/i.test(m),
115
79
  build: (host) => `Connection to ${host} timed out \u2014 verify the host and port are correct and that the server is reachable.`
116
80
  },
117
81
  {
@@ -156,6 +120,351 @@ function friendlyDbError(err, dbUrl) {
156
120
  return raw;
157
121
  }
158
122
 
123
+ // src/db.ts
124
+ import pg from "pg";
125
+ function resolveConnectTimeoutMs() {
126
+ const raw = process.env.SUPAFORGE_CONNECT_TIMEOUT;
127
+ if (raw) {
128
+ const secs = Number(raw);
129
+ if (Number.isFinite(secs) && secs > 0) return Math.round(secs * 1e3);
130
+ }
131
+ return DB_CONNECT_TIMEOUT_MS;
132
+ }
133
+ function pgClientConfig(dbUrl, queryTimeoutMs) {
134
+ const config = {
135
+ connectionString: dbUrl,
136
+ connectionTimeoutMillis: resolveConnectTimeoutMs()
137
+ };
138
+ if (queryTimeoutMs !== void 0) {
139
+ config.query_timeout = queryTimeoutMs;
140
+ }
141
+ return config;
142
+ }
143
+ var pools = /* @__PURE__ */ new Map();
144
+ var POOL_MAX = 4;
145
+ function poolFor(dbUrl) {
146
+ const existing = pools.get(dbUrl);
147
+ if (existing) return existing;
148
+ const pool = new pg.Pool({
149
+ ...pgClientConfig(dbUrl),
150
+ max: POOL_MAX,
151
+ allowExitOnIdle: true
152
+ });
153
+ pool.on("error", () => void 0);
154
+ pools.set(dbUrl, pool);
155
+ return pool;
156
+ }
157
+ var pgQuery = async (dbUrl, sql, params) => {
158
+ const { rows } = await poolFor(dbUrl).query(sql, params);
159
+ return rows;
160
+ };
161
+ async function inRolledBackTransaction(dbUrl, fn) {
162
+ const client = await poolFor(dbUrl).connect();
163
+ try {
164
+ await client.query("BEGIN");
165
+ try {
166
+ return await fn(client);
167
+ } finally {
168
+ await client.query("ROLLBACK").catch(() => void 0);
169
+ }
170
+ } finally {
171
+ client.release();
172
+ }
173
+ }
174
+
175
+ // src/local-pg.ts
176
+ import { execFile } from "child_process";
177
+ import { promisify } from "util";
178
+ import pg2 from "pg";
179
+ var defaultExecFile = promisify(execFile);
180
+ var PG_IMAGE = "docker.io/library/postgres:17";
181
+ var DEFAULT_LOCAL_PORT = 5432;
182
+ var CONTAINER_NAME = "supaforge-local-pg";
183
+ var LOCAL_PG_USER = "postgres";
184
+ var LOCAL_PG_PASSWORD = "postgres";
185
+ var READINESS_RETRIES = 30;
186
+ var READINESS_INTERVAL_MS = 2e3;
187
+ async function defaultConnectFn(url) {
188
+ const client = new pg2.Client(pgClientConfig(url));
189
+ await client.connect();
190
+ await client.end();
191
+ }
192
+ async function detectRuntime(execFn = defaultExecFile) {
193
+ for (const rt of ["podman", "docker"]) {
194
+ try {
195
+ await execFn(rt, ["--version"], { timeout: RUNTIME_DETECT_TIMEOUT_MS });
196
+ return rt;
197
+ } catch {
198
+ continue;
199
+ }
200
+ }
201
+ return null;
202
+ }
203
+ async function startLocalPg(options = {}) {
204
+ const exec = options.execFn ?? defaultExecFile;
205
+ const connect = options.connectFn ?? defaultConnectFn;
206
+ const runtime = options.runtime ?? await detectRuntime(exec);
207
+ if (!runtime) {
208
+ throw new Error(
209
+ "No container runtime found. Install Podman (recommended) or Docker.\n Podman: https://podman.io/docs/installation\n Docker: https://docs.docker.com/engine/install/"
210
+ );
211
+ }
212
+ const port = options.port ?? DEFAULT_LOCAL_PORT;
213
+ const password = options.password ?? LOCAL_PG_PASSWORD;
214
+ const name = options.name ?? CONTAINER_NAME;
215
+ const image = options.image ?? PG_IMAGE;
216
+ const existing = await getContainerStatus(runtime, name, exec);
217
+ if (existing === "running") {
218
+ return {
219
+ runtime,
220
+ containerName: name,
221
+ port,
222
+ url: buildLocalUrl(port, password)
223
+ };
224
+ }
225
+ if (existing === "stopped") {
226
+ await exec(runtime, ["rm", "-f", name], { timeout: CONTAINER_RM_TIMEOUT_MS });
227
+ }
228
+ const args = [
229
+ "run",
230
+ "-d",
231
+ "--name",
232
+ name,
233
+ "-p",
234
+ `${port}:5432`,
235
+ "-e",
236
+ `POSTGRES_PASSWORD=${password}`,
237
+ "-e",
238
+ `POSTGRES_USER=${LOCAL_PG_USER}`,
239
+ "--tmpfs",
240
+ "/var/lib/postgresql/data",
241
+ "--health-cmd",
242
+ `pg_isready -U ${LOCAL_PG_USER}`,
243
+ "--health-interval",
244
+ "5s",
245
+ "--health-timeout",
246
+ "5s",
247
+ "--health-retries",
248
+ "20",
249
+ "--health-start-period",
250
+ "10s",
251
+ image
252
+ ];
253
+ try {
254
+ await exec(runtime, args, { timeout: CONTAINER_START_TIMEOUT_MS });
255
+ } catch (err) {
256
+ throw new Error(
257
+ `Failed to start PostgreSQL container via ${runtime}: ${err.message}`
258
+ );
259
+ }
260
+ const url = buildLocalUrl(port, password);
261
+ await waitForPg(url, connect);
262
+ return { runtime, containerName: name, port, url };
263
+ }
264
+ async function getContainerStatus(runtime, name, execFn) {
265
+ try {
266
+ const { stdout } = await execFn(
267
+ runtime,
268
+ ["inspect", "--format", "{{.State.Running}}", name],
269
+ { timeout: RUNTIME_DETECT_TIMEOUT_MS }
270
+ );
271
+ return stdout.trim() === "true" ? "running" : "stopped";
272
+ } catch {
273
+ return "none";
274
+ }
275
+ }
276
+ function buildLocalUrl(port, password) {
277
+ return `postgres://${LOCAL_PG_USER}:${password}@localhost:${port}/postgres`;
278
+ }
279
+ async function waitForPg(url, connectFn) {
280
+ for (let i = 0; i < READINESS_RETRIES; i++) {
281
+ try {
282
+ await connectFn(url);
283
+ return;
284
+ } catch {
285
+ await sleep(READINESS_INTERVAL_MS);
286
+ }
287
+ }
288
+ throw new Error(
289
+ `PostgreSQL at ${url} did not become ready within ${READINESS_RETRIES * READINESS_INTERVAL_MS / 1e3}s`
290
+ );
291
+ }
292
+ function sleep(ms) {
293
+ return new Promise((resolve) => setTimeout(resolve, ms));
294
+ }
295
+
296
+ // src/preflight.ts
297
+ import pg3 from "pg";
298
+ var SUPABASE_LOCAL_PORT = "54322";
299
+ var DEFAULT_PG_PORT = "5432";
300
+ var CONNECT_TIMEOUT_RE = /timeout expired|connection timeout/i;
301
+ var QUERY_TIMEOUT_RE = /query read timeout/i;
302
+ function describeTimeout(message, connectTimeoutMs, probeTimeoutMs) {
303
+ if (CONNECT_TIMEOUT_RE.test(message)) {
304
+ return `timed out after ${Math.round(connectTimeoutMs / 1e3)}s connecting \u2014 the host accepted the connection but never completed the handshake`;
305
+ }
306
+ if (QUERY_TIMEOUT_RE.test(message)) {
307
+ return `timed out after ${Math.round(probeTimeoutMs / 1e3)}s waiting for server response \u2014 connected, but the server did not answer`;
308
+ }
309
+ return message;
310
+ }
311
+ async function checkConnection(dbUrl) {
312
+ const connectTimeoutMs = resolveConnectTimeoutMs();
313
+ let client;
314
+ try {
315
+ client = new pg3.Client(pgClientConfig(dbUrl, DB_PROBE_TIMEOUT_MS));
316
+ await client.connect();
317
+ const { rows } = await client.query("SHOW server_version");
318
+ const version = rows[0].server_version;
319
+ return { reachable: true, version };
320
+ } catch (err) {
321
+ return {
322
+ reachable: false,
323
+ error: describeTimeout(describeFailure(err), connectTimeoutMs, DB_PROBE_TIMEOUT_MS)
324
+ };
325
+ } finally {
326
+ try {
327
+ await client?.end();
328
+ } catch {
329
+ }
330
+ }
331
+ }
332
+ var SERVER_REACHABLE_RE = /password authentication failed|does not exist|database .* does not exist|SSL.*required|no pg_hba\.conf entry/i;
333
+ async function buildLocalHints(dbUrl, error) {
334
+ const hints = [];
335
+ try {
336
+ const urlObj = new URL(dbUrl);
337
+ const isSupabasePort = urlObj.port === SUPABASE_LOCAL_PORT;
338
+ const isLocal = ["localhost", "127.0.0.1", "::1", ""].includes(urlObj.hostname);
339
+ if (!isLocal) return hints;
340
+ if (error && SERVER_REACHABLE_RE.test(error)) {
341
+ hints.push(`Check the username and password in your database URL.`);
342
+ if (isSupabasePort) {
343
+ hints.push(`Port ${SUPABASE_LOCAL_PORT} is the Supabase CLI default. The default password is "postgres".`);
344
+ }
345
+ return hints;
346
+ }
347
+ if (isSupabasePort) {
348
+ hints.push(`Port ${SUPABASE_LOCAL_PORT} is the Supabase CLI default. Run ${cmd('"supabase start"')} to start your local Supabase instance.`);
349
+ }
350
+ const runtime = await detectRuntime();
351
+ if (runtime) {
352
+ hints.push(`${bold(runtime)} detected \u2014 you can start a PostgreSQL container manually.`);
353
+ }
354
+ if (!isSupabasePort) {
355
+ hints.push(`Start PostgreSQL manually on port ${urlObj.port || DEFAULT_PG_PORT}.`);
356
+ }
357
+ } catch {
358
+ }
359
+ return hints;
360
+ }
361
+ function buildTimeoutHints() {
362
+ return [
363
+ "The host is listening but the database did not answer.",
364
+ "Check the database process is running and not paused, restarting, or overloaded.",
365
+ "Over a VPN or tunnel, check the connection is still up.",
366
+ `Raise the bound with ${cmd("SUPAFORGE_CONNECT_TIMEOUT")} (in seconds) if the link is simply slow.`
367
+ ];
368
+ }
369
+ async function buildConnectionHints(dbUrl, error) {
370
+ if (error && /timed out after \d+s/.test(error)) return buildTimeoutHints();
371
+ return buildLocalHints(dbUrl, error);
372
+ }
373
+ var defaultPending = (msg) => {
374
+ if (!process.stdout.isTTY) return;
375
+ process.stdout.write(msg === null ? "\r\x1B[2K" : `\r\x1B[2K${msg}`);
376
+ };
377
+ var Preflight = class {
378
+ title;
379
+ log;
380
+ pending;
381
+ databases = [];
382
+ customs = [];
383
+ infoLines = [];
384
+ constructor(title, log, pending = defaultPending) {
385
+ this.title = title;
386
+ this.log = log;
387
+ this.pending = pending;
388
+ }
389
+ /** Register a database connectivity check. */
390
+ addDatabase(label, envName, dbUrl) {
391
+ this.databases.push({ label, envName, dbUrl });
392
+ return this;
393
+ }
394
+ /** Add an informational line to the header (displayed after database lines). */
395
+ addInfo(label, value) {
396
+ this.infoLines.push({ label, value });
397
+ return this;
398
+ }
399
+ /** Register a custom check (runs after all DB connectivity checks). */
400
+ addCheck(label, fn) {
401
+ this.customs.push({ label, fn });
402
+ return this;
403
+ }
404
+ /** Execute all registered checks, render results, and return the report. */
405
+ async run() {
406
+ const entries = [];
407
+ const log = this.log;
408
+ log(`
409
+ ${bold(this.title)}
410
+ `);
411
+ for (const db of this.databases) {
412
+ log(` ${db.label}: ${db.envName} ${dim(`(${redactUrls(db.dbUrl)})`)}`);
413
+ }
414
+ for (const info of this.infoLines) {
415
+ log(` ${info.label}: ${info.value}`);
416
+ }
417
+ log("");
418
+ log(" Checks:");
419
+ for (const db of this.databases) {
420
+ this.pending(` ${dim(`\u2026 connecting to ${db.label.toLowerCase()}`)}`);
421
+ const result = await checkConnection(db.dbUrl);
422
+ this.pending(null);
423
+ if (result.reachable) {
424
+ log(` ${ok("\u2713")} ${db.label} reachable ${dim(`(PostgreSQL ${result.version})`)}`);
425
+ entries.push({ label: db.label, passed: true, detail: `PostgreSQL ${result.version}` });
426
+ } else {
427
+ log(` ${warn("\u2717")} ${db.label} not reachable: ${redactUrls(describeFailure(result.error))}`);
428
+ const hints = await buildConnectionHints(db.dbUrl, result.error);
429
+ if (hints.length > 0) {
430
+ log(`
431
+ ${dim("Hints:")}`);
432
+ for (const h of hints) log(` ${dim("\u2022")} ${h}`);
433
+ }
434
+ entries.push({ label: db.label, passed: false, error: result.error, hints });
435
+ }
436
+ }
437
+ for (const custom of this.customs) {
438
+ this.pending(` ${dim(`\u2026 ${custom.label}`)}`);
439
+ const result = await custom.fn();
440
+ this.pending(null);
441
+ if (!result.error) {
442
+ const suffix = result.detail ? ` ${dim(result.detail)}` : "";
443
+ log(` ${ok("\u2713")} ${custom.label}${suffix}`);
444
+ entries.push({ label: custom.label, passed: true, detail: result.detail });
445
+ } else {
446
+ log(` ${warn("\u2717")} ${custom.label}: ${redactUrls(describeFailure(result.error))}`);
447
+ if (result.hints?.length) {
448
+ log(`
449
+ ${dim("Hints:")}`);
450
+ for (const h of result.hints) log(` ${dim("\u2022")} ${h}`);
451
+ }
452
+ entries.push({ label: custom.label, passed: false, error: result.error, hints: result.hints });
453
+ }
454
+ }
455
+ const passed = entries.every((e) => e.passed);
456
+ log("");
457
+ if (!passed) {
458
+ log(` ${warn("Some checks failed.")} Fix the issues above first.
459
+ `);
460
+ } else {
461
+ log(` ${ok("All checks passed.")}
462
+ `);
463
+ }
464
+ return { passed, checks: entries };
465
+ }
466
+ };
467
+
159
468
  // src/checks/base.ts
160
469
  var CheckSkipped = class extends Error {
161
470
  /** Distinguishes a skip from a genuine error across module boundaries. */
@@ -167,6 +476,19 @@ var CheckSkipped = class extends Error {
167
476
  function isCheckSkipped(err) {
168
477
  return err instanceof Error && err.name === "CheckSkipped";
169
478
  }
479
+ var MISSING_OBJECT_CODES = /* @__PURE__ */ new Set(["42P01", "3F000", "42883"]);
480
+ function isMissingObject(err) {
481
+ const code = err?.code;
482
+ return typeof code === "string" && MISSING_OBJECT_CODES.has(code);
483
+ }
484
+ async function readOrAbsent(read, absent) {
485
+ try {
486
+ return await read();
487
+ } catch (err) {
488
+ if (isMissingObject(err)) return absent;
489
+ throw err;
490
+ }
491
+ }
170
492
  var Check = class {
171
493
  };
172
494
 
@@ -220,11 +542,7 @@ var MigrationsCheck = class extends Check {
220
542
  return diffMigrations(local, db, mode);
221
543
  }
222
544
  async fetchDbMigrations(dbUrl) {
223
- try {
224
- return await this.queryFn(dbUrl, MIGRATIONS_SQL);
225
- } catch {
226
- return [];
227
- }
545
+ return readOrAbsent(async () => await this.queryFn(dbUrl, MIGRATIONS_SQL), []);
228
546
  }
229
547
  };
230
548
  function parseFilename(filename) {
@@ -310,24 +628,30 @@ function markAppliedSql(version, name) {
310
628
  }
311
629
 
312
630
  export {
313
- resolveConnectTimeoutMs,
314
- pgClientConfig,
315
- pgQuery,
316
- inRolledBackTransaction,
317
631
  redactUrls,
318
632
  describeFailure,
319
633
  errMsg,
320
634
  DiagnosticError,
321
635
  friendlyDbError,
636
+ pgClientConfig,
637
+ pgQuery,
638
+ inRolledBackTransaction,
639
+ DEFAULT_LOCAL_PORT,
640
+ LOCAL_PG_USER,
641
+ LOCAL_PG_PASSWORD,
642
+ startLocalPg,
643
+ checkConnection,
644
+ Preflight,
322
645
  quoteIdent,
323
646
  quoteName,
324
647
  quoteLiteral,
325
648
  sqlLiteral,
326
649
  CheckSkipped,
327
650
  isCheckSkipped,
651
+ readOrAbsent,
328
652
  Check,
329
653
  DEFAULT_MIGRATIONS_DIR,
330
654
  MigrationsCheck,
331
655
  readLocalMigrations
332
656
  };
333
- //# sourceMappingURL=chunk-X6V2GGDZ.js.map
657
+ //# sourceMappingURL=chunk-SQPCWGQO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/error.ts","../src/db.ts","../src/local-pg.ts","../src/preflight.ts","../src/checks/base.ts","../src/checks/migrations.ts","../src/utils/sql.ts"],"sourcesContent":["/**\n * Regex matching database connection URL schemes (postgres, mysql, etc.).\n * Captures the scheme + `://` and the rest of the URL up to the next whitespace.\n */\nconst DB_URL_RE = /\\b((?:postgres(?:ql)?|mysql|mariadb):\\/\\/)(\\S+)/g\n\n/**\n * Redact passwords from database connection URLs in a string.\n *\n * Replaces `://user:PASSWORD@host` with `://user:***@host` to prevent\n * credentials from leaking into logs, error messages, or terminal output.\n * Handles passwords containing special characters including `@`.\n */\nexport function redactUrls(message: string): string {\n return message.replace(DB_URL_RE, (_, scheme: string, rest: string) => {\n const lastAt = rest.lastIndexOf('@')\n if (lastAt === -1) return scheme + rest\n const creds = rest.slice(0, lastAt)\n const hostPart = rest.slice(lastAt)\n const colonIdx = creds.indexOf(':')\n if (colonIdx === -1) return scheme + rest\n return scheme + creds.slice(0, colonIdx) + ':***' + hostPart\n })\n}\n\n/** Shown when a failure carries nothing at all that could name it. */\nexport const UNDESCRIBED_ERROR = 'unknown error — no message reported'\n\n/**\n * Get something printable out of a thrown value.\n *\n * Not every failure arrives as an `Error` with a populated `message`. One did\n * not — observed when a container runtime's daemon stopped while a port mapping\n * was still registered — and every renderer downstream printed its label, a\n * colon, and nothing: `✗ Source database not reachable:` (issue #47).\n *\n * Falls back through what a driver error still carries when its message is\n * empty: the `code` (`ECONNRESET`, `EPIPE`) is the most useful, then the error\n * type, then a fixed string. The return value is never empty, which is the\n * whole point — a reason a user cannot read is worse than a generic one.\n */\nexport function describeFailure(err: unknown): string {\n if (typeof err === 'string') return err.trim() || UNDESCRIBED_ERROR\n\n const candidate = err as { message?: unknown; code?: unknown; name?: unknown } | null | undefined\n const message = typeof candidate?.message === 'string' ? candidate.message.trim() : ''\n if (message) return message\n\n const code = typeof candidate?.code === 'string' ? candidate.code.trim() : ''\n if (code) return `${code} (no further detail reported)`\n\n const name = typeof candidate?.name === 'string' ? candidate.name.trim() : ''\n if (name && name !== 'Error') return `${name} (no further detail reported)`\n\n if (err !== null && err !== undefined && !(err instanceof Error)) {\n const rendered = String(err).trim()\n if (rendered && rendered !== '[object Object]') return rendered\n }\n\n return UNDESCRIBED_ERROR\n}\n\n/**\n * Extract a concise error message from an unknown caught value.\n *\n * Safely handles Error instances, strings, and other thrown types, and never\n * returns an empty string — see describeFailure. Used across the codebase in\n * catch blocks to normalise error output. Automatically redacts database\n * credentials from the message.\n */\nexport function errMsg(err: unknown): string {\n return redactUrls(describeFailure(err))\n}\n\n/**\n * An error whose message is already written for the user — it has been\n * diagnosed, and usually carries remediation steps.\n *\n * friendlyDbError() passes these through untouched instead of pattern-matching\n * them into a generic connection error. Without this, any accurate message that\n * happens to mention a timeout (including one telling the user which timeout\n * env var to raise) got rewritten into advice to check their host and port.\n */\nexport class DiagnosticError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'DiagnosticError'\n }\n}\n\n/**\n * Structural check rather than `instanceof`.\n *\n * The CLI and its tests can load a module through more than one path (src vs\n * dist, ESM vs CJS interop), which yields two distinct class identities and\n * makes `instanceof` silently false. Matching on the name keeps the guard\n * working across those boundaries.\n */\nexport function isDiagnosticError(err: unknown): boolean {\n return err instanceof DiagnosticError || (err instanceof Error && err.name === 'DiagnosticError')\n}\n\n// ─── Connection Error Patterns ───────────────────────────────────────────────\n\n/** Known patterns matched against error messages, checked in order. */\nconst CONNECTION_ERROR_PATTERNS: Array<{ test: (msg: string) => boolean; build: (host: string) => string }> = [\n {\n test: (m) => /ECONNREFUSED|Connection refused/i.test(m),\n build: (host) => `Cannot connect to PostgreSQL at ${host} — the server does not appear to be running. Start it and try again.`,\n },\n {\n test: (m) => /ENOTFOUND|getaddrinfo/i.test(m),\n build: (host) => `Cannot resolve hostname ${host} — check the database URL in your config.`,\n },\n {\n // Before the connection timeout: the server answered, and a query ran\n // past its statement_timeout. Calling that a connection problem sent\n // people to check a host and port that were fine.\n test: (m) => /canceling statement due to statement timeout|57014/i.test(m),\n build: (host) => `A query on ${host} was cancelled by statement_timeout — the server is reachable. Raise statement_timeout for this role or connection and try again.`,\n },\n {\n // Deliberately narrow. A bare /timeout/i also matches our own remediation\n // text — \"set SUPAFORGE_DBDIFF_TIMEOUT=600\" contains \"TIMEOUT\" — which is\n // how an accurate \"Schema diff timed out after Ns\" message was being\n // rewritten into a wrong \"check the host and port\" one (issue #29).\n // DiagnosticError below is the primary guard; this is defence in depth.\n test: (m) => /ETIMEDOUT|connection timed out|timeout expired/i.test(m),\n build: (host) => `Connection to ${host} timed out — verify the host and port are correct and that the server is reachable.`,\n },\n {\n test: (m) => /password authentication failed/i.test(m),\n build: (host) => `Authentication failed for ${host} — check the username and password in your database URL.`,\n },\n {\n // Must stay anchored to \"database ... does not exist\" (Postgres SQLSTATE\n // 3D000). A bare /does not exist/ is the same trap as the timeout pattern\n // above: it matched dbdiff's own CLI complaint — The \"--allow-destructive\"\n // option does not exist — and rewrote it into \"Database does not exist on\n // 127.0.0.1:5432\", sending you off to check a database name that was fine\n // while the real cause (an outdated @dbdiff/cli) went unmentioned.\n test: (m) => /database\\s+\"[^\"]*\"\\s+does not exist|3D000/i.test(m),\n build: (host) => `Database does not exist on ${host} — verify the database name in your config.`,\n },\n {\n test: (m) => /SSL.*required|no pg_hba.conf entry/i.test(m),\n build: (host) => `Connection rejected by ${host} — the server requires SSL or your IP is not allowed. Check pg_hba.conf and SSL settings.`,\n },\n]\n\n/**\n * Extract host:port from a PostgreSQL connection URL.\n * Returns just the host portion with the port for display.\n */\nfunction extractHost(dbUrl: string): string {\n try {\n const url = new URL(dbUrl)\n return url.port ? `${url.hostname}:${url.port}` : url.hostname\n } catch {\n return 'the configured host'\n }\n}\n\n/**\n * Translate a raw database error into a user-friendly message.\n *\n * Matches known pg error patterns and returns an actionable message\n * with the host identified. Returns the original (redacted) message\n * if no pattern matches.\n */\nexport function friendlyDbError(err: unknown, dbUrl?: string): string {\n const raw = errMsg(err)\n\n // Already a message written for the user, with its own diagnosis and\n // remediation — translating it again can only make it worse, and did:\n // the schema-diff timeout message was being replaced by a connection\n // error naming a host that was demonstrably reachable (issue #29).\n if (isDiagnosticError(err)) return raw\n\n const host = dbUrl ? extractHost(dbUrl) : 'the configured host'\n\n for (const pattern of CONNECTION_ERROR_PATTERNS) {\n try {\n if (pattern.test(raw)) {\n return pattern.build(host)\n }\n } catch {\n // A malformed host or an unexpected pattern failure must never turn a\n // reportable error into a crash — fall through to the raw message.\n }\n }\n\n return raw\n}\n","import pg from 'pg'\nimport { DB_CONNECT_TIMEOUT_MS } from './constants.js'\n\nexport type QueryFn = (dbUrl: string, sql: string, params?: unknown[]) => Promise<Record<string, unknown>[]>\n\n/**\n * Resolve the bound on establishing a connection (ms).\n *\n * SUPAFORGE_CONNECT_TIMEOUT is in seconds, so a network that legitimately\n * needs longer than the default can raise it without a code change. A\n * malformed or non-positive value falls back to the default rather than\n * forwarding something `pg` would treat as \"wait forever\" — which is the very\n * failure this bound exists to prevent (issue #44).\n */\nexport function resolveConnectTimeoutMs(): number {\n const raw = process.env.SUPAFORGE_CONNECT_TIMEOUT\n if (raw) {\n const secs = Number(raw)\n if (Number.isFinite(secs) && secs > 0) return Math.round(secs * 1000)\n }\n return DB_CONNECT_TIMEOUT_MS\n}\n\n/**\n * Build `pg.Client` config with a connection bound always applied.\n *\n * Every client in the codebase goes through here so none can be constructed\n * without one. `queryTimeoutMs` is opt-in: it belongs on short probes, not on\n * a migration or restore that is legitimately slow.\n */\nexport function pgClientConfig(dbUrl: string, queryTimeoutMs?: number): pg.ClientConfig {\n const config: pg.ClientConfig = {\n connectionString: dbUrl,\n connectionTimeoutMillis: resolveConnectTimeoutMs(),\n }\n if (queryTimeoutMs !== undefined) {\n config.query_timeout = queryTimeoutMs\n }\n return config\n}\n\n/**\n * One pool per database, shared by every query in a run.\n *\n * `pgQuery` used to open and close a `pg.Client` per query, and each connection\n * costs several round trips before the query itself runs: TCP, startup, then\n * SCRAM authentication. Over a link with latency that dominated a diff — a full\n * run opened 47 connections for 574 round trips, and the storage check alone\n * opened 14 (issue #78). `schema-introspect.ts` already shared a pool for\n * snapshots; the diff path did not.\n *\n * `allowExitOnIdle` is what makes this safe to do without lifecycle plumbing\n * through every command: an idle pool does not hold the process open, so a CLI\n * that forgets to close one still exits. `closePgPools()` exists for tests and\n * for anywhere that wants the sockets gone at a known moment.\n */\nconst pools = new Map<string, pg.Pool>()\n\n/**\n * Concurrent checks share these, so a pool needs more than one connection —\n * but a diff is not a web server, and a Supabase pooler counts every one.\n */\nconst POOL_MAX = 4\n\nfunction poolFor(dbUrl: string): pg.Pool {\n const existing = pools.get(dbUrl)\n if (existing) return existing\n\n const pool = new pg.Pool({\n ...pgClientConfig(dbUrl),\n max: POOL_MAX,\n allowExitOnIdle: true,\n })\n // A pool emits 'error' for an idle client dropped by the server, and an\n // unhandled 'error' event would take the process down. Queries still reject\n // through their own promise, so this only has to stop the crash.\n pool.on('error', () => undefined)\n\n pools.set(dbUrl, pool)\n return pool\n}\n\nexport const pgQuery: QueryFn = async (dbUrl, sql, params) => {\n const { rows } = await poolFor(dbUrl).query(sql, params)\n return rows\n}\n\n/**\n * Run `fn` on one pooled connection inside a transaction that is always\n * rolled back — for reading what the server makes of something by creating it\n * as a temporary object, without leaving anything behind.\n */\nexport async function inRolledBackTransaction<T>(\n dbUrl: string,\n fn: (client: pg.PoolClient) => Promise<T>,\n): Promise<T> {\n const client = await poolFor(dbUrl).connect()\n try {\n await client.query('BEGIN')\n try {\n return await fn(client)\n } finally {\n await client.query('ROLLBACK').catch(() => undefined)\n }\n } finally {\n client.release()\n }\n}\n\n/** Close every pool this process opened. Safe to call more than once. */\nexport async function closePgPools(): Promise<void> {\n const open = [...pools.values()]\n pools.clear()\n await Promise.all(open.map(pool => pool.end().catch(() => undefined)))\n}\n","import { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport pg from 'pg'\nimport { pgClientConfig } from './db.js'\nimport { RUNTIME_DETECT_TIMEOUT_MS, CONTAINER_RM_TIMEOUT_MS, CONTAINER_START_TIMEOUT_MS } from './constants'\n\nconst defaultExecFile = promisify(execFile)\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Injected exec function for testability. */\nexport type ExecFn = (\n cmd: string,\n args: string[],\n opts?: { timeout?: number },\n) => Promise<{ stdout: string; stderr: string }>\n\n/** Injected PostgreSQL connect function for readiness polling. */\nexport type ConnectFn = (url: string) => Promise<void>\n\n// ─── Constants ───────────────────────────────────────────────────────────────\n\n/** Default PostgreSQL image used for local containers. */\nexport const PG_IMAGE = 'docker.io/library/postgres:17'\n\n/** Default host port for the local PostgreSQL container. */\nexport const DEFAULT_LOCAL_PORT = 5432\n\n/** Default container name. */\nexport const CONTAINER_NAME = 'supaforge-local-pg'\n\n/** Default credentials for the local container. */\nexport const LOCAL_PG_USER = 'postgres'\nexport const LOCAL_PG_PASSWORD = 'postgres'\n\n/** Maximum retries when waiting for PostgreSQL readiness. */\nexport const READINESS_RETRIES = 30\n\n/** Delay between readiness checks (ms). */\nexport const READINESS_INTERVAL_MS = 2000\n\n// ─── Default implementations ────────────────────────────────────────────────\n\nasync function defaultConnectFn(url: string): Promise<void> {\n const client = new pg.Client(pgClientConfig(url))\n await client.connect()\n await client.end()\n}\n\n// ─── Container Runtime Detection ─────────────────────────────────────────────\n\nexport type ContainerRuntime = 'podman' | 'docker'\n\n/**\n * Detect the available container runtime.\n * Prefers podman (rootless, daemonless) over docker.\n * Returns null if neither is available.\n */\nexport async function detectRuntime(execFn: ExecFn = defaultExecFile): Promise<ContainerRuntime | null> {\n for (const rt of ['podman', 'docker'] as const) {\n try {\n await execFn(rt, ['--version'], { timeout: RUNTIME_DETECT_TIMEOUT_MS })\n return rt\n } catch {\n continue\n }\n }\n return null\n}\n\n// ─── Container Lifecycle ─────────────────────────────────────────────────────\n\nexport interface StartLocalPgOptions {\n /** Container runtime to use. Auto-detected if not provided. */\n runtime?: ContainerRuntime\n /** Host port to bind (default: 5432). */\n port?: number\n /** PostgreSQL password (default: 'postgres'). */\n password?: string\n /** Container name (default: 'supaforge-local-pg'). */\n name?: string\n /** PostgreSQL image (default: PG_IMAGE). */\n image?: string\n /** Injected exec function for testability. */\n execFn?: ExecFn\n /** Injected connect function for testability. */\n connectFn?: ConnectFn\n}\n\nexport interface LocalPgInfo {\n runtime: ContainerRuntime\n containerName: string\n port: number\n url: string\n}\n\n/**\n * Start a local PostgreSQL container using the detected runtime.\n *\n * Uses tmpfs for ephemeral storage (fast, no disk writes).\n * Waits for PostgreSQL to accept connections before returning.\n */\nexport async function startLocalPg(options: StartLocalPgOptions = {}): Promise<LocalPgInfo> {\n const exec = options.execFn ?? defaultExecFile\n const connect = options.connectFn ?? defaultConnectFn\n const runtime = options.runtime ?? await detectRuntime(exec)\n if (!runtime) {\n throw new Error(\n 'No container runtime found. Install Podman (recommended) or Docker.\\n' +\n ' Podman: https://podman.io/docs/installation\\n' +\n ' Docker: https://docs.docker.com/engine/install/',\n )\n }\n\n const port = options.port ?? DEFAULT_LOCAL_PORT\n const password = options.password ?? LOCAL_PG_PASSWORD\n const name = options.name ?? CONTAINER_NAME\n const image = options.image ?? PG_IMAGE\n\n // Check if container already exists and is running\n const existing = await getContainerStatus(runtime, name, exec)\n if (existing === 'running') {\n return {\n runtime,\n containerName: name,\n port,\n url: buildLocalUrl(port, password),\n }\n }\n\n // Remove stopped container with same name\n if (existing === 'stopped') {\n await exec(runtime, ['rm', '-f', name], { timeout: CONTAINER_RM_TIMEOUT_MS })\n }\n\n // Start the container\n const args = [\n 'run', '-d',\n '--name', name,\n '-p', `${port}:5432`,\n '-e', `POSTGRES_PASSWORD=${password}`,\n '-e', `POSTGRES_USER=${LOCAL_PG_USER}`,\n '--tmpfs', '/var/lib/postgresql/data',\n '--health-cmd', `pg_isready -U ${LOCAL_PG_USER}`,\n '--health-interval', '5s',\n '--health-timeout', '5s',\n '--health-retries', '20',\n '--health-start-period', '10s',\n image,\n ]\n\n try {\n await exec(runtime, args, { timeout: CONTAINER_START_TIMEOUT_MS })\n } catch (err) {\n throw new Error(\n `Failed to start PostgreSQL container via ${runtime}: ${(err as Error).message}`,\n )\n }\n\n // Wait for readiness using actual pg connection\n const url = buildLocalUrl(port, password)\n await waitForPg(url, connect)\n\n return { runtime, containerName: name, port, url }\n}\n\n/**\n * Stop and remove the local PostgreSQL container.\n */\nexport async function stopLocalPg(\n runtime?: ContainerRuntime,\n name: string = CONTAINER_NAME,\n execFn: ExecFn = defaultExecFile,\n): Promise<void> {\n const rt = runtime ?? await detectRuntime(execFn)\n if (!rt) return\n\n try {\n await execFn(rt, ['rm', '-f', name], { timeout: CONTAINER_RM_TIMEOUT_MS })\n } catch {\n // Container may not exist — ignore\n }\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nasync function getContainerStatus(\n runtime: ContainerRuntime,\n name: string,\n execFn: ExecFn,\n): Promise<'running' | 'stopped' | 'none'> {\n try {\n const { stdout } = await execFn(\n runtime,\n ['inspect', '--format', '{{.State.Running}}', name],\n { timeout: RUNTIME_DETECT_TIMEOUT_MS },\n )\n return stdout.trim() === 'true' ? 'running' : 'stopped'\n } catch {\n return 'none'\n }\n}\n\nfunction buildLocalUrl(port: number, password: string): string {\n return `postgres://${LOCAL_PG_USER}:${password}@localhost:${port}/postgres`\n}\n\n/**\n * Poll PostgreSQL until it accepts connections.\n * Uses actual pg.Client connection rather than relying on container health checks\n * (which may not work on all runtimes).\n */\nasync function waitForPg(url: string, connectFn: ConnectFn): Promise<void> {\n for (let i = 0; i < READINESS_RETRIES; i++) {\n try {\n await connectFn(url)\n return\n } catch {\n await sleep(READINESS_INTERVAL_MS)\n }\n }\n throw new Error(\n `PostgreSQL at ${url} did not become ready within ${READINESS_RETRIES * READINESS_INTERVAL_MS / 1000}s`,\n )\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n","import pg from 'pg'\nimport { detectRuntime } from './local-pg.js'\nimport { pgClientConfig, resolveConnectTimeoutMs } from './db.js'\nimport { DB_PROBE_TIMEOUT_MS } from './constants.js'\nimport { ok, warn, dim, cmd, bold } from './ui.js'\nimport { redactUrls, describeFailure } from './utils/error.js'\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Result of a single connectivity check. */\nexport interface ConnCheckResult {\n reachable: boolean\n version?: string\n error?: string\n}\n\n/** Outcome of a single preflight check (DB connectivity or custom). */\nexport interface CheckEntry {\n label: string\n passed: boolean\n detail?: string\n error?: string\n hints?: string[]\n}\n\n/** Full report returned by Preflight.run(). */\nexport interface PreflightReport {\n passed: boolean\n checks: CheckEntry[]\n}\n\n/** Supabase CLI default PostgreSQL port. */\nconst SUPABASE_LOCAL_PORT = '54322'\n\n/** Standard PostgreSQL port. */\nconst DEFAULT_PG_PORT = '5432'\n\n// ─── Standalone helpers (remain exported for direct use / tests) ─────────────\n\n/**\n * `pg`'s messages for the two bounds this module sets. Neither says what was\n * being waited for, and \"timeout expired\" in particular reads like a bug\n * rather than a diagnosis.\n */\nconst CONNECT_TIMEOUT_RE = /timeout expired|connection timeout/i\nconst QUERY_TIMEOUT_RE = /query read timeout/i\n\n/**\n * Replace a bare driver timeout with something that says which wait elapsed.\n *\n * Left untouched when it is not one of ours: a server-side `statement_timeout`\n * or an OS-level ETIMEDOUT is a different failure and already reads clearly.\n */\nexport function describeTimeout(message: string, connectTimeoutMs: number, probeTimeoutMs: number): string {\n if (CONNECT_TIMEOUT_RE.test(message)) {\n return `timed out after ${Math.round(connectTimeoutMs / 1000)}s connecting — the host accepted the connection but never completed the handshake`\n }\n if (QUERY_TIMEOUT_RE.test(message)) {\n return `timed out after ${Math.round(probeTimeoutMs / 1000)}s waiting for server response — connected, but the server did not answer`\n }\n return message\n}\n\n/**\n * Test that a PostgreSQL database is reachable and return the server version.\n *\n * Both waits are bounded. Without that, a host that accepts the connection and\n * then goes silent blocks here forever, and the command produces no output at\n * all past the `Checks:` header (issue #44).\n */\nexport async function checkConnection(dbUrl: string): Promise<ConnCheckResult> {\n const connectTimeoutMs = resolveConnectTimeoutMs()\n let client: pg.Client | undefined\n try {\n client = new pg.Client(pgClientConfig(dbUrl, DB_PROBE_TIMEOUT_MS))\n await client.connect()\n const { rows } = await client.query('SHOW server_version')\n const version = (rows[0] as Record<string, string>).server_version\n return { reachable: true, version }\n } catch (err) {\n return {\n reachable: false,\n error: describeTimeout(describeFailure(err), connectTimeoutMs, DB_PROBE_TIMEOUT_MS),\n }\n } finally {\n // A client that timed out mid-handshake still holds an open socket, which\n // keeps the event loop alive and hangs the process after the report has\n // already printed. end() on a never-connected client is a no-op, and a\n // failure closing it must not mask the real error above.\n try {\n await client?.end()\n } catch {\n // ignore\n }\n }\n}\n\n/** Errors that indicate the server IS running but rejecting the connection. */\nconst SERVER_REACHABLE_RE = /password authentication failed|does not exist|database .* does not exist|SSL.*required|no pg_hba\\.conf entry/i\n\n/**\n * Build context-aware hints when a local PostgreSQL is not reachable.\n * Detects Supabase CLI port, available container runtimes, etc.\n *\n * When `error` is provided and indicates the server IS running (auth failure,\n * missing database, SSL rejection), startup hints are suppressed in favour of\n * configuration hints.\n */\nexport async function buildLocalHints(dbUrl: string, error?: string): Promise<string[]> {\n const hints: string[] = []\n try {\n const urlObj = new URL(dbUrl)\n const isSupabasePort = urlObj.port === SUPABASE_LOCAL_PORT\n const isLocal = ['localhost', '127.0.0.1', '::1', ''].includes(urlObj.hostname)\n\n if (!isLocal) return hints\n\n // Server is reachable but rejecting — suggest config fixes, not startup.\n if (error && SERVER_REACHABLE_RE.test(error)) {\n hints.push(`Check the username and password in your database URL.`)\n if (isSupabasePort) {\n hints.push(`Port ${SUPABASE_LOCAL_PORT} is the Supabase CLI default. The default password is \"postgres\".`)\n }\n return hints\n }\n\n if (isSupabasePort) {\n hints.push(`Port ${SUPABASE_LOCAL_PORT} is the Supabase CLI default. Run ${cmd('\"supabase start\"')} to start your local Supabase instance.`)\n }\n\n const runtime = await detectRuntime()\n if (runtime) {\n hints.push(`${bold(runtime)} detected — you can start a PostgreSQL container manually.`)\n }\n\n if (!isSupabasePort) {\n hints.push(`Start PostgreSQL manually on port ${urlObj.port || DEFAULT_PG_PORT}.`)\n }\n } catch {\n // Invalid URL — no hints\n }\n return hints\n}\n\n/**\n * Hints for a connection that was bounded rather than refused.\n *\n * These apply to any host, unlike the local-startup hints — a stalled server\n * is just as likely to be a remote one behind a dropped tunnel, which is the\n * case that motivated bounding the wait at all (issue #44).\n */\nexport function buildTimeoutHints(): string[] {\n return [\n 'The host is listening but the database did not answer.',\n 'Check the database process is running and not paused, restarting, or overloaded.',\n 'Over a VPN or tunnel, check the connection is still up.',\n `Raise the bound with ${cmd('SUPAFORGE_CONNECT_TIMEOUT')} (in seconds) if the link is simply slow.`,\n ]\n}\n\n/**\n * Pick the right hints for a failed connection.\n *\n * A timeout and a refusal need different advice, and the local-startup hints\n * are actively misleading for a remote host that stalled.\n */\nexport async function buildConnectionHints(dbUrl: string, error?: string): Promise<string[]> {\n if (error && /timed out after \\d+s/.test(error)) return buildTimeoutHints()\n return buildLocalHints(dbUrl, error)\n}\n\n// ─── Preflight class ─────────────────────────────────────────────────────────\n\ntype LogFn = (msg: string) => void\n\n/**\n * Render a transient \"in progress\" line, or clear it when passed null.\n *\n * Separate from LogFn because these lines are overwritten rather than kept:\n * on a TTY the finished result replaces them, and off a TTY they are dropped\n * entirely so piped output and CI logs stay one line per check.\n */\nexport type PendingFn = (msg: string | null) => void\n\nconst defaultPending: PendingFn = (msg) => {\n if (!process.stdout.isTTY) return\n process.stdout.write(msg === null ? '\\r\\u001b[2K' : `\\r\\u001b[2K${msg}`)\n}\n\n/** Queued database to check during run(). */\ninterface DbEntry {\n label: string\n envName: string\n dbUrl: string\n}\n\n/** Custom check callback. Return null on success, or an error string on failure. */\nexport type CustomCheckFn = () => Promise<{ error?: string; detail?: string; hints?: string[] }>\n\n/** Queued custom check. */\ninterface CustomEntry {\n label: string\n fn: CustomCheckFn\n}\n\n/**\n * Composable preflight check runner.\n *\n * Usage:\n * ```ts\n * const pre = new Preflight('Diff preflight checks', (m) => this.log(m))\n * pre.addDatabase('Source', 'local', sourceUrl)\n * pre.addDatabase('Target', 'prod', targetUrl)\n * const report = await pre.run()\n * if (!report.passed) this.error('Aborted.', { exit: 1 })\n * ```\n *\n * For commands with extra checks (e.g. clone's pg_dump compat):\n * ```ts\n * pre.addCheck('pg_dump compatibility', async () => { ... })\n * ```\n */\nexport class Preflight {\n private readonly title: string\n private readonly log: LogFn\n private readonly pending: PendingFn\n private readonly databases: DbEntry[] = []\n private readonly customs: CustomEntry[] = []\n private readonly infoLines: Array<{ label: string; value: string }> = []\n\n constructor(title: string, log: LogFn, pending: PendingFn = defaultPending) {\n this.title = title\n this.log = log\n this.pending = pending\n }\n\n /** Register a database connectivity check. */\n addDatabase(label: string, envName: string, dbUrl: string): this {\n this.databases.push({ label, envName, dbUrl })\n return this\n }\n\n /** Add an informational line to the header (displayed after database lines). */\n addInfo(label: string, value: string): this {\n this.infoLines.push({ label, value })\n return this\n }\n\n /** Register a custom check (runs after all DB connectivity checks). */\n addCheck(label: string, fn: CustomCheckFn): this {\n this.customs.push({ label, fn })\n return this\n }\n\n /** Execute all registered checks, render results, and return the report. */\n async run(): Promise<PreflightReport> {\n const entries: CheckEntry[] = []\n const log = this.log\n\n // Header\n log(`\\n ${bold(this.title)}\\n`)\n for (const db of this.databases) {\n log(` ${db.label}: ${db.envName} ${dim(`(${redactUrls(db.dbUrl)})`)}`)\n }\n for (const info of this.infoLines) {\n log(` ${info.label}: ${info.value}`)\n }\n log('')\n log(' Checks:')\n\n // Database connectivity checks\n for (const db of this.databases) {\n // Named before the wait, not after: a connection that is merely slow\n // otherwise leaves the header on screen with no clue which of the two\n // environments is holding things up (issue #44).\n // The label is already the noun — \"Database\", \"Target\", \"Source\" — so\n // appending \"database\" gave \"Database database reachable\" (issue #97).\n this.pending(` ${dim(`… connecting to ${db.label.toLowerCase()}`)}`)\n const result = await checkConnection(db.dbUrl)\n this.pending(null)\n if (result.reachable) {\n log(` ${ok('✓')} ${db.label} reachable ${dim(`(PostgreSQL ${result.version})`)}`)\n entries.push({ label: db.label, passed: true, detail: `PostgreSQL ${result.version}` })\n } else {\n log(` ${warn('✗')} ${db.label} not reachable: ${redactUrls(describeFailure(result.error))}`)\n const hints = await buildConnectionHints(db.dbUrl, result.error)\n if (hints.length > 0) {\n log(`\\n ${dim('Hints:')}`)\n for (const h of hints) log(` ${dim('•')} ${h}`)\n }\n entries.push({ label: db.label, passed: false, error: result.error, hints })\n }\n }\n\n // Custom checks\n for (const custom of this.customs) {\n this.pending(` ${dim(`… ${custom.label}`)}`)\n const result = await custom.fn()\n this.pending(null)\n if (!result.error) {\n const suffix = result.detail ? ` ${dim(result.detail)}` : ''\n log(` ${ok('✓')} ${custom.label}${suffix}`)\n entries.push({ label: custom.label, passed: true, detail: result.detail })\n } else {\n log(` ${warn('✗')} ${custom.label}: ${redactUrls(describeFailure(result.error))}`)\n if (result.hints?.length) {\n log(`\\n ${dim('Hints:')}`)\n for (const h of result.hints) log(` ${dim('•')} ${h}`)\n }\n entries.push({ label: custom.label, passed: false, error: result.error, hints: result.hints })\n }\n }\n\n const passed = entries.every(e => e.passed)\n log('')\n if (!passed) {\n log(` ${warn('Some checks failed.')} Fix the issues above first.\\n`)\n } else {\n log(` ${ok('All checks passed.')}\\n`)\n }\n\n return { passed, checks: entries }\n }\n}\n","import type { EnvironmentConfig, SupaForgeConfig } from '../types/config'\nimport type { TableFilter } from '../utils/table-filter'\nimport type { DriftIssue, CheckName } from '../types/drift'\n\nexport interface CheckContext {\n /**\n * Which tables this run is scoped to, resolved from `checks.tables` /\n * `checks.excludeTables` and the `--tables` / `--exclude-tables` flags.\n *\n * Only the schema and data layers act on it — they are the ones backed by\n * @dbdiff/cli, which is where the table concept exists (issue #43). Absent\n * or empty means every table, which is the default.\n */\n tableFilter?: TableFilter\n /**\n * Optional sink for sub-check progress, e.g. the table counter emitted\n * during a long schema diff (issue #29). Checks that have nothing\n * fine-grained to report simply ignore it.\n */\n onDetail?: (detail: string) => void\n source: EnvironmentConfig\n target: EnvironmentConfig\n config: SupaForgeConfig\n}\n\n/**\n * Thrown by a check that cannot run — missing credentials, an absent\n * extension, nothing configured to compare.\n *\n * Checks used to signal this by returning `[]`, which is the same value a\n * genuinely clean scan returns. The distinction was lost before it reached the\n * scanner, so a layer that never ran rendered as a green zero-issue pass\n * (issue #42). Throwing keeps `scan()` returning plain issues while giving the\n * scanner something it cannot mistake for a result.\n *\n * A skip is a normal outcome, not a failure: it carries no stack for the user\n * and is reported separately from errored checks.\n */\nexport class CheckSkipped extends Error {\n /** Distinguishes a skip from a genuine error across module boundaries. */\n override readonly name = 'CheckSkipped'\n\n constructor(reason: string) {\n super(reason)\n }\n}\n\n/**\n * Name-based rather than `instanceof`, which fails when two copies of the\n * module are loaded — a real possibility with bundled output and linked\n * packages.\n */\nexport function isCheckSkipped(err: unknown): err is CheckSkipped {\n return err instanceof Error && err.name === 'CheckSkipped'\n}\n\n/**\n * SQLSTATEs that mean the thing queried isn't there: no such table or view\n * (42P01), schema (3F000) or function (42883). A project without pg_cron or\n * Realtime answers with one of these, and that is a genuine \"nothing to\n * compare\".\n *\n * Nothing else is. A wrong password, a dropped connection or a permission\n * error read as \"nothing there\" made the source look empty — and the target's\n * webhooks, cron jobs and publications then looked extra and were dropped.\n */\nconst MISSING_OBJECT_CODES = new Set(['42P01', '3F000', '42883'])\n\nexport function isMissingObject(err: unknown): boolean {\n const code = (err as { code?: unknown } | null)?.code\n return typeof code === 'string' && MISSING_OBJECT_CODES.has(code)\n}\n\n/** Run a read that may legitimately find nothing, returning `absent` only then. */\nexport async function readOrAbsent<T>(read: () => Promise<T>, absent: T): Promise<T> {\n try {\n return await read()\n } catch (err) {\n if (isMissingObject(err)) return absent\n throw err\n }\n}\n\nexport abstract class Check {\n abstract readonly name: CheckName\n abstract scan(ctx: CheckContext): Promise<DriftIssue[]>\n}\n","import { readdir as fsReaddir } from 'node:fs/promises'\nimport type { QueryFn } from '../db.js'\nimport { pgQuery } from '../db.js'\nimport type { DriftIssue } from '../types/drift.js'\nimport { MIGRATIONS_TABLE } from '../constants.js'\nimport { quoteLiteral } from '../utils/sql.js'\nimport { Check, CheckSkipped, readOrAbsent, type CheckContext } from './base.js'\nimport type { MigrationsMode } from '../types/config.js'\n\nexport const DEFAULT_MIGRATIONS_DIR = 'supabase/migrations'\n\nconst MIGRATIONS_SQL = `\n SELECT version, name\n FROM ${MIGRATIONS_TABLE}\n ORDER BY version\n`\n\ninterface MigrationRecord {\n version: string\n name: string | null\n}\n\nexport interface LocalMigration {\n version: string\n name: string\n filename: string\n}\n\nexport type ReadDirFn = (dir: string) => Promise<string[]>\n\nconst defaultReadDir: ReadDirFn = async (dir) => {\n const entries = await fsReaddir(dir)\n return entries as string[]\n}\n\nexport class MigrationsCheck extends Check {\n readonly name = 'migrations' as const\n\n constructor(\n private queryFn: QueryFn = pgQuery,\n private readDirFn: ReadDirFn = defaultReadDir,\n ) {\n super()\n }\n\n async scan(ctx: CheckContext): Promise<DriftIssue[]> {\n const dir = ctx.config.checks?.migrations?.dir ?? DEFAULT_MIGRATIONS_DIR\n const mode = resolveMigrationsMode(ctx.config.checks?.migrations?.mode)\n\n // Nothing to read or query when the check is switched off entirely. It is\n // still reported as skipped rather than clean, so turning it off does not\n // look like a layer that passed (issue #42).\n if (mode === 'ignore') throw new CheckSkipped(\"checks.migrations.mode is 'ignore'\")\n\n const [local, db] = await Promise.all([\n readLocalMigrations(dir, this.readDirFn),\n this.fetchDbMigrations(ctx.target.dbUrl),\n ])\n\n return diffMigrations(local, db, mode)\n }\n\n private async fetchDbMigrations(dbUrl: string): Promise<MigrationRecord[]> {\n // No schema_migrations table means no records; any other failure is an error.\n return readOrAbsent(async () => await this.queryFn(dbUrl, MIGRATIONS_SQL) as unknown as MigrationRecord[], [])\n }\n}\n\n/**\n * Parse a migration filename into version + name.\n * Handles both `20240101000000_create_users.sql` and `001_initial_schema.sql`.\n */\nexport function parseFilename(filename: string): { version: string; name: string } | null {\n if (!filename.endsWith('.sql')) return null\n const match = filename.replace(/\\.sql$/, '').match(/^(\\d+)_(.+)$/)\n if (!match) return null\n return { version: match[1], name: match[2] }\n}\n\nexport async function readLocalMigrations(\n dir: string,\n readDirFn: ReadDirFn = defaultReadDir,\n): Promise<LocalMigration[]> {\n let files: string[]\n try {\n files = (await readDirFn(dir)).filter(f => f.endsWith('.sql')).sort()\n } catch {\n return []\n }\n\n const migrations: LocalMigration[] = []\n for (const filename of files) {\n const parsed = parseFilename(filename)\n if (!parsed) continue\n migrations.push({ ...parsed, filename })\n }\n return migrations\n}\n\nconst MIGRATIONS_MODES: MigrationsMode[] = ['auto', 'warn', 'ignore']\n\n/**\n * Normalise the configured mode.\n *\n * An unrecognised value falls back to 'auto' rather than throwing — a typo in\n * a config file should not take the whole scan down, and 'auto' is the least\n * surprising default.\n */\nexport function resolveMigrationsMode(raw: unknown): MigrationsMode {\n return MIGRATIONS_MODES.includes(raw as MigrationsMode) ? (raw as MigrationsMode) : 'auto'\n}\n\n/**\n * One INFO describing a project that applies migrations outside the Supabase\n * CLI, instead of one warning per file.\n *\n * schema_migrations is a Supabase CLI convention, not a database requirement.\n * Projects that apply migrations via psql or the SQL editor never populate it,\n * so every local file was reported as \"unapplied\" on every scan — all false\n * positives, and enough of them to drown the rest of the layer (issue #31).\n */\nfunction untrackedWorkflowIssue(local: LocalMigration[]): DriftIssue {\n const noun = local.length === 1 ? 'file' : 'files'\n return {\n id: 'migration-workflow-untracked',\n check: 'migrations',\n severity: 'info',\n title: `Untracked migration workflow: ${local.length} local ${noun}, none recorded`,\n description:\n `${MIGRATIONS_TABLE} is empty while ${local.length} migration ${noun} exist locally. ` +\n 'That is the normal shape for a project applying migrations outside the Supabase CLI ' +\n '(psql, the SQL editor, or another tool), so each file is not reported separately. ' +\n 'Run `supaforge migrate baseline` to record them as applied, or set ' +\n 'checks.migrations.mode to \"warn\" to report every file, or \"ignore\" to disable this check.',\n sourceValue: `${local.length} local migration ${noun}`,\n }\n}\n\nexport function diffMigrations(\n local: LocalMigration[],\n db: MigrationRecord[],\n mode: MigrationsMode = 'auto',\n): DriftIssue[] {\n if (mode === 'ignore') return []\n\n const issues: DriftIssue[] = []\n const dbMap = new Map(db.map(r => [r.version, r]))\n const localMap = new Map(local.map(m => [m.version, m]))\n const unapplied = local.filter(m => !dbMap.has(m.version))\n\n // Nothing tracked at all, but files on disk: report the workflow once\n // rather than each file. Requires db to be *entirely* empty — a project\n // that tracks some migrations and missed others has genuine drift.\n if (mode === 'auto' && db.length === 0 && unapplied.length > 0) {\n issues.push(untrackedWorkflowIssue(local))\n } else {\n for (const migration of unapplied) {\n issues.push({\n id: `migration-unapplied-${migration.version}`,\n check: 'migrations',\n severity: 'warning',\n title: `Unapplied migration: ${migration.filename}`,\n description: `Migration file \"${migration.filename}\" exists locally but is not recorded in ${MIGRATIONS_TABLE}.`,\n sourceValue: migration.filename,\n sql: {\n up: markAppliedSql(migration.version, migration.name),\n down: `DELETE FROM ${MIGRATIONS_TABLE} WHERE version = ${quoteLiteral(migration.version)};`,\n },\n })\n }\n }\n\n // DB records without local files (untracked)\n for (const [version, record] of dbMap) {\n if (!localMap.has(version)) {\n issues.push({\n id: `migration-untracked-${version}`,\n check: 'migrations',\n severity: 'info',\n title: `Untracked migration: ${version}`,\n description: `Migration version \"${version}\"${record.name ? ` (${record.name})` : ''} is recorded in the database but has no corresponding local file.`,\n targetValue: record,\n })\n }\n }\n\n return issues\n}\n\n/** SQL to insert a migration record into schema_migrations (mark as applied). */\nfunction markAppliedSql(version: string, name: string): string {\n return [\n `INSERT INTO ${MIGRATIONS_TABLE} (version, name, statements)`,\n `VALUES (${quoteLiteral(version)}, ${quoteLiteral(name)}, '{}')`,\n `ON CONFLICT (version) DO NOTHING;`,\n ].join('\\n')\n}\n","/**\n * Shared SQL escaping utilities for generating safe SQL strings.\n *\n * Used across checks, snapshots, and migration layers to avoid\n * duplicating quoting logic.\n */\n\n/**\n * Quote a schema-qualified or bare identifier for safe inclusion in SQL.\n * Handles `schema.table` → `\"schema\".\"table\"` and bare `table` → `\"table\"`.\n */\nexport function quoteIdent(name: string): string {\n return name.split('.').map(p => `\"${p.replace(/\"/g, '\"\"')}\"`).join('.')\n}\n\n/**\n * Quote a bare identifier (single name, no dot-splitting).\n * Use for column/table names that should never be schema-qualified.\n */\nexport function quoteName(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`\n}\n\n/**\n * Quote a string value for safe inclusion as a SQL literal.\n * Escapes single quotes by doubling them.\n */\nexport function quoteLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`\n}\n\n/**\n * Convert a JavaScript value to a SQL literal representation.\n * Handles null, boolean, number, array, and string types.\n */\nexport function sqlLiteral(val: unknown): string {\n if (val === null || val === undefined) return 'NULL'\n if (typeof val === 'boolean') return val ? 'true' : 'false'\n if (typeof val === 'number') return String(val)\n if (Array.isArray(val)) return `ARRAY[${val.map(v => quoteLiteral(String(v))).join(', ')}]`\n return quoteLiteral(String(val))\n}\n"],"mappings":";;;;;;;;;;;;;;;AAIA,IAAM,YAAY;AASX,SAAS,WAAW,SAAyB;AAClD,SAAO,QAAQ,QAAQ,WAAW,CAAC,GAAG,QAAgB,SAAiB;AACrE,UAAM,SAAS,KAAK,YAAY,GAAG;AACnC,QAAI,WAAW,GAAI,QAAO,SAAS;AACnC,UAAM,QAAQ,KAAK,MAAM,GAAG,MAAM;AAClC,UAAM,WAAW,KAAK,MAAM,MAAM;AAClC,UAAM,WAAW,MAAM,QAAQ,GAAG;AAClC,QAAI,aAAa,GAAI,QAAO,SAAS;AACrC,WAAO,SAAS,MAAM,MAAM,GAAG,QAAQ,IAAI,SAAS;AAAA,EACtD,CAAC;AACH;AAGO,IAAM,oBAAoB;AAe1B,SAAS,gBAAgB,KAAs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