@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,632 @@
1
+ import {
2
+ sanitizeForReport
3
+ } from "./chunk-6Q7MHFBM.js";
4
+ import {
5
+ coverage,
6
+ formatSkips,
7
+ renderDetailed,
8
+ renderSummary
9
+ } from "./chunk-GEHPTPNZ.js";
10
+ import {
11
+ createDefaultRegistry,
12
+ scan,
13
+ summarizeByKind
14
+ } from "./chunk-3HGAV5CC.js";
15
+ import {
16
+ comparedSchemas,
17
+ proofScope,
18
+ proveConvergence,
19
+ residualHeldBack
20
+ } from "./chunk-DMIWAJRB.js";
21
+ import {
22
+ CHECK_META,
23
+ CHECK_NAMES,
24
+ describeTableFilter,
25
+ isFiltered,
26
+ planWork,
27
+ promote,
28
+ resolveTableFilter
29
+ } from "./chunk-UWAVXC57.js";
30
+ import {
31
+ renderTip
32
+ } from "./chunk-BLKJWDTL.js";
33
+ import {
34
+ BaseCommand
35
+ } from "./chunk-GZREXCQZ.js";
36
+ import {
37
+ isCloneDatabase,
38
+ sourceLooksLikeCloneOf
39
+ } from "./chunk-ORQJVE57.js";
40
+ import {
41
+ parseFlagList
42
+ } from "./chunk-DQQ5E563.js";
43
+ import {
44
+ Preflight,
45
+ describeFailure,
46
+ redactUrls
47
+ } from "./chunk-SQPCWGQO.js";
48
+ import {
49
+ CLONE_SKIP_FLAGS,
50
+ DEFAULT_IGNORE_SCHEMAS,
51
+ bold,
52
+ cmd,
53
+ dim,
54
+ ok,
55
+ schemaDiffIgnores,
56
+ warn
57
+ } from "./chunk-6WAMNZLO.js";
58
+
59
+ // src/commands/diff.ts
60
+ import { Flags } from "@oclif/core";
61
+
62
+ // src/ci.ts
63
+ function escapeData(value) {
64
+ return value.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
65
+ }
66
+ function escapeProperty(value) {
67
+ return escapeData(value).replace(/:/g, "%3A").replace(/,/g, "%2C");
68
+ }
69
+ function formatAnnotation(issue) {
70
+ const level = issue.severity === "critical" ? "error" : "warning";
71
+ const title = escapeProperty(issue.title);
72
+ const message = escapeData(issue.description);
73
+ return `::${level} title=${title}::${message}`;
74
+ }
75
+ function formatGitHubAnnotations(result) {
76
+ const lines = [];
77
+ for (const check of result.checks) {
78
+ for (const issue of check.issues) {
79
+ lines.push(formatAnnotation(issue));
80
+ }
81
+ }
82
+ return lines;
83
+ }
84
+ function exceeds(counts, failOn) {
85
+ if (failOn === "critical") return counts.critical > 0;
86
+ if (failOn === "warning") return counts.critical > 0 || counts.warning > 0;
87
+ return counts.total > 0;
88
+ }
89
+ function computeCiExitCode(result, failOn = "critical", opts = {}) {
90
+ const hasError = result.checks.some((c) => c.status === "error");
91
+ if (hasError) return 2;
92
+ const { drift, posture } = summarizeByKind(result.checks);
93
+ if (exceeds(drift, failOn)) return 1;
94
+ if (opts.failOnPosture && exceeds(posture, failOn)) return 1;
95
+ return 0;
96
+ }
97
+ function formatCiSummary(result) {
98
+ const criticalIssues = [];
99
+ const warningIssues = [];
100
+ const errors = [];
101
+ const skipped = [];
102
+ for (const check of result.checks ?? []) {
103
+ if (check?.status === "error") {
104
+ errors.push({ check: check.check, message: check.error ?? "Check failed with no error message" });
105
+ }
106
+ if (check?.status === "skipped") {
107
+ skipped.push({ check: check.check, reason: check.skipReason ?? "no reason given" });
108
+ }
109
+ for (const issue of check?.issues ?? []) {
110
+ const entry = { check: check.check, id: issue.id, title: issue.title };
111
+ if (issue.severity === "critical") {
112
+ criticalIssues.push(entry);
113
+ } else if (issue.severity === "warning") {
114
+ warningIssues.push(entry);
115
+ }
116
+ }
117
+ }
118
+ return {
119
+ timestamp: result.timestamp,
120
+ score: result.score,
121
+ postureScore: result.postureScore ?? null,
122
+ summary: result.summary,
123
+ errors,
124
+ skipped,
125
+ coverage: coverage(result),
126
+ criticalIssues,
127
+ warningIssues
128
+ };
129
+ }
130
+
131
+ // src/commands/diff.ts
132
+ function describeCheckOutcome(status, issueCount, skipReason) {
133
+ if (status === "error") return { glyph: warn("\u2717"), text: warn("error") };
134
+ if (status === "skipped") {
135
+ return { glyph: dim("\u25CB"), text: dim(`skipped \u2014 ${skipReason ?? "no reason given"}`) };
136
+ }
137
+ return { glyph: ok("\u2713"), text: `${issueCount} ${issueCount === 1 ? "issue" : "issues"}` };
138
+ }
139
+ var APPLY_ONLY_FLAGS = [
140
+ { flag: "prove", shapesThePlan: false },
141
+ { flag: "no-transaction", shapesThePlan: false },
142
+ { flag: "only", shapesThePlan: true },
143
+ { flag: "apply-posture", shapesThePlan: true },
144
+ { flag: "allow-destructive", shapesThePlan: true }
145
+ ];
146
+ function inertApplyFlags(flags) {
147
+ if (flags["apply"]) return [];
148
+ const dryRun = Boolean(flags["dry-run"]);
149
+ return APPLY_ONLY_FLAGS.filter(({ flag, shapesThePlan }) => {
150
+ const given = flags[flag];
151
+ const passed = Array.isArray(given) ? given.length > 0 : Boolean(given);
152
+ if (!passed) return false;
153
+ return !(dryRun && shapesThePlan);
154
+ });
155
+ }
156
+ var Diff = class _Diff extends BaseCommand {
157
+ static description = "Detect drift between Supabase environments and optionally fix it";
158
+ static examples = [
159
+ "<%= config.bin %> diff",
160
+ "<%= config.bin %> diff --detail",
161
+ "<%= config.bin %> diff --apply",
162
+ "<%= config.bin %> diff --check=rls",
163
+ "<%= config.bin %> diff --check=rls --apply",
164
+ "<%= config.bin %> diff --source=staging --target=production",
165
+ "<%= config.bin %> diff --skip=storage --skip=vault",
166
+ "<%= config.bin %> diff --tables=orders,order_items",
167
+ "<%= config.bin %> diff --tables='billing_*' --exclude-tables='*_audit'",
168
+ "<%= config.bin %> diff --tables=orders --detail",
169
+ // Built from the same constant the tips and the post-clone output use, so
170
+ // the advice cannot fall behind the check list again: this example predated
171
+ // Layer 14 and omitted `roles`, which on a real clone → remote diff is 227
172
+ // of the findings someone following it was left to puzzle over (issue #70).
173
+ `<%= config.bin %> diff ${CLONE_SKIP_FLAGS}`,
174
+ "<%= config.bin %> diff --ci",
175
+ "<%= config.bin %> diff --ci --fail-on=warning"
176
+ ];
177
+ /**
178
+ * Read from the environment rather than passed as flags, because they tune
179
+ * limits rather than select behaviour. Rendered as their own `--help`
180
+ * section (issue #40); the README carries the same table plus the timeout
181
+ * precedence chain.
182
+ */
183
+ static envVars = [
184
+ { name: "SUPAFORGE_CONNECT_TIMEOUT", description: "Seconds before a database connection attempt is abandoned (default 15)." },
185
+ { name: "SUPAFORGE_DBDIFF_TIMEOUT", description: "Seconds before the schema/data diff is abandoned. Overrides checks.schema.timeout (default 600)." },
186
+ { name: "SUPAFORGE_DBDIFF_MEMORY", description: "PHP memory limit for @dbdiff/cli \u2014 512M, 2G, or -1 for unlimited (default dbdiff's own 1G)." }
187
+ ];
188
+ static flags = {
189
+ check: Flags.string({
190
+ char: "l",
191
+ description: "Limit to a specific check",
192
+ options: [...CHECK_NAMES]
193
+ }),
194
+ skip: Flags.string({
195
+ char: "x",
196
+ description: "Skip a specific check (repeatable). Also configurable via checks.exclude in supaforge.config.json.",
197
+ options: [...CHECK_NAMES],
198
+ multiple: true
199
+ }),
200
+ detail: Flags.boolean({
201
+ description: "Show detailed SQL diffs (default: summary)",
202
+ default: false
203
+ }),
204
+ apply: Flags.boolean({
205
+ description: "Apply SQL fixes to resolve drift in the target environment",
206
+ default: false
207
+ }),
208
+ "allow-destructive": Flags.boolean({
209
+ description: "With --apply, also run fixes that drop tables or columns (destroys data)",
210
+ default: false
211
+ }),
212
+ "dry-run": Flags.boolean({
213
+ description: "With --apply, print the fixes in the order they would run without executing any of them",
214
+ default: false
215
+ }),
216
+ "no-transaction": Flags.boolean({
217
+ description: "With --apply, run each fix on its own instead of rolling the whole set back on the first failure",
218
+ aliases: ["continue-on-error"],
219
+ default: false
220
+ }),
221
+ only: Flags.string({
222
+ description: "With --apply, only apply these issue ids (repeatable, comma-separated, globs allowed). Ids come from --json.",
223
+ multiple: true
224
+ }),
225
+ "include-files": Flags.boolean({
226
+ description: "Include file-level drift detection in storage check",
227
+ default: false
228
+ }),
229
+ tables: Flags.string({
230
+ description: "Only compare these tables in the schema and data checks (repeatable, comma-separated, globs allowed). Overrides checks.tables.",
231
+ multiple: true
232
+ }),
233
+ "exclude-tables": Flags.string({
234
+ description: "Never compare these tables (repeatable, comma-separated, globs allowed). Merged with checks.excludeTables.",
235
+ multiple: true
236
+ }),
237
+ json: Flags.boolean({ description: "Output results as JSON" }),
238
+ source: Flags.string({ char: "s", description: "Source environment name" }),
239
+ target: Flags.string({ char: "t", description: "Target environment name" }),
240
+ ci: Flags.boolean({
241
+ description: "CI mode: emit GitHub Actions annotations and use semantic exit codes (0=clean, 1=drift, 2=error)",
242
+ default: false
243
+ }),
244
+ prove: Flags.boolean({
245
+ description: "Before applying, replay the migration on a throwaway clone of the target and verify it reproduces the source exactly. Refuses to apply if it does not.",
246
+ default: false
247
+ }),
248
+ "apply-posture": Flags.boolean({
249
+ description: "With --apply, also apply fixes from checks that judge the target on its own (RLS coverage, migration history). Off by default: those fixes move the target away from the source and so create drift.",
250
+ default: false
251
+ }),
252
+ "fail-on": Flags.string({
253
+ description: "Threshold for a non-zero exit in CI mode",
254
+ options: ["critical", "warning", "any"],
255
+ default: "critical"
256
+ }),
257
+ "fail-on-posture": Flags.boolean({
258
+ description: "Let findings from the target-only checks (RLS coverage, migration history) affect the exit code too. Off by default: they fire identically whichever pair you diff, so they cannot indicate that the environments have diverged.",
259
+ default: false
260
+ })
261
+ };
262
+ /**
263
+ * Report what `--apply` did, or — under `--dry-run` — what it would do.
264
+ *
265
+ * The applied list is printed in execution order, which is now dependency
266
+ * order rather than the order the checks reported the issues. That ordering
267
+ * is the whole point of the dry run: it is what makes the outcome of a real
268
+ * apply predictable before running it (issue #48).
269
+ */
270
+ renderApplyResult(result, dryRun) {
271
+ const verb = dryRun ? "Would apply" : "Applied";
272
+ if (result.applied.length > 0) {
273
+ const heading = `${verb} ${result.applied.length} fix(es)${dryRun ? ", in this order" : ""}:`;
274
+ this.log(dryRun ? bold(heading) : ok(heading));
275
+ result.applied.forEach((stmt, i) => {
276
+ const glyph = dryRun ? dim(`${i + 1}.`) : ok("\u2713");
277
+ this.log(` ${glyph} ${dim(`[${stmt.check}]`)} ${stmt.issueId}`);
278
+ if (dryRun && stmt.sql) this.log(` ${dim(stmt.sql.replace(/\s*\n\s*/g, " "))}`);
279
+ if (dryRun && stmt.action) this.log(` ${dim(stmt.action)}`);
280
+ });
281
+ }
282
+ if (result.skipped.length > 0) {
283
+ this.log(`
284
+ ${dim(`Skipped ${result.skipped.length} issue(s):`)}`);
285
+ for (const line of formatSkips(result.skipped)) this.log(` ${dim(line)}`);
286
+ }
287
+ if (result.rolledBack?.length) {
288
+ this.log(`
289
+ ${warn(`Rolled back ${result.rolledBack.length} fix(es)`)} \u2014 the target is unchanged:`);
290
+ for (const item of result.rolledBack) {
291
+ this.log(` ${dim("\u21A9")} ${dim(`[${item.check}]`)} ${item.issueId}`);
292
+ }
293
+ }
294
+ if (result.errors.length > 0) {
295
+ this.log(`
296
+ ${warn(`${result.errors.length} error(s):`)}`);
297
+ for (const item of result.errors) {
298
+ this.log(` ${warn("\u2717")} ${dim(`[${item.check}]`)} ${item.issueId}: ${item.error}`);
299
+ }
300
+ if (result.rolledBack) {
301
+ this.log(`
302
+ ${dim(`Nothing was written. Re-run with ${cmd("--no-transaction")} to apply the fixes that do work.`)}`);
303
+ }
304
+ }
305
+ if (dryRun) {
306
+ this.log(`
307
+ ${dim(`Nothing was executed. Drop ${cmd("--dry-run")} to apply.`)}`);
308
+ }
309
+ }
310
+ async run() {
311
+ const { flags } = await this.parse(_Diff);
312
+ for (const { flag, shapesThePlan } of inertApplyFlags(flags)) {
313
+ const suggestion = shapesThePlan ? `Add ${cmd("--apply")} (or ${cmd("--dry-run")} to preview) for it to take effect.` : `Add ${cmd("--apply")} for it to take effect.`;
314
+ process.stderr.write(` ${warn(`--${flag} has no effect without --apply.`)} ${suggestion}
315
+ `);
316
+ }
317
+ const config = await this.loadConfigOrFail();
318
+ this.validateDualEnvConfig(config, flags.source, flags.target);
319
+ const registry = createDefaultRegistry({ includeFiles: flags["include-files"] });
320
+ const checks = flags.check ? [flags.check] : void 0;
321
+ const skip = flags.skip?.length ? flags.skip : void 0;
322
+ const tableFilter = resolveTableFilter(config, {
323
+ tables: flags.tables,
324
+ excludeTables: flags["exclude-tables"]
325
+ });
326
+ if (isFiltered(tableFilter) && !flags.json && !flags.ci) {
327
+ this.log(`
328
+ ${dim(describeTableFilter(tableFilter))}`);
329
+ }
330
+ await this.preflightBothDatabases(config, flags);
331
+ const makeProgress = () => {
332
+ if (flags.json || flags.ci) return void 0;
333
+ process.stdout.write("\n Scanning...\n");
334
+ return (event) => {
335
+ const meta = CHECK_META[event.check];
336
+ const label = meta?.label ?? event.check;
337
+ const idx = `[${event.index + 1}/${event.total}]`;
338
+ if (event.phase === "check:start") {
339
+ process.stdout.write(` \u25B6 ${idx} ${label}...
340
+ `);
341
+ } else {
342
+ if (process.stdout.isTTY) process.stdout.write("\r\x1B[2K");
343
+ const dur = `${(event.durationMs / 1e3).toFixed(1)}s`;
344
+ const { glyph, text } = describeCheckOutcome(event.status, event.issueCount, event.skipReason);
345
+ process.stdout.write(` ${glyph} ${idx} ${label.padEnd(24)} ${text} (${dur})
346
+ `);
347
+ }
348
+ };
349
+ };
350
+ const makeDetail = () => {
351
+ if (flags.json || flags.ci || !process.stdout.isTTY) return void 0;
352
+ return (_check, detail) => {
353
+ process.stdout.write(`\r\x1B[2K ${dim(detail)}`);
354
+ };
355
+ };
356
+ if (flags.apply || flags["dry-run"]) {
357
+ const onProgress2 = makeProgress();
358
+ const scanResult = await scan(registry, { config, checks, skip, tableFilter, onProgress: onProgress2, onDetail: makeDetail() });
359
+ this.setCheckSummaries(scanResult.checks.map((c) => ({
360
+ check: c.check,
361
+ status: c.status,
362
+ issueCount: c.issues.length,
363
+ durationMs: c.durationMs,
364
+ ...c.error ? { error: sanitizeForReport(c.error) } : {}
365
+ })));
366
+ const unchecked = scanResult.checks.filter((c) => c.status === "error").map((c) => ({ check: c.check, error: sanitizeForReport(c.error ?? "check failed") }));
367
+ if (scanResult.summary.total === 0) {
368
+ if (flags.json) {
369
+ const empty = { applied: [], skipped: [], errors: [] };
370
+ this.json(unchecked.length ? { ...empty, unchecked } : empty);
371
+ if (unchecked.length) this.exit(1);
372
+ return;
373
+ }
374
+ if (unchecked.length) {
375
+ this.reportUnchecked(unchecked);
376
+ this.exit(1);
377
+ }
378
+ this.log(`${ok("No drift detected.")} Nothing to apply. \u2713`);
379
+ this.log(renderTip({ command: "diff", apply: true, driftTotal: 0 }));
380
+ return;
381
+ }
382
+ const targetEnv = config.environments[config.target];
383
+ const dryRun = flags["dry-run"];
384
+ if (flags.prove && !dryRun) {
385
+ const sourceEnv = config.environments[config.source];
386
+ const planned = planWork(scanResult, {
387
+ checks,
388
+ only: parseFlagList(flags.only),
389
+ allowDestructive: flags["allow-destructive"],
390
+ tableFilter,
391
+ applyPosture: flags["apply-posture"]
392
+ });
393
+ const { replay, unproved } = proofScope(planned.sqlStatements);
394
+ const migrationSql = replay.map((s) => s.sql).join("\n");
395
+ this.log(`
396
+ ${dim("Proving convergence on a throwaway clone\u2026")}`);
397
+ if (unproved.length > 0) {
398
+ const byCheck = [...new Set(unproved.map((s) => s.check))].map((c) => `${c} \xD7${unproved.filter((s) => s.check === c).length}`).join(", ");
399
+ this.log(` ${dim(`Not proved \u2014 act outside the proved schemas or on the whole server: ${byCheck}`)}`);
400
+ }
401
+ const proof = replay.length === 0 ? { converged: false, residual: [], cloneName: "", skipped: "none of the planned fixes is one the proof can replay" } : await proveConvergence({
402
+ sourceUrl: sourceEnv.dbUrl,
403
+ targetUrl: targetEnv.dbUrl,
404
+ migrationSql,
405
+ fixes: replay,
406
+ // Every schema the schema diff compares, not `public` alone: a
407
+ // migration dropping a schema the source lacks runs against it.
408
+ schemas: await comparedSchemas(
409
+ sourceEnv.dbUrl,
410
+ targetEnv.dbUrl,
411
+ schemaDiffIgnores(config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS)
412
+ ),
413
+ // The checks this run compares: without the schema check, what the
414
+ // target already lacks elsewhere is not this migration's to fix.
415
+ checks: scanResult.checks.map((c) => c.check)
416
+ });
417
+ const heldBack = [...heldBackSql(scanResult, planned), ...(proof.notApplied ?? []).map((n) => n.sql)];
418
+ if (proof.notApplied?.length) {
419
+ this.log(` ${dim(`Left out, as the apply will leave them \u2014 this server can't hold them: ${proof.notApplied.map((n) => n.issueId).join(", ")}`)}`);
420
+ }
421
+ if (proof.skipped && replay.length === 0) {
422
+ this.log(` ${dim(`Nothing to prove: ${proof.skipped}.`)}
423
+ `);
424
+ } else if (proof.skipped) {
425
+ this.refuseUnproven(`Not proven: ${proof.skipped}`, [], flags.json);
426
+ } else if (!proof.converged && residualHeldBack(proof.residual, heldBack).unexplained.length === 0) {
427
+ this.log(` ${ok("Converged")}, apart from what is held back and stays on the target:`);
428
+ for (const line of proof.residual.slice(0, 15)) this.log(` ${dim(line)}`);
429
+ this.log("");
430
+ } else if (!proof.converged) {
431
+ const { unexplained } = residualHeldBack(proof.residual, heldBack);
432
+ this.refuseUnproven("Migration does not reproduce the source.", unexplained, flags.json);
433
+ } else {
434
+ if (proof.outOfScope?.length) {
435
+ this.log(` ${ok("Converged")} on what this run compares. Outside it, and already different before:`);
436
+ for (const line of proof.outOfScope.slice(0, 15)) this.log(` ${dim(line)}`);
437
+ if (proof.outOfScope.length > 15) this.log(` ${dim(`\u2026and ${proof.outOfScope.length - 15} more`)}`);
438
+ this.log("");
439
+ } else {
440
+ this.log(` ${ok("Converged")} \u2014 the migration reproduces the source exactly.
441
+ `);
442
+ }
443
+ }
444
+ }
445
+ const result2 = await promote({
446
+ dbUrl: targetEnv.dbUrl,
447
+ scanResult,
448
+ checks,
449
+ dryRun,
450
+ allowDestructive: flags["allow-destructive"],
451
+ tableFilter,
452
+ only: parseFlagList(flags.only),
453
+ applyPosture: flags["apply-posture"],
454
+ transactional: !flags["no-transaction"]
455
+ });
456
+ if (flags.json) {
457
+ this.json(unchecked.length ? { ...result2, unchecked } : result2);
458
+ if (result2.errors.length > 0 || unchecked.length > 0) this.exit(1);
459
+ return;
460
+ }
461
+ this.renderApplyResult(result2, dryRun);
462
+ if (unchecked.length > 0) this.reportUnchecked(unchecked);
463
+ if (result2.errors.length > 0 || unchecked.length > 0) {
464
+ this.exit(1);
465
+ }
466
+ this.log(renderTip({
467
+ command: "diff",
468
+ apply: true,
469
+ driftTotal: scanResult.summary.total,
470
+ driftedChecks: scanResult.checks.filter((c) => c.status === "drifted").map((c) => c.check)
471
+ }));
472
+ return;
473
+ }
474
+ const onProgress = makeProgress();
475
+ const result = await scan(registry, { config, checks, skip, tableFilter, onProgress, onDetail: makeDetail() });
476
+ this.setCheckSummaries(result.checks.map((c) => ({
477
+ check: c.check,
478
+ status: c.status,
479
+ issueCount: c.issues.length,
480
+ durationMs: c.durationMs,
481
+ ...c.error ? { error: sanitizeForReport(c.error) } : {}
482
+ })));
483
+ const sourceUrl = config.environments[config.source]?.dbUrl;
484
+ const sourceIsClone = await isCloneDatabase(sourceUrl) || await sourceLooksLikeCloneOf(sourceUrl, config.environments[config.target]?.dbUrl);
485
+ const driftedChecks = result.checks.filter((c) => c.status === "drifted").map((c) => c.check);
486
+ const skippedChecks = result.checks.filter((c) => c.status === "skipped").map((c) => c.check);
487
+ const erroredChecks = result.checks.filter((c) => c.status === "error").map((c) => c.check);
488
+ if (flags.ci) {
489
+ const failOn = flags["fail-on"] ?? "critical";
490
+ const annotations = formatGitHubAnnotations(result);
491
+ for (const line of annotations) {
492
+ process.stderr.write(line + "\n");
493
+ }
494
+ const summary = formatCiSummary(result);
495
+ process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
496
+ const exitCode = computeCiExitCode(result, failOn, {
497
+ failOnPosture: flags["fail-on-posture"]
498
+ });
499
+ if (exitCode !== 0) {
500
+ this.exit(exitCode);
501
+ }
502
+ return;
503
+ }
504
+ if (flags.json) {
505
+ this.json(result);
506
+ } else if (flags.detail) {
507
+ this.log(renderDetailed(result));
508
+ this.log(renderTip({
509
+ command: "diff",
510
+ detail: true,
511
+ driftTotal: result.summary.total,
512
+ driftedChecks,
513
+ skippedChecks,
514
+ erroredChecks,
515
+ singleCheck: checks?.[0],
516
+ sourceIsClone
517
+ }));
518
+ } else {
519
+ this.log(renderSummary(result));
520
+ if (result.summary.total > 0) {
521
+ this.log(` \u2192 Run with ${cmd("--detail")} to see SQL diffs`);
522
+ this.log(
523
+ sourceIsClone ? ` \u2192 ${cmd("--apply")} would push this clone's shape onto the target, absences included \u2014 preview it first with ${cmd("--apply --dry-run")}
524
+ ` : ` \u2192 Run with ${cmd("--apply")} to fix drift
525
+ `
526
+ );
527
+ }
528
+ this.log(renderTip({
529
+ command: "diff",
530
+ detail: false,
531
+ driftTotal: result.summary.total,
532
+ driftedChecks,
533
+ skippedChecks,
534
+ erroredChecks,
535
+ singleCheck: checks?.[0],
536
+ sourceIsClone
537
+ }));
538
+ }
539
+ const { drift, posture } = summarizeByKind(result.checks);
540
+ if (drift.critical === 0 && posture.critical > 0 && !flags.json) {
541
+ this.log(
542
+ ` ${dim("Posture findings do not affect the exit code \u2014 they describe the target, not drift from the source. Add")} ${cmd("--fail-on-posture")} ${dim("to gate on them.")}
543
+ `
544
+ );
545
+ }
546
+ if (drift.critical > 0 || flags["fail-on-posture"] && posture.critical > 0 || erroredChecks.length > 0) {
547
+ this.exit(1);
548
+ }
549
+ }
550
+ /**
551
+ * Stop before applying anything: the proof could not run, or ran and found
552
+ * the migration would not reproduce the source. Under --json the reason is
553
+ * the output, rather than nothing at all.
554
+ */
555
+ refuseUnproven(reason, residual, json) {
556
+ if (json) {
557
+ this.json({ proved: false, reason, residual, applied: [], skipped: [], errors: [] });
558
+ this.exit(1);
559
+ }
560
+ this.log(` ${warn(/[.!?]$/.test(reason) ? reason : `${reason}.`)} Nothing was applied.
561
+ `);
562
+ for (const line of residual.slice(0, 15)) this.log(` ${line}`);
563
+ if (residual.length > 15) this.log(` ${dim(`\u2026and ${residual.length - 15} more`)}`);
564
+ if (residual.length > 0) this.log(`
565
+ ${dim("These objects would still differ after applying.")}`);
566
+ else this.log(` ${dim("Re-run without --prove to apply without the proof.")}`);
567
+ this.exit(1);
568
+ }
569
+ /** Name the checks that failed, whose drift this run neither saw nor applied. */
570
+ reportUnchecked(unchecked) {
571
+ this.log(`
572
+ ${warn(`${unchecked.length} check(s) could not run, so nothing of theirs was applied:`)}`);
573
+ for (const u of unchecked) this.log(` ${u.check}: ${u.error}`);
574
+ this.log("");
575
+ }
576
+ /**
577
+ * Abort before scanning when either database can't be reached.
578
+ *
579
+ * Text mode prints the preflight as before. Under --json the report goes to
580
+ * stdout as JSON; under --ci it becomes an error annotation, with exit 2
581
+ * (couldn't run) as the CI contract says.
582
+ */
583
+ async preflightBothDatabases(config, flags) {
584
+ const quiet = Boolean(flags.json || flags.ci);
585
+ const pre = new Preflight("Diff preflight checks", quiet ? () => void 0 : (m) => this.log(m)).addDatabase("Source", config.source, config.environments[config.source].dbUrl).addDatabase("Target", config.target, config.environments[config.target].dbUrl);
586
+ const report = await pre.run();
587
+ if (report.passed) return;
588
+ const failures = report.checks.filter((c) => !c.passed).map((c) => `${c.label} not reachable: ${redactUrls(describeFailure(c.error))}`);
589
+ const message = `Diff aborted \u2014 ${failures.join("; ")}`;
590
+ if (flags.ci) {
591
+ process.stderr.write(`::error title=Diff aborted::${failures.join("; ")}
592
+ `);
593
+ process.stdout.write(JSON.stringify({
594
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
595
+ error: message,
596
+ score: null,
597
+ postureScore: null,
598
+ summary: { total: 0, critical: 0, warning: 0, info: 0 },
599
+ errors: failures.map((f) => ({ check: "preflight", message: f })),
600
+ skipped: [],
601
+ coverage: { compared: 0, total: 0 },
602
+ criticalIssues: [],
603
+ warningIssues: [],
604
+ preflight: report.checks.map(stripError)
605
+ }, null, 2) + "\n");
606
+ this.exit(2);
607
+ }
608
+ if (flags.json) {
609
+ this.json({ error: message, preflight: report.checks.map(stripError) });
610
+ this.exit(1);
611
+ }
612
+ this.error("Diff aborted \u2014 fix the issues above first.", { exit: 1 });
613
+ }
614
+ };
615
+ function heldBackSql(scanResult, planned) {
616
+ const skipped = new Set(planned.skipped.map((s) => s.issueId));
617
+ return scanResult.checks.flatMap((c) => c.issues).filter((i) => skipped.has(i.id) && i.sql?.up).map((i) => i.sql.up);
618
+ }
619
+ function stripError(c) {
620
+ return {
621
+ label: c.label,
622
+ passed: c.passed,
623
+ ...c.detail ? { detail: c.detail } : {},
624
+ ...c.error ? { error: redactUrls(describeFailure(c.error)) } : {}
625
+ };
626
+ }
627
+
628
+ export {
629
+ inertApplyFlags,
630
+ Diff
631
+ };
632
+ //# sourceMappingURL=chunk-4IVN7QVY.js.map