@akal/supaforge 0.0.0-stage → 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 (97) hide show
  1. package/README.md +350 -2
  2. package/bin/dev.js +10 -0
  3. package/bin/run.js +18 -0
  4. package/dist/base-command.d.ts +135 -0
  5. package/dist/base-command.js +9 -0
  6. package/dist/base-command.js.map +1 -0
  7. package/dist/branch-C4ndfoj5.d.ts +58 -0
  8. package/dist/chunk-2SELREHW.js +156 -0
  9. package/dist/chunk-2SELREHW.js.map +1 -0
  10. package/dist/chunk-3HGAV5CC.js +2073 -0
  11. package/dist/chunk-3HGAV5CC.js.map +1 -0
  12. package/dist/chunk-4IVN7QVY.js +632 -0
  13. package/dist/chunk-4IVN7QVY.js.map +1 -0
  14. package/dist/chunk-6LJERPUN.js +499 -0
  15. package/dist/chunk-6LJERPUN.js.map +1 -0
  16. package/dist/chunk-6Q7MHFBM.js +13 -0
  17. package/dist/chunk-6Q7MHFBM.js.map +1 -0
  18. package/dist/chunk-6WAMNZLO.js +336 -0
  19. package/dist/chunk-6WAMNZLO.js.map +1 -0
  20. package/dist/chunk-7NAZGZPV.js +868 -0
  21. package/dist/chunk-7NAZGZPV.js.map +1 -0
  22. package/dist/chunk-BLKJWDTL.js +153 -0
  23. package/dist/chunk-BLKJWDTL.js.map +1 -0
  24. package/dist/chunk-BUOWHE36.js +1311 -0
  25. package/dist/chunk-BUOWHE36.js.map +1 -0
  26. package/dist/chunk-DMIWAJRB.js +602 -0
  27. package/dist/chunk-DMIWAJRB.js.map +1 -0
  28. package/dist/chunk-DQQ5E563.js +64 -0
  29. package/dist/chunk-DQQ5E563.js.map +1 -0
  30. package/dist/chunk-G2DIPIYU.js +94 -0
  31. package/dist/chunk-G2DIPIYU.js.map +1 -0
  32. package/dist/chunk-GEHPTPNZ.js +240 -0
  33. package/dist/chunk-GEHPTPNZ.js.map +1 -0
  34. package/dist/chunk-GZREXCQZ.js +207 -0
  35. package/dist/chunk-GZREXCQZ.js.map +1 -0
  36. package/dist/chunk-MIRLB5JM.js +1292 -0
  37. package/dist/chunk-MIRLB5JM.js.map +1 -0
  38. package/dist/chunk-NTUASFQ3.js +248 -0
  39. package/dist/chunk-NTUASFQ3.js.map +1 -0
  40. package/dist/chunk-ORQJVE57.js +642 -0
  41. package/dist/chunk-ORQJVE57.js.map +1 -0
  42. package/dist/chunk-SC2XHGIS.js +122 -0
  43. package/dist/chunk-SC2XHGIS.js.map +1 -0
  44. package/dist/chunk-SQPCWGQO.js +657 -0
  45. package/dist/chunk-SQPCWGQO.js.map +1 -0
  46. package/dist/chunk-UWAVXC57.js +916 -0
  47. package/dist/chunk-UWAVXC57.js.map +1 -0
  48. package/dist/commands/clone.d.ts +66 -0
  49. package/dist/commands/clone.js +416 -0
  50. package/dist/commands/clone.js.map +1 -0
  51. package/dist/commands/diff.d.ts +81 -0
  52. package/dist/commands/diff.js +23 -0
  53. package/dist/commands/diff.js.map +1 -0
  54. package/dist/commands/help.d.ts +32 -0
  55. package/dist/commands/help.js +36 -0
  56. package/dist/commands/help.js.map +1 -0
  57. package/dist/commands/hukam.d.ts +13 -0
  58. package/dist/commands/hukam.js +28 -0
  59. package/dist/commands/hukam.js.map +1 -0
  60. package/dist/commands/init.d.ts +47 -0
  61. package/dist/commands/init.js +388 -0
  62. package/dist/commands/init.js.map +1 -0
  63. package/dist/commands/mcp.d.ts +13 -0
  64. package/dist/commands/mcp.js +43 -0
  65. package/dist/commands/mcp.js.map +1 -0
  66. package/dist/commands/migrate/baseline.d.ts +24 -0
  67. package/dist/commands/migrate/baseline.js +69 -0
  68. package/dist/commands/migrate/baseline.js.map +1 -0
  69. package/dist/commands/migrate/create.d.ts +36 -0
  70. package/dist/commands/migrate/create.js +127 -0
  71. package/dist/commands/migrate/create.js.map +1 -0
  72. package/dist/commands/migrate/list.d.ts +23 -0
  73. package/dist/commands/migrate/list.js +110 -0
  74. package/dist/commands/migrate/list.js.map +1 -0
  75. package/dist/commands/migrate/run.d.ts +61 -0
  76. package/dist/commands/migrate/run.js +18 -0
  77. package/dist/commands/migrate/run.js.map +1 -0
  78. package/dist/commands/report.d.ts +27 -0
  79. package/dist/commands/report.js +210 -0
  80. package/dist/commands/report.js.map +1 -0
  81. package/dist/commands/restore.d.ts +26 -0
  82. package/dist/commands/restore.js +266 -0
  83. package/dist/commands/restore.js.map +1 -0
  84. package/dist/commands/snapshot.d.ts +33 -0
  85. package/dist/commands/snapshot.js +249 -0
  86. package/dist/commands/snapshot.js.map +1 -0
  87. package/dist/commands/sync.d.ts +16 -0
  88. package/dist/commands/sync.js +38 -0
  89. package/dist/commands/sync.js.map +1 -0
  90. package/dist/config-CTbeRlJk.d.ts +134 -0
  91. package/dist/help.d.ts +28 -0
  92. package/dist/help.js +64 -0
  93. package/dist/help.js.map +1 -0
  94. package/dist/index.d.ts +498 -0
  95. package/dist/index.js +147 -0
  96. package/dist/index.js.map +1 -0
  97. package/package.json +74 -4
@@ -0,0 +1,657 @@
1
+ import {
2
+ CONTAINER_RM_TIMEOUT_MS,
3
+ CONTAINER_START_TIMEOUT_MS,
4
+ DB_CONNECT_TIMEOUT_MS,
5
+ DB_PROBE_TIMEOUT_MS,
6
+ MIGRATIONS_TABLE,
7
+ RUNTIME_DETECT_TIMEOUT_MS,
8
+ bold,
9
+ cmd,
10
+ dim,
11
+ ok,
12
+ warn
13
+ } from "./chunk-6WAMNZLO.js";
14
+
15
+ // src/utils/error.ts
16
+ var DB_URL_RE = /\b((?:postgres(?:ql)?|mysql|mariadb):\/\/)(\S+)/g;
17
+ function redactUrls(message) {
18
+ return message.replace(DB_URL_RE, (_, scheme, rest) => {
19
+ const lastAt = rest.lastIndexOf("@");
20
+ if (lastAt === -1) return scheme + rest;
21
+ const creds = rest.slice(0, lastAt);
22
+ const hostPart = rest.slice(lastAt);
23
+ const colonIdx = creds.indexOf(":");
24
+ if (colonIdx === -1) return scheme + rest;
25
+ return scheme + creds.slice(0, colonIdx) + ":***" + hostPart;
26
+ });
27
+ }
28
+ var UNDESCRIBED_ERROR = "unknown error \u2014 no message reported";
29
+ function describeFailure(err) {
30
+ if (typeof err === "string") return err.trim() || UNDESCRIBED_ERROR;
31
+ const candidate = err;
32
+ const message = typeof candidate?.message === "string" ? candidate.message.trim() : "";
33
+ if (message) return message;
34
+ const code = typeof candidate?.code === "string" ? candidate.code.trim() : "";
35
+ if (code) return `${code} (no further detail reported)`;
36
+ const name = typeof candidate?.name === "string" ? candidate.name.trim() : "";
37
+ if (name && name !== "Error") return `${name} (no further detail reported)`;
38
+ if (err !== null && err !== void 0 && !(err instanceof Error)) {
39
+ const rendered = String(err).trim();
40
+ if (rendered && rendered !== "[object Object]") return rendered;
41
+ }
42
+ return UNDESCRIBED_ERROR;
43
+ }
44
+ function errMsg(err) {
45
+ return redactUrls(describeFailure(err));
46
+ }
47
+ var DiagnosticError = class extends Error {
48
+ constructor(message) {
49
+ super(message);
50
+ this.name = "DiagnosticError";
51
+ }
52
+ };
53
+ function isDiagnosticError(err) {
54
+ return err instanceof DiagnosticError || err instanceof Error && err.name === "DiagnosticError";
55
+ }
56
+ var CONNECTION_ERROR_PATTERNS = [
57
+ {
58
+ test: (m) => /ECONNREFUSED|Connection refused/i.test(m),
59
+ build: (host) => `Cannot connect to PostgreSQL at ${host} \u2014 the server does not appear to be running. Start it and try again.`
60
+ },
61
+ {
62
+ test: (m) => /ENOTFOUND|getaddrinfo/i.test(m),
63
+ build: (host) => `Cannot resolve hostname ${host} \u2014 check the database URL in your config.`
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
+ },
72
+ {
73
+ // Deliberately narrow. A bare /timeout/i also matches our own remediation
74
+ // text — "set SUPAFORGE_DBDIFF_TIMEOUT=600" contains "TIMEOUT" — which is
75
+ // how an accurate "Schema diff timed out after Ns" message was being
76
+ // rewritten into a wrong "check the host and port" one (issue #29).
77
+ // DiagnosticError below is the primary guard; this is defence in depth.
78
+ test: (m) => /ETIMEDOUT|connection timed out|timeout expired/i.test(m),
79
+ build: (host) => `Connection to ${host} timed out \u2014 verify the host and port are correct and that the server is reachable.`
80
+ },
81
+ {
82
+ test: (m) => /password authentication failed/i.test(m),
83
+ build: (host) => `Authentication failed for ${host} \u2014 check the username and password in your database URL.`
84
+ },
85
+ {
86
+ // Must stay anchored to "database ... does not exist" (Postgres SQLSTATE
87
+ // 3D000). A bare /does not exist/ is the same trap as the timeout pattern
88
+ // above: it matched dbdiff's own CLI complaint — The "--allow-destructive"
89
+ // option does not exist — and rewrote it into "Database does not exist on
90
+ // 127.0.0.1:5432", sending you off to check a database name that was fine
91
+ // while the real cause (an outdated @dbdiff/cli) went unmentioned.
92
+ test: (m) => /database\s+"[^"]*"\s+does not exist|3D000/i.test(m),
93
+ build: (host) => `Database does not exist on ${host} \u2014 verify the database name in your config.`
94
+ },
95
+ {
96
+ test: (m) => /SSL.*required|no pg_hba.conf entry/i.test(m),
97
+ build: (host) => `Connection rejected by ${host} \u2014 the server requires SSL or your IP is not allowed. Check pg_hba.conf and SSL settings.`
98
+ }
99
+ ];
100
+ function extractHost(dbUrl) {
101
+ try {
102
+ const url = new URL(dbUrl);
103
+ return url.port ? `${url.hostname}:${url.port}` : url.hostname;
104
+ } catch {
105
+ return "the configured host";
106
+ }
107
+ }
108
+ function friendlyDbError(err, dbUrl) {
109
+ const raw = errMsg(err);
110
+ if (isDiagnosticError(err)) return raw;
111
+ const host = dbUrl ? extractHost(dbUrl) : "the configured host";
112
+ for (const pattern of CONNECTION_ERROR_PATTERNS) {
113
+ try {
114
+ if (pattern.test(raw)) {
115
+ return pattern.build(host);
116
+ }
117
+ } catch {
118
+ }
119
+ }
120
+ return raw;
121
+ }
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
+
468
+ // src/checks/base.ts
469
+ var CheckSkipped = class extends Error {
470
+ /** Distinguishes a skip from a genuine error across module boundaries. */
471
+ name = "CheckSkipped";
472
+ constructor(reason) {
473
+ super(reason);
474
+ }
475
+ };
476
+ function isCheckSkipped(err) {
477
+ return err instanceof Error && err.name === "CheckSkipped";
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
+ }
492
+ var Check = class {
493
+ };
494
+
495
+ // src/checks/migrations.ts
496
+ import { readdir as fsReaddir } from "fs/promises";
497
+
498
+ // src/utils/sql.ts
499
+ function quoteIdent(name) {
500
+ return name.split(".").map((p) => `"${p.replace(/"/g, '""')}"`).join(".");
501
+ }
502
+ function quoteName(name) {
503
+ return `"${name.replace(/"/g, '""')}"`;
504
+ }
505
+ function quoteLiteral(value) {
506
+ return `'${value.replace(/'/g, "''")}'`;
507
+ }
508
+ function sqlLiteral(val) {
509
+ if (val === null || val === void 0) return "NULL";
510
+ if (typeof val === "boolean") return val ? "true" : "false";
511
+ if (typeof val === "number") return String(val);
512
+ if (Array.isArray(val)) return `ARRAY[${val.map((v) => quoteLiteral(String(v))).join(", ")}]`;
513
+ return quoteLiteral(String(val));
514
+ }
515
+
516
+ // src/checks/migrations.ts
517
+ var DEFAULT_MIGRATIONS_DIR = "supabase/migrations";
518
+ var MIGRATIONS_SQL = `
519
+ SELECT version, name
520
+ FROM ${MIGRATIONS_TABLE}
521
+ ORDER BY version
522
+ `;
523
+ var defaultReadDir = async (dir) => {
524
+ const entries = await fsReaddir(dir);
525
+ return entries;
526
+ };
527
+ var MigrationsCheck = class extends Check {
528
+ constructor(queryFn = pgQuery, readDirFn = defaultReadDir) {
529
+ super();
530
+ this.queryFn = queryFn;
531
+ this.readDirFn = readDirFn;
532
+ }
533
+ name = "migrations";
534
+ async scan(ctx) {
535
+ const dir = ctx.config.checks?.migrations?.dir ?? DEFAULT_MIGRATIONS_DIR;
536
+ const mode = resolveMigrationsMode(ctx.config.checks?.migrations?.mode);
537
+ if (mode === "ignore") throw new CheckSkipped("checks.migrations.mode is 'ignore'");
538
+ const [local, db] = await Promise.all([
539
+ readLocalMigrations(dir, this.readDirFn),
540
+ this.fetchDbMigrations(ctx.target.dbUrl)
541
+ ]);
542
+ return diffMigrations(local, db, mode);
543
+ }
544
+ async fetchDbMigrations(dbUrl) {
545
+ return readOrAbsent(async () => await this.queryFn(dbUrl, MIGRATIONS_SQL), []);
546
+ }
547
+ };
548
+ function parseFilename(filename) {
549
+ if (!filename.endsWith(".sql")) return null;
550
+ const match = filename.replace(/\.sql$/, "").match(/^(\d+)_(.+)$/);
551
+ if (!match) return null;
552
+ return { version: match[1], name: match[2] };
553
+ }
554
+ async function readLocalMigrations(dir, readDirFn = defaultReadDir) {
555
+ let files;
556
+ try {
557
+ files = (await readDirFn(dir)).filter((f) => f.endsWith(".sql")).sort();
558
+ } catch {
559
+ return [];
560
+ }
561
+ const migrations = [];
562
+ for (const filename of files) {
563
+ const parsed = parseFilename(filename);
564
+ if (!parsed) continue;
565
+ migrations.push({ ...parsed, filename });
566
+ }
567
+ return migrations;
568
+ }
569
+ var MIGRATIONS_MODES = ["auto", "warn", "ignore"];
570
+ function resolveMigrationsMode(raw) {
571
+ return MIGRATIONS_MODES.includes(raw) ? raw : "auto";
572
+ }
573
+ function untrackedWorkflowIssue(local) {
574
+ const noun = local.length === 1 ? "file" : "files";
575
+ return {
576
+ id: "migration-workflow-untracked",
577
+ check: "migrations",
578
+ severity: "info",
579
+ title: `Untracked migration workflow: ${local.length} local ${noun}, none recorded`,
580
+ description: `${MIGRATIONS_TABLE} is empty while ${local.length} migration ${noun} exist locally. That is the normal shape for a project applying migrations outside the Supabase CLI (psql, the SQL editor, or another tool), so each file is not reported separately. Run \`supaforge migrate baseline\` to record them as applied, or set checks.migrations.mode to "warn" to report every file, or "ignore" to disable this check.`,
581
+ sourceValue: `${local.length} local migration ${noun}`
582
+ };
583
+ }
584
+ function diffMigrations(local, db, mode = "auto") {
585
+ if (mode === "ignore") return [];
586
+ const issues = [];
587
+ const dbMap = new Map(db.map((r) => [r.version, r]));
588
+ const localMap = new Map(local.map((m) => [m.version, m]));
589
+ const unapplied = local.filter((m) => !dbMap.has(m.version));
590
+ if (mode === "auto" && db.length === 0 && unapplied.length > 0) {
591
+ issues.push(untrackedWorkflowIssue(local));
592
+ } else {
593
+ for (const migration of unapplied) {
594
+ issues.push({
595
+ id: `migration-unapplied-${migration.version}`,
596
+ check: "migrations",
597
+ severity: "warning",
598
+ title: `Unapplied migration: ${migration.filename}`,
599
+ description: `Migration file "${migration.filename}" exists locally but is not recorded in ${MIGRATIONS_TABLE}.`,
600
+ sourceValue: migration.filename,
601
+ sql: {
602
+ up: markAppliedSql(migration.version, migration.name),
603
+ down: `DELETE FROM ${MIGRATIONS_TABLE} WHERE version = ${quoteLiteral(migration.version)};`
604
+ }
605
+ });
606
+ }
607
+ }
608
+ for (const [version, record] of dbMap) {
609
+ if (!localMap.has(version)) {
610
+ issues.push({
611
+ id: `migration-untracked-${version}`,
612
+ check: "migrations",
613
+ severity: "info",
614
+ title: `Untracked migration: ${version}`,
615
+ description: `Migration version "${version}"${record.name ? ` (${record.name})` : ""} is recorded in the database but has no corresponding local file.`,
616
+ targetValue: record
617
+ });
618
+ }
619
+ }
620
+ return issues;
621
+ }
622
+ function markAppliedSql(version, name) {
623
+ return [
624
+ `INSERT INTO ${MIGRATIONS_TABLE} (version, name, statements)`,
625
+ `VALUES (${quoteLiteral(version)}, ${quoteLiteral(name)}, '{}')`,
626
+ `ON CONFLICT (version) DO NOTHING;`
627
+ ].join("\n");
628
+ }
629
+
630
+ export {
631
+ redactUrls,
632
+ describeFailure,
633
+ errMsg,
634
+ DiagnosticError,
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,
645
+ quoteIdent,
646
+ quoteName,
647
+ quoteLiteral,
648
+ sqlLiteral,
649
+ CheckSkipped,
650
+ isCheckSkipped,
651
+ readOrAbsent,
652
+ Check,
653
+ DEFAULT_MIGRATIONS_DIR,
654
+ MigrationsCheck,
655
+ readLocalMigrations
656
+ };
657
+ //# sourceMappingURL=chunk-SQPCWGQO.js.map