@akal/supaforge 0.0.0-stage → 0.0.31

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 (99) 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 +134 -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-4OU7KO5Y.js +13 -0
  9. package/dist/chunk-4OU7KO5Y.js.map +1 -0
  10. package/dist/chunk-5QQBTLWO.js +642 -0
  11. package/dist/chunk-5QQBTLWO.js.map +1 -0
  12. package/dist/chunk-5Z3SAIQS.js +2807 -0
  13. package/dist/chunk-5Z3SAIQS.js.map +1 -0
  14. package/dist/chunk-6WAMNZLO.js +336 -0
  15. package/dist/chunk-6WAMNZLO.js.map +1 -0
  16. package/dist/chunk-BHYLBKYD.js +156 -0
  17. package/dist/chunk-BHYLBKYD.js.map +1 -0
  18. package/dist/chunk-BLKJWDTL.js +153 -0
  19. package/dist/chunk-BLKJWDTL.js.map +1 -0
  20. package/dist/chunk-DQQ5E563.js +64 -0
  21. package/dist/chunk-DQQ5E563.js.map +1 -0
  22. package/dist/chunk-G2DIPIYU.js +94 -0
  23. package/dist/chunk-G2DIPIYU.js.map +1 -0
  24. package/dist/chunk-H5MJ5DFX.js +16 -0
  25. package/dist/chunk-H5MJ5DFX.js.map +1 -0
  26. package/dist/chunk-KIFJGON5.js +248 -0
  27. package/dist/chunk-KIFJGON5.js.map +1 -0
  28. package/dist/chunk-LQXF65MC.js +240 -0
  29. package/dist/chunk-LQXF65MC.js.map +1 -0
  30. package/dist/chunk-NXRSAVRU.js +478 -0
  31. package/dist/chunk-NXRSAVRU.js.map +1 -0
  32. package/dist/chunk-PARSNTBD.js +837 -0
  33. package/dist/chunk-PARSNTBD.js.map +1 -0
  34. package/dist/chunk-RRMI5CZD.js +376 -0
  35. package/dist/chunk-RRMI5CZD.js.map +1 -0
  36. package/dist/chunk-SF3YA42C.js +506 -0
  37. package/dist/chunk-SF3YA42C.js.map +1 -0
  38. package/dist/chunk-TQJSQLWA.js +574 -0
  39. package/dist/chunk-TQJSQLWA.js.map +1 -0
  40. package/dist/chunk-VMTBLHN2.js +122 -0
  41. package/dist/chunk-VMTBLHN2.js.map +1 -0
  42. package/dist/chunk-VOXZWQ3N.js +948 -0
  43. package/dist/chunk-VOXZWQ3N.js.map +1 -0
  44. package/dist/chunk-X6V2GGDZ.js +333 -0
  45. package/dist/chunk-X6V2GGDZ.js.map +1 -0
  46. package/dist/chunk-XMYMIURR.js +552 -0
  47. package/dist/chunk-XMYMIURR.js.map +1 -0
  48. package/dist/chunk-YVDSR4GM.js +1264 -0
  49. package/dist/chunk-YVDSR4GM.js.map +1 -0
  50. package/dist/commands/clone.d.ts +66 -0
  51. package/dist/commands/clone.js +416 -0
  52. package/dist/commands/clone.js.map +1 -0
  53. package/dist/commands/diff.d.ts +65 -0
  54. package/dist/commands/diff.js +24 -0
  55. package/dist/commands/diff.js.map +1 -0
  56. package/dist/commands/help.d.ts +32 -0
  57. package/dist/commands/help.js +36 -0
  58. package/dist/commands/help.js.map +1 -0
  59. package/dist/commands/hukam.d.ts +13 -0
  60. package/dist/commands/hukam.js +29 -0
  61. package/dist/commands/hukam.js.map +1 -0
  62. package/dist/commands/init.d.ts +47 -0
  63. package/dist/commands/init.js +388 -0
  64. package/dist/commands/init.js.map +1 -0
  65. package/dist/commands/mcp.d.ts +13 -0
  66. package/dist/commands/mcp.js +44 -0
  67. package/dist/commands/mcp.js.map +1 -0
  68. package/dist/commands/migrate/baseline.d.ts +24 -0
  69. package/dist/commands/migrate/baseline.js +69 -0
  70. package/dist/commands/migrate/baseline.js.map +1 -0
  71. package/dist/commands/migrate/create.d.ts +36 -0
  72. package/dist/commands/migrate/create.js +128 -0
  73. package/dist/commands/migrate/create.js.map +1 -0
  74. package/dist/commands/migrate/list.d.ts +23 -0
  75. package/dist/commands/migrate/list.js +110 -0
  76. package/dist/commands/migrate/list.js.map +1 -0
  77. package/dist/commands/migrate/run.d.ts +61 -0
  78. package/dist/commands/migrate/run.js +19 -0
  79. package/dist/commands/migrate/run.js.map +1 -0
  80. package/dist/commands/report.d.ts +27 -0
  81. package/dist/commands/report.js +210 -0
  82. package/dist/commands/report.js.map +1 -0
  83. package/dist/commands/restore.d.ts +26 -0
  84. package/dist/commands/restore.js +268 -0
  85. package/dist/commands/restore.js.map +1 -0
  86. package/dist/commands/snapshot.d.ts +33 -0
  87. package/dist/commands/snapshot.js +251 -0
  88. package/dist/commands/snapshot.js.map +1 -0
  89. package/dist/commands/sync.d.ts +16 -0
  90. package/dist/commands/sync.js +39 -0
  91. package/dist/commands/sync.js.map +1 -0
  92. package/dist/config-CTbeRlJk.d.ts +134 -0
  93. package/dist/help.d.ts +28 -0
  94. package/dist/help.js +64 -0
  95. package/dist/help.js.map +1 -0
  96. package/dist/index.d.ts +493 -0
  97. package/dist/index.js +147 -0
  98. package/dist/index.js.map +1 -0
  99. package/package.json +74 -4
@@ -0,0 +1,153 @@
1
+ import {
2
+ CLONE_SKIP_FLAGS,
3
+ cmd,
4
+ dim
5
+ } from "./chunk-6WAMNZLO.js";
6
+
7
+ // src/tips.ts
8
+ function applyTip(sourceIsClone, driftedChecks) {
9
+ if (!sourceIsClone) {
10
+ return { text: `Add ${cmd("--apply")} to push all fixes to the target in one shot.` };
11
+ }
12
+ const layer = driftedChecks[0] ?? "schema";
13
+ return {
14
+ text: `Source is a local clone \u2014 ${cmd("--apply")} would reshape the target to match it, including dropping roles, grants and policies the clone never had. Scope it first: ${cmd(`--check=${layer} --apply --dry-run`)}.`
15
+ };
16
+ }
17
+ function diffTips(ctx) {
18
+ const tips = [];
19
+ const { driftTotal = 0, driftedChecks = [], detail, apply, singleCheck, skippedChecks = [], erroredChecks = [], sourceIsClone } = ctx;
20
+ if (apply) {
21
+ if (driftTotal > 0) {
22
+ tips.push({ text: `Re-run ${cmd("supaforge diff")} to verify everything is clean.` });
23
+ tips.push({ text: `Take a snapshot after a successful sync: ${cmd("supaforge snapshot")}.` });
24
+ } else {
25
+ tips.push({ text: `No drift to apply \u2014 run ${cmd("supaforge snapshot")} to lock in this clean state.` });
26
+ }
27
+ return tips;
28
+ }
29
+ if (driftTotal > 0 && !detail) {
30
+ tips.push({ text: `Add ${cmd("--detail")} to see the full SQL for each issue.` });
31
+ tips.push(applyTip(sourceIsClone, driftedChecks));
32
+ if (driftedChecks.length > 1) {
33
+ tips.push({ text: `Focus on one layer: ${cmd(`--check=${driftedChecks[0]}`)} to see just that check.` });
34
+ }
35
+ if (skippedChecks.length === 0) {
36
+ tips.push({ text: `Post-clone? Use ${cmd(CLONE_SKIP_FLAGS)} to suppress clone-only noise, roles and grants included.` });
37
+ }
38
+ } else if (driftTotal > 0 && detail) {
39
+ tips.push(
40
+ sourceIsClone ? applyTip(sourceIsClone, driftedChecks) : { text: `Run ${cmd("supaforge diff --apply")} to execute all the SQL fixes above.` }
41
+ );
42
+ if (driftedChecks.length > 1) {
43
+ tips.push({ text: `Fix one layer at a time: ${cmd(`--check=${driftedChecks[0]} --apply`)}.` });
44
+ }
45
+ } else if (driftTotal === 0) {
46
+ tips.push(...noDriftTips(erroredChecks, singleCheck));
47
+ }
48
+ return tips;
49
+ }
50
+ function cloneTips(ctx) {
51
+ if (!ctx.cloneApplied) {
52
+ return [{ text: `Looks good? Add ${cmd("--apply")} to execute the clone.` }];
53
+ }
54
+ return [
55
+ {
56
+ text: `Diff against this clone with: ${cmd(`supaforge diff ${CLONE_SKIP_FLAGS}`)} \u2014 or add ${cmd('"checks": { "exclude": [...] }')} to config to make it permanent.`
57
+ },
58
+ { text: `Restore from a snapshot any time: ${cmd("supaforge restore --env=local --from-snapshot=latest --apply")}.` },
59
+ { text: `Run ${cmd("supaforge snapshot")} on the remote after a deploy to track incremental drift.` }
60
+ ];
61
+ }
62
+ function snapshotTips(ctx) {
63
+ if (ctx.snapshotList) {
64
+ return [
65
+ { text: `Clean up old snapshots with ${cmd("supaforge snapshot --prune")} (keeps last 7 by default).` },
66
+ { text: `Restore into an environment: ${cmd("supaforge restore --env=local --from-snapshot=latest --apply")}.` }
67
+ ];
68
+ }
69
+ if (ctx.snapshotMigration) {
70
+ return [
71
+ { text: `Migration files live in ${cmd(".supaforge/migrations/")} \u2014 commit them to version-control.` },
72
+ { text: `Replay all migrations: ${cmd("supaforge restore --env=local --from-migrations --apply")}.` }
73
+ ];
74
+ }
75
+ return [
76
+ { text: `Add ${cmd("--migration")} to also generate an incremental diff against the previous snapshot.` },
77
+ { text: `List all snapshots: ${cmd("supaforge snapshot --list")}.` },
78
+ { text: `Restore this snapshot: ${cmd("supaforge restore --env=local --from-snapshot=latest --apply")}.` }
79
+ ];
80
+ }
81
+ function restoreTips(_ctx) {
82
+ return [
83
+ { text: `After a restore, run ${cmd("supaforge diff")} to confirm the environment matches the source.` },
84
+ { text: `Take a new snapshot to lock in the restored state: ${cmd("supaforge snapshot")}.` }
85
+ ];
86
+ }
87
+ var GENERAL_TIPS = [
88
+ { text: `${cmd("supaforge hukam")} is an alias for ${cmd("diff")} \u2014 same flags, different vibe \u{1F64F}` },
89
+ { text: `Use ${cmd("--source=X --target=Y")} to compare any two environments without editing config.` },
90
+ { text: `Store credentials in ${cmd(".env")} \u2014 SupaForge auto-loads it. Config supports ${cmd("$VAR")} references.` },
91
+ { text: `Add ${cmd('"checks": { "exclude": ["storage","vault"] }')} to config to permanently skip noisy checks.` },
92
+ { text: `Run ${cmd("supaforge diff --json")} for machine-readable output \u2014 useful in scripts and CI.` },
93
+ { text: `Connect AI agents: add ${cmd("supaforge mcp")} to your Claude Desktop / Cursor MCP config.` },
94
+ { text: `Enable row-level data drift: add ${cmd('"checks": { "data": { "tables": ["plans","flags"] } }')} to config.` },
95
+ { text: `${cmd("supaforge diff --include-files")} also checks file-level storage drift (checksums).` },
96
+ { text: `${cmd("supaforge sync")} is shorthand for ${cmd("diff --apply")} \u2014 detects and fixes drift in one step.` },
97
+ { text: `Preview an apply in dependency order without running it: ${cmd("supaforge diff --apply --dry-run")}.` },
98
+ { text: `Apply a reviewed subset by id: ${cmd("supaforge diff --apply --only='schema-create-*'")}.` }
99
+ ];
100
+ function noDriftTips(erroredChecks, singleCheck) {
101
+ if (erroredChecks.length > 0) {
102
+ const noun = erroredChecks.length === 1 ? "check" : "checks";
103
+ const names = erroredChecks.join(", ");
104
+ return [
105
+ { text: `${erroredChecks.length} ${noun} could not run (${names}) \u2014 drift is unknown, not zero.` },
106
+ { text: `Re-run with ${cmd("--detail")} to see why, then fix the cause before trusting this result.` }
107
+ ];
108
+ }
109
+ const tips = [
110
+ { text: `Environments are in sync \u2014 run ${cmd("supaforge snapshot")} to capture this state.` },
111
+ { text: `Wire this into CI: ${cmd("supaforge diff")} exits 1 on critical drift.` }
112
+ ];
113
+ if (!singleCheck) {
114
+ tips.push({ text: `Deep-dive a specific layer: ${cmd("supaforge diff --check=rls --detail")}.` });
115
+ }
116
+ return tips;
117
+ }
118
+ function pickTip(ctx, seed) {
119
+ let pool;
120
+ switch (ctx.command) {
121
+ case "diff":
122
+ pool = diffTips(ctx);
123
+ break;
124
+ case "clone":
125
+ pool = cloneTips(ctx);
126
+ break;
127
+ case "snapshot":
128
+ pool = snapshotTips(ctx);
129
+ break;
130
+ case "restore":
131
+ pool = restoreTips(ctx);
132
+ break;
133
+ default:
134
+ pool = [];
135
+ }
136
+ if (pool.length === 0) pool = GENERAL_TIPS;
137
+ if (pool.length < 3 && GENERAL_TIPS.length > 0) {
138
+ const generalIdx = (seed ?? Date.now()) % GENERAL_TIPS.length;
139
+ pool = [...pool, GENERAL_TIPS[generalIdx]];
140
+ }
141
+ const idx = (seed ?? Date.now()) % pool.length;
142
+ const tip = pool[idx];
143
+ return `
144
+ ${dim("tip:")} ${tip.text}`;
145
+ }
146
+ function renderTip(ctx) {
147
+ return pickTip(ctx) ?? "";
148
+ }
149
+
150
+ export {
151
+ renderTip
152
+ };
153
+ //# sourceMappingURL=chunk-BLKJWDTL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tips.ts"],"sourcesContent":["import { dim, cmd } from './ui.js'\nimport type { CheckName } from './types/drift.js'\nimport { CLONE_SKIP_FLAGS } from './defaults.js'\n\n// ─── Context ──────────────────────────────────────────────────────────────────\n\nexport interface TipContext {\n /** Which top-level command just ran. */\n command: 'diff' | 'clone' | 'snapshot' | 'restore'\n /** diff: total drift issues found. */\n driftTotal?: number\n /** diff: checks that had drift, in order of severity. */\n driftedChecks?: CheckName[]\n /** diff: checks that were skipped (via --skip or config). */\n skippedChecks?: CheckName[]\n /** diff: checks that failed to run. Drift is unknown for these. */\n erroredChecks?: CheckName[]\n /** diff: whether --detail was used. */\n detail?: boolean\n /** diff: whether --apply was used. */\n apply?: boolean\n /** diff: whether --check narrowed to a single check. */\n singleCheck?: CheckName\n /**\n * diff: whether the source environment is a local clone.\n *\n * Changes what `--apply` means. Clone → remote reshapes a shared environment\n * to match a vanilla-PostgreSQL copy, which includes dropping the roles,\n * grants and policies the clone never had — 227 of 601 findings on the diff\n * that prompted issue #48. Recommending it generically in that direction is\n * advice a first-time user should not follow.\n */\n sourceIsClone?: boolean\n /** clone: whether --apply completed successfully (not dry-run). */\n cloneApplied?: boolean\n /** clone: whether --schema-only was used. */\n schemaOnly?: boolean\n /** snapshot: whether --migration was used. */\n snapshotMigration?: boolean\n /** snapshot: whether --list was used. */\n snapshotList?: boolean\n}\n\n// ─── Tip type ─────────────────────────────────────────────────────────────────\n\ninterface Tip {\n text: string\n}\n\n// ─── Contextual tip pools ─────────────────────────────────────────────────────\n\n/**\n * How to word the `--apply` suggestion for this diff.\n *\n * From a clone it is a warning rather than a suggestion: the same command that\n * promotes local work to a remote will, run from a clone, push the clone's\n * *absences* to the remote too.\n */\nfunction applyTip(sourceIsClone: boolean | undefined, driftedChecks: CheckName[]): Tip {\n if (!sourceIsClone) {\n return { text: `Add ${cmd('--apply')} to push all fixes to the target in one shot.` }\n }\n const layer = driftedChecks[0] ?? 'schema'\n return {\n text:\n `Source is a local clone — ${cmd('--apply')} would reshape the target to match it, ` +\n `including dropping roles, grants and policies the clone never had. ` +\n `Scope it first: ${cmd(`--check=${layer} --apply --dry-run`)}.`,\n }\n}\n\nfunction diffTips(ctx: TipContext): Tip[] {\n const tips: Tip[] = []\n const { driftTotal = 0, driftedChecks = [], detail, apply, singleCheck, skippedChecks = [], erroredChecks = [], sourceIsClone } = ctx\n\n if (apply) {\n // Post-apply tips\n if (driftTotal > 0) {\n tips.push({ text: `Re-run ${cmd('supaforge diff')} to verify everything is clean.` })\n tips.push({ text: `Take a snapshot after a successful sync: ${cmd('supaforge snapshot')}.` })\n } else {\n tips.push({ text: `No drift to apply — run ${cmd('supaforge snapshot')} to lock in this clean state.` })\n }\n return tips\n }\n\n if (driftTotal > 0 && !detail) {\n // Summary mode with drift\n tips.push({ text: `Add ${cmd('--detail')} to see the full SQL for each issue.` })\n tips.push(applyTip(sourceIsClone, driftedChecks))\n if (driftedChecks.length > 1) {\n tips.push({ text: `Focus on one layer: ${cmd(`--check=${driftedChecks[0]}`)} to see just that check.` })\n }\n if (skippedChecks.length === 0) {\n tips.push({ text: `Post-clone? Use ${cmd(CLONE_SKIP_FLAGS)} to suppress clone-only noise, roles and grants included.` })\n }\n } else if (driftTotal > 0 && detail) {\n // Detail mode with drift\n tips.push(\n sourceIsClone\n ? applyTip(sourceIsClone, driftedChecks)\n : { text: `Run ${cmd('supaforge diff --apply')} to execute all the SQL fixes above.` },\n )\n if (driftedChecks.length > 1) {\n tips.push({ text: `Fix one layer at a time: ${cmd(`--check=${driftedChecks[0]} --apply`)}.` })\n }\n } else if (driftTotal === 0) {\n tips.push(...noDriftTips(erroredChecks, singleCheck))\n }\n\n return tips\n}\n\nfunction cloneTips(ctx: TipContext): Tip[] {\n if (!ctx.cloneApplied) {\n // Dry-run — hint to add --apply\n return [{ text: `Looks good? Add ${cmd('--apply')} to execute the clone.` }]\n }\n\n // Post-clone: most important tip is about skipping non-Postgres checks\n return [\n {\n text: `Diff against this clone with: ${cmd(`supaforge diff ${CLONE_SKIP_FLAGS}`)} — or add ${cmd('\"checks\": { \"exclude\": [...] }')} to config to make it permanent.`,\n },\n { text: `Restore from a snapshot any time: ${cmd('supaforge restore --env=local --from-snapshot=latest --apply')}.` },\n { text: `Run ${cmd('supaforge snapshot')} on the remote after a deploy to track incremental drift.` },\n ]\n}\n\nfunction snapshotTips(ctx: TipContext): Tip[] {\n if (ctx.snapshotList) {\n return [\n { text: `Clean up old snapshots with ${cmd('supaforge snapshot --prune')} (keeps last 7 by default).` },\n { text: `Restore into an environment: ${cmd('supaforge restore --env=local --from-snapshot=latest --apply')}.` },\n ]\n }\n if (ctx.snapshotMigration) {\n return [\n { text: `Migration files live in ${cmd('.supaforge/migrations/')} — commit them to version-control.` },\n { text: `Replay all migrations: ${cmd('supaforge restore --env=local --from-migrations --apply')}.` },\n ]\n }\n return [\n { text: `Add ${cmd('--migration')} to also generate an incremental diff against the previous snapshot.` },\n { text: `List all snapshots: ${cmd('supaforge snapshot --list')}.` },\n { text: `Restore this snapshot: ${cmd('supaforge restore --env=local --from-snapshot=latest --apply')}.` },\n ]\n}\n\nfunction restoreTips(_ctx: TipContext): Tip[] {\n return [\n { text: `After a restore, run ${cmd('supaforge diff')} to confirm the environment matches the source.` },\n { text: `Take a new snapshot to lock in the restored state: ${cmd('supaforge snapshot')}.` },\n ]\n}\n\n// ─── General tips pool (fallback) ────────────────────────────────────────────\n\nconst GENERAL_TIPS: Tip[] = [\n { text: `${cmd('supaforge hukam')} is an alias for ${cmd('diff')} — same flags, different vibe 🙏` },\n { text: `Use ${cmd('--source=X --target=Y')} to compare any two environments without editing config.` },\n { text: `Store credentials in ${cmd('.env')} — SupaForge auto-loads it. Config supports ${cmd('$VAR')} references.` },\n { text: `Add ${cmd('\"checks\": { \"exclude\": [\"storage\",\"vault\"] }')} to config to permanently skip noisy checks.` },\n { text: `Run ${cmd('supaforge diff --json')} for machine-readable output — useful in scripts and CI.` },\n { text: `Connect AI agents: add ${cmd('supaforge mcp')} to your Claude Desktop / Cursor MCP config.` },\n { text: `Enable row-level data drift: add ${cmd('\"checks\": { \"data\": { \"tables\": [\"plans\",\"flags\"] } }')} to config.` },\n { text: `${cmd('supaforge diff --include-files')} also checks file-level storage drift (checksums).` },\n { text: `${cmd('supaforge sync')} is shorthand for ${cmd('diff --apply')} — detects and fixes drift in one step.` },\n { text: `Preview an apply in dependency order without running it: ${cmd('supaforge diff --apply --dry-run')}.` },\n { text: `Apply a reviewed subset by id: ${cmd(\"supaforge diff --apply --only='schema-create-*'\")}.` },\n]\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Pick the most relevant tip for the current context.\n * Returns null when no tip applies (e.g. --json mode — caller should gate on that).\n */\n/**\n * Tips for a scan that found no drift.\n *\n * \"No drift\" and \"nothing was measured\" look identical in the totals but mean\n * opposite things, so they get different advice. Telling a user their\n * environments are in sync when the only check errored is the most actively\n * misleading output the tool can produce (issue #29).\n *\n * Extracted from pickTip rather than added as another branch: the extra\n * condition took that function from 17 to 21 cognitive complexity.\n */\nfunction noDriftTips(erroredChecks: CheckName[], singleCheck?: CheckName): Array<{ text: string }> {\n if (erroredChecks.length > 0) {\n const noun = erroredChecks.length === 1 ? 'check' : 'checks'\n const names = erroredChecks.join(', ')\n return [\n { text: `${erroredChecks.length} ${noun} could not run (${names}) — drift is unknown, not zero.` },\n { text: `Re-run with ${cmd('--detail')} to see why, then fix the cause before trusting this result.` },\n ]\n }\n\n const tips = [\n { text: `Environments are in sync — run ${cmd('supaforge snapshot')} to capture this state.` },\n { text: `Wire this into CI: ${cmd('supaforge diff')} exits 1 on critical drift.` },\n ]\n if (!singleCheck) {\n tips.push({ text: `Deep-dive a specific layer: ${cmd('supaforge diff --check=rls --detail')}.` })\n }\n return tips\n}\n\nexport function pickTip(ctx: TipContext, seed?: number): string | null {\n let pool: Tip[]\n\n switch (ctx.command) {\n case 'diff': pool = diffTips(ctx); break\n case 'clone': pool = cloneTips(ctx); break\n case 'snapshot': pool = snapshotTips(ctx); break\n case 'restore': pool = restoreTips(ctx); break\n default: pool = []\n }\n\n // Fall back to general pool if contextual pool is empty\n if (pool.length === 0) pool = GENERAL_TIPS\n\n // Mix in a general tip occasionally (every ~3 runs) when the contextual pool\n // is smaller than 3, so users see variety over time.\n if (pool.length < 3 && GENERAL_TIPS.length > 0) {\n const generalIdx = (seed ?? Date.now()) % GENERAL_TIPS.length\n pool = [...pool, GENERAL_TIPS[generalIdx]]\n }\n\n const idx = (seed ?? Date.now()) % pool.length\n const tip = pool[idx]\n return `\\n${dim('tip:')} ${tip.text}`\n}\n\n/** Format and return a tip line ready to log, or empty string if none. */\nexport function renderTip(ctx: TipContext): string {\n return pickTip(ctx) ?? ''\n}\n"],"mappings":";;;;;;;AA0DA,SAAS,SAAS,eAAoC,eAAiC;AACrF,MAAI,CAAC,eAAe;AAClB,WAAO,EAAE,MAAM,OAAO,IAAI,SAAS,CAAC,gDAAgD;AAAA,EACtF;AACA,QAAM,QAAQ,cAAc,CAAC,KAAK;AAClC,SAAO;AAAA,IACL,MACE,kCAA6B,IAAI,SAAS,CAAC,6HAExB,IAAI,WAAW,KAAK,oBAAoB,CAAC;AAAA,EAChE;AACF;AAEA,SAAS,SAAS,KAAwB;AACxC,QAAM,OAAc,CAAC;AACrB,QAAM,EAAE,aAAa,GAAG,gBAAgB,CAAC,GAAG,QAAQ,OAAO,aAAa,gBAAgB,CAAC,GAAG,gBAAgB,CAAC,GAAG,cAAc,IAAI;AAElI,MAAI,OAAO;AAET,QAAI,aAAa,GAAG;AAClB,WAAK,KAAK,EAAE,MAAM,UAAU,IAAI,gBAAgB,CAAC,kCAAkC,CAAC;AACpF,WAAK,KAAK,EAAE,MAAM,4CAA4C,IAAI,oBAAoB,CAAC,IAAI,CAAC;AAAA,IAC9F,OAAO;AACL,WAAK,KAAK,EAAE,MAAM,gCAA2B,IAAI,oBAAoB,CAAC,g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MAAI,KAAK,SAAS,KAAK,aAAa,SAAS,GAAG;AAC9C,UAAM,cAAc,QAAQ,KAAK,IAAI,KAAK,aAAa;AACvD,WAAO,CAAC,GAAG,MAAM,aAAa,UAAU,CAAC;AAAA,EAC3C;AAEA,QAAM,OAAO,QAAQ,KAAK,IAAI,KAAK,KAAK;AACxC,QAAM,MAAM,KAAK,GAAG;AACpB,SAAO;AAAA,EAAK,IAAI,MAAM,CAAC,IAAI,IAAI,IAAI;AACrC;AAGO,SAAS,UAAU,KAAyB;AACjD,SAAO,QAAQ,GAAG,KAAK;AACzB;","names":[]}
@@ -0,0 +1,64 @@
1
+ // src/utils/strings.ts
2
+ var MAX_SLUG_LENGTH = 60;
3
+ function slugify(name, separator = "_") {
4
+ const pattern = new RegExp(`[^a-z0-9]+`, "g");
5
+ const edgePattern = new RegExp(`^${escapeRegex(separator)}|${escapeRegex(separator)}$`, "g");
6
+ return name.toLowerCase().replace(pattern, separator).replace(edgePattern, "").slice(0, MAX_SLUG_LENGTH);
7
+ }
8
+ function escapeRegex(s) {
9
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10
+ }
11
+ function parseFlagList(values) {
12
+ if (!Array.isArray(values)) return [];
13
+ return values.flatMap((v) => String(v).split(",")).map((v) => v.trim()).filter((v) => v.length > 0);
14
+ }
15
+ function globToRegExp(pattern) {
16
+ let out = "^";
17
+ for (const ch of pattern) {
18
+ if (ch === "*") out += ".*";
19
+ else if (ch === "?") out += ".";
20
+ else out += escapeRegex(ch);
21
+ }
22
+ return new RegExp(out + "$");
23
+ }
24
+ function matchesGlob(value, pattern) {
25
+ return globToRegExp(pattern.toLowerCase()).test(value.toLowerCase());
26
+ }
27
+ function normalizeRoles(roles) {
28
+ const arr = Array.isArray(roles) ? roles : [roles];
29
+ return [...new Set(
30
+ arr.flatMap((r) => /^\{.*\}$/s.test(r) ? arrayLiteralElements(r) : [r]).map((r) => r.trim()).filter(Boolean)
31
+ )].sort();
32
+ }
33
+ function arrayLiteralElements(literal) {
34
+ const inner = literal.slice(1, -1);
35
+ const out = [];
36
+ let i = 0;
37
+ while (i < inner.length) {
38
+ let value = "";
39
+ if (inner[i] === '"') {
40
+ for (i++; i < inner.length && inner[i] !== '"'; i++) {
41
+ if (inner[i] === "\\") i++;
42
+ value += inner[i];
43
+ }
44
+ i++;
45
+ } else {
46
+ const end = inner.indexOf(",", i);
47
+ value = inner.slice(i, end === -1 ? inner.length : end);
48
+ i = end === -1 ? inner.length : end;
49
+ }
50
+ out.push(value);
51
+ if (inner[i] === ",") i++;
52
+ }
53
+ return out;
54
+ }
55
+
56
+ export {
57
+ slugify,
58
+ escapeRegex,
59
+ parseFlagList,
60
+ globToRegExp,
61
+ matchesGlob,
62
+ normalizeRoles
63
+ };
64
+ //# sourceMappingURL=chunk-DQQ5E563.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/strings.ts"],"sourcesContent":["/**\n * Shared string manipulation utilities.\n */\n\n/** Maximum length for generated slugs. */\nconst MAX_SLUG_LENGTH = 60\n\n/**\n * Convert a human-readable string to a filename-safe slug.\n * Lowercases, replaces non-alphanumeric chars with separator, trims edges.\n */\nexport function slugify(name: string, separator = '_'): string {\n const pattern = new RegExp(`[^a-z0-9]+`, 'g')\n const edgePattern = new RegExp(`^${escapeRegex(separator)}|${escapeRegex(separator)}$`, 'g')\n return name\n .toLowerCase()\n .replace(pattern, separator)\n .replace(edgePattern, '')\n .slice(0, MAX_SLUG_LENGTH)\n}\n\n/** Escape every regex metacharacter, so a value can be matched literally. */\nexport function escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Split a repeatable CLI flag into individual values.\n *\n * `--x=a,b --x=c` and `--x=a --x=b --x=c` mean the same thing; oclif hands over\n * the raw strings, and a comma is the natural separator for the lists these\n * flags take — table names, issue ids — none of which can contain one.\n */\nexport function parseFlagList(values?: string[]): string[] {\n if (!Array.isArray(values)) return []\n return values\n .flatMap(v => String(v).split(','))\n .map(v => v.trim())\n .filter(v => v.length > 0)\n}\n\n/**\n * Compile a `*`/`?` glob to an anchored regular expression.\n *\n * The same two wildcards `@dbdiff/cli` supports, so a pattern means one thing\n * whether it reaches dbdiff or is matched here. Every other character is\n * escaped, so a value containing regex metacharacters cannot turn a filter into\n * a different pattern. Both are linear: the pattern is anchored and has no\n * nested quantifiers.\n */\nexport function globToRegExp(pattern: string): RegExp {\n let out = '^'\n for (const ch of pattern) {\n if (ch === '*') out += '.*'\n else if (ch === '?') out += '.'\n else out += escapeRegex(ch)\n }\n return new RegExp(out + '$')\n}\n\n/** Does `value` match a `*`/`?` glob? Case-insensitive. */\nexport function matchesGlob(value: string, pattern: string): boolean {\n return globToRegExp(pattern.toLowerCase()).test(value.toLowerCase())\n}\n\n/**\n * Parse Postgres name[] which may arrive as a JS array or Postgres literal `{a,b}`.\n * Returns a sorted, deduplicated array of role names.\n *\n * An element with a space, comma or quote in it is double-quoted in the\n * literal, with `\\\\` escaping a quote or backslash: `{\"Admins \\\\\"A\\\\\"\",anon}`.\n * Split on commas, such a role kept its literal quoting and was then quoted\n * again as a name, so the policy went to a role that did not exist.\n */\nexport function normalizeRoles(roles: string[] | string): string[] {\n const arr = Array.isArray(roles) ? roles : [roles]\n return [...new Set(\n arr\n .flatMap(r => /^\\{.*\\}$/s.test(r) ? arrayLiteralElements(r) : [r])\n .map(r => r.trim())\n .filter(Boolean),\n )].sort()\n}\n\n/** The elements of a one-dimensional PostgreSQL array literal. */\nfunction arrayLiteralElements(literal: string): string[] {\n const inner = literal.slice(1, -1)\n const out: string[] = []\n let i = 0\n while (i < inner.length) {\n let value = ''\n if (inner[i] === '\"') {\n for (i++; i < inner.length && inner[i] !== '\"'; i++) {\n if (inner[i] === '\\\\') i++\n value += inner[i]\n }\n i++\n } else {\n const end = inner.indexOf(',', i)\n value = inner.slice(i, end === -1 ? inner.length : end)\n i = end === -1 ? inner.length : end\n }\n out.push(value)\n if (inner[i] === ',') i++\n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ACV;AAGA,SAAS,qBAAqB,SAA2B;AACvD,QAAM,QAAQ,QAAQ,MAAM,GAAG,EAAE;AACjC,QAAM,MAAgB,CAAC;AACvB,MAAI,IAAI;AACR,SAAO,IAAI,MAAM,QAAQ;AACvB,QAAI,QAAQ;AACZ,QAAI,MAAM,CAAC,MAAM,KAAK;AACpB,WAAK,KAAK,IAAI,MAAM,UAAU,MAAM,CAAC,MAAM,KAAK,KAAK;AACnD,YAAI,MAAM,CAAC,MAAM,KAAM;AACvB,iBAAS,MAAM,CAAC;AAAA,MAClB;AACA;AAAA,IACF,OAAO;AACL,YAAM,MAAM,MAAM,QAAQ,KAAK,CAAC;AAChC,cAAQ,MAAM,MAAM,GAAG,QAAQ,KAAK,MAAM,SAAS,GAAG;AACtD,UAAI,QAAQ,KAAK,MAAM,SAAS;AAAA,IAClC;AACA,QAAI,KAAK,KAAK;AACd,QAAI,MAAM,CAAC,MAAM,IAAK;AAAA,EACxB;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,94 @@
1
+ // src/utils/sql-split.ts
2
+ var DOLLAR_TAG = /^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/;
3
+ function splitSqlStatements(sql) {
4
+ const statements = [];
5
+ let start = 0;
6
+ let i = 0;
7
+ let blockDepth = 0;
8
+ const push = (end) => {
9
+ const piece = sql.slice(start, end).trim();
10
+ if (piece.length > 0) statements.push(piece);
11
+ };
12
+ while (i < sql.length) {
13
+ if (blockDepth > 0) {
14
+ if (sql.startsWith("/*", i)) {
15
+ blockDepth++;
16
+ i += 2;
17
+ continue;
18
+ }
19
+ if (sql.startsWith("*/", i)) {
20
+ blockDepth--;
21
+ i += 2;
22
+ continue;
23
+ }
24
+ i++;
25
+ continue;
26
+ }
27
+ if (sql.startsWith("/*", i)) {
28
+ blockDepth = 1;
29
+ i += 2;
30
+ continue;
31
+ }
32
+ if (sql.startsWith("--", i)) {
33
+ const newline = sql.indexOf("\n", i);
34
+ i = newline === -1 ? sql.length : newline + 1;
35
+ continue;
36
+ }
37
+ const ch = sql[i];
38
+ if (ch === "'" || ch === '"') {
39
+ i++;
40
+ while (i < sql.length) {
41
+ if (sql[i] !== ch) {
42
+ i++;
43
+ continue;
44
+ }
45
+ if (sql[i + 1] === ch) {
46
+ i += 2;
47
+ continue;
48
+ }
49
+ i++;
50
+ break;
51
+ }
52
+ continue;
53
+ }
54
+ if (ch === "$") {
55
+ const tag = DOLLAR_TAG.exec(sql.slice(i));
56
+ if (tag) {
57
+ const close = sql.indexOf(tag[0], i + tag[0].length);
58
+ i = close === -1 ? sql.length : close + tag[0].length;
59
+ continue;
60
+ }
61
+ i++;
62
+ continue;
63
+ }
64
+ if (ch === ";") {
65
+ push(i);
66
+ i++;
67
+ start = i;
68
+ continue;
69
+ }
70
+ i++;
71
+ }
72
+ push(sql.length);
73
+ return statements;
74
+ }
75
+ function isCommentOnly(statement) {
76
+ const meaningful = statement.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("--"));
77
+ return meaningful.length === 0;
78
+ }
79
+ var PSQL_WRAPPER_LINE = /^[ \t]*\\(?:un)?restrict\b[^\n]*$/gm;
80
+ function stripPsqlMetaCommands(sql) {
81
+ return sql.replace(PSQL_WRAPPER_LINE, "");
82
+ }
83
+ function isPsqlMetaCommand(statement) {
84
+ const meaningful = statement.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("--"));
85
+ return meaningful.length > 0 && meaningful.every((line) => line.startsWith("\\"));
86
+ }
87
+
88
+ export {
89
+ splitSqlStatements,
90
+ isCommentOnly,
91
+ stripPsqlMetaCommands,
92
+ isPsqlMetaCommand
93
+ };
94
+ //# sourceMappingURL=chunk-G2DIPIYU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/sql-split.ts"],"sourcesContent":["/**\n * Splitting SQL text into statements.\n *\n * Kept apart from the quoting helpers in `sql.ts` because this is a scanner\n * rather than an escaper, and it is only needed where SQL arrives from outside\n * — a pg_dump, a migration file — rather than being generated here.\n */\n\n/** `$$` or `$tag$`, anchored at the current position. */\nconst DOLLAR_TAG = /^\\$(?:[A-Za-z_][A-Za-z0-9_]*)?\\$/\n\n/**\n * Split SQL into individual statements.\n *\n * Splitting on `;` alone breaks the moment the SQL contains a routine body: a\n * `CREATE FUNCTION ... AS $$ BEGIN ... ; ... END; $$;` is shredded into three\n * fragments, none of which parse, and whatever depends on the function fails\n * after them. That is what `restore` did to a pg_dump's functions and their\n * triggers (issue #80).\n *\n * The text is walked once, tracking the four things that can hold a semicolon\n * without ending a statement:\n *\n * - `'single quoted'`, where `''` is an escaped quote and not a close\n * - `\"quoted identifiers\"`, same doubling rule\n * - `$tag$ dollar quoted $tag$`, which is how routine bodies arrive\n * - line comments, and block comments, which nest in PostgreSQL\n *\n * Statements come back trimmed with the trailing `;` removed, and empty\n * fragments dropped. Comments are left in place: they are part of the\n * statement's text, and a caller wanting a bare statement can say so.\n */\nexport function splitSqlStatements(sql: string): string[] {\n const statements: string[] = []\n let start = 0\n let i = 0\n let blockDepth = 0\n\n const push = (end: number) => {\n const piece = sql.slice(start, end).trim()\n if (piece.length > 0) statements.push(piece)\n }\n\n while (i < sql.length) {\n if (blockDepth > 0) {\n if (sql.startsWith('/*', i)) { blockDepth++; i += 2; continue }\n if (sql.startsWith('*/', i)) { blockDepth--; i += 2; continue }\n i++\n continue\n }\n\n if (sql.startsWith('/*', i)) { blockDepth = 1; i += 2; continue }\n\n if (sql.startsWith('--', i)) {\n const newline = sql.indexOf('\\n', i)\n i = newline === -1 ? sql.length : newline + 1\n continue\n }\n\n const ch = sql[i]\n\n if (ch === \"'\" || ch === '\"') {\n i++\n while (i < sql.length) {\n if (sql[i] !== ch) { i++; continue }\n // A doubled quote is an escape, not the end of the run.\n if (sql[i + 1] === ch) { i += 2; continue }\n i++\n break\n }\n continue\n }\n\n if (ch === '$') {\n const tag = DOLLAR_TAG.exec(sql.slice(i))\n if (tag) {\n const close = sql.indexOf(tag[0], i + tag[0].length)\n i = close === -1 ? sql.length : close + tag[0].length\n continue\n }\n i++\n continue\n }\n\n if (ch === ';') {\n push(i)\n i++\n start = i\n continue\n }\n\n i++\n }\n\n push(sql.length)\n return statements\n}\n\n/** Whether a statement is nothing but comments and whitespace. */\nexport function isCommentOnly(statement: string): boolean {\n const meaningful = statement\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line.length > 0 && !line.startsWith('--'))\n return meaningful.length === 0\n}\n\n/**\n * The `\\restrict` / `\\unrestrict` wrappers pg_dump 16 and later emit.\n *\n * Matched as whole lines, and only these two commands rather than anything\n * beginning with a backslash: a line inside a dollar-quoted routine body could\n * start with one, and rewriting a function's body would be worse than the\n * problem being solved.\n */\nconst PSQL_WRAPPER_LINE = /^[ \\t]*\\\\(?:un)?restrict\\b[^\\n]*$/gm\n\n/**\n * Remove psql meta-commands, which only psql understands.\n *\n * Done to the text *before* it is split, because these commands are terminated\n * by the end of the line rather than by a semicolon. Dropping them afterwards\n * as whole statements took the following statement with them — `\\restrict abc`\n * and the `CREATE TABLE` under it are one fragment when nothing separates them\n * (issue #80). Sent to the server they fail with `syntax error at or near \"\\\"`.\n */\nexport function stripPsqlMetaCommands(sql: string): string {\n return sql.replace(PSQL_WRAPPER_LINE, '')\n}\n\n/**\n * Whether a statement is nothing but psql meta-commands and comments.\n *\n * A safety net for anything `stripPsqlMetaCommands` does not cover. It\n * deliberately requires *every* meaningful line to be a meta-command, so a\n * statement that also carries SQL is never discarded wholesale.\n */\nexport function isPsqlMetaCommand(statement: string): boolean {\n const meaningful = statement\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line.length > 0 && !line.startsWith('--'))\n\n return meaningful.length > 0 && meaningful.every(line => line.startsWith('\\\\'))\n}\n"],"mappings":";AASA,IAAM,aAAa;AAuBZ,SAAS,mBAAmB,KAAuB;AACxD,QAAM,aAAuB,CAAC;AAC9B,MAAI,QAAQ;AACZ,MAAI,IAAI;AACR,MAAI,aAAa;AAEjB,QAAM,OAAO,CAAC,QAAgB;AAC5B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K,IAAI,MAAM;AACf,SAAO;AACT;AAGO,SAAS,cAAc,WAA4B;AACxD,QAAM,aAAa,UAChB,MAAM,IAAI,EACV,IAAI,UAAQ,KAAK,KAAK,CAAC,EACvB,OAAO,UAAQ,KAAK,SAAS,KAAK,CAAC,KAAK,WAAW,IAAI,CAAC;AAC3D,SAAO,WAAW,WAAW;AAC/B;AAUA,IAAM,oBAAoB;AAWnB,SAAS,sBAAsB,KAAqB;AACzD,SAAO,IAAI,QAAQ,mBAAmB,EAAE;AAC1C;AASO,SAAS,kBAAkB,WAA4B;AAC5D,QAAM,aAAa,UAChB,MAAM,IAAI,EACV,IAAI,UAAQ,KAAK,KAAK,CAAC,EACvB,OAAO,UAAQ,KAAK,SAAS,KAAK,CAAC,KAAK,WAAW,IAAI,CAAC;AAE3D,SAAO,WAAW,SAAS,KAAK,WAAW,MAAM,UAAQ,KAAK,WAAW,IAAI,CAAC;AAChF;","names":[]}
@@ -0,0 +1,16 @@
1
+ // src/pg-errors.ts
2
+ var ABSENT_ON_TARGET = /* @__PURE__ */ new Set(["42P01", "42883", "3F000", "42704"]);
3
+ var UNDEFINED_COLUMN = "42703";
4
+ var EXTENSION_UNAVAILABLE = /* @__PURE__ */ new Set(["0A000", "58P01"]);
5
+ function sqlState(err) {
6
+ const code = err?.code;
7
+ return typeof code === "string" ? code : void 0;
8
+ }
9
+
10
+ export {
11
+ ABSENT_ON_TARGET,
12
+ UNDEFINED_COLUMN,
13
+ EXTENSION_UNAVAILABLE,
14
+ sqlState
15
+ };
16
+ //# sourceMappingURL=chunk-H5MJ5DFX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/pg-errors.ts"],"sourcesContent":["/**\n * SQLSTATEs for \"that does not exist here\": a relation, function, schema or\n * other object the statement names is missing from the database it ran on.\n */\nexport const ABSENT_ON_TARGET: ReadonlySet<string> = new Set(['42P01', '42883', '3F000', '42704'])\n\n/** A column the statement names is missing. */\nexport const UNDEFINED_COLUMN = '42703'\n\n/** SQLSTATEs for an extension the server does not ship. */\nexport const EXTENSION_UNAVAILABLE: ReadonlySet<string> = new Set(['0A000', '58P01'])\n\n/** The SQLSTATE of a PostgreSQL error, if it is one. */\nexport function sqlState(err: unknown): string | undefined {\n const code = (err as { code?: unknown } | null)?.code\n return typeof code === 'string' ? code : undefined\n}\n"],"mappings":";AAIO,IAAM,mBAAwC,oBAAI,IAAI,CAAC,SAAS,SAAS,SAAS,OAAO,CAAC;AAG1F,IAAM,mBAAmB;AAGzB,IAAM,wBAA6C,oBAAI,IAAI,CAAC,SAAS,OAAO,CAAC;AAG7E,SAAS,SAAS,KAAkC;AACzD,QAAM,OAAQ,KAAmC;AACjD,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;","names":[]}
@@ -0,0 +1,248 @@
1
+ import {
2
+ isCommentOnly,
3
+ splitSqlStatements
4
+ } from "./chunk-G2DIPIYU.js";
5
+ import {
6
+ captureSnapshot,
7
+ findLatestSnapshot,
8
+ loadSnapshot
9
+ } from "./chunk-YVDSR4GM.js";
10
+ import {
11
+ slugify
12
+ } from "./chunk-DQQ5E563.js";
13
+ import {
14
+ MIGRATIONS_SUBDIR,
15
+ SUPAFORGE_DIR
16
+ } from "./chunk-6WAMNZLO.js";
17
+
18
+ // src/migration.ts
19
+ import { mkdir, writeFile, readFile, readdir } from "fs/promises";
20
+ import { join, resolve } from "path";
21
+ function migrationsDir(cwd) {
22
+ return resolve(cwd, SUPAFORGE_DIR, MIGRATIONS_SUBDIR);
23
+ }
24
+ async function backup(options) {
25
+ const cwd = options.cwd ?? process.cwd();
26
+ const previousDir = await findLatestSnapshot(cwd);
27
+ const previousManifest = previousDir ? await loadSnapshot(previousDir) : null;
28
+ const snapshot = await captureSnapshot({ ...options, cwd });
29
+ const description = options.description ?? "auto-backup";
30
+ const isBaseline = !previousManifest;
31
+ const migration = isBaseline ? await generateBaselineMigration(snapshot, cwd, description) : await generateDiffMigration(previousDir, snapshot, cwd, description);
32
+ let migrationFile = null;
33
+ if (migration) {
34
+ const mDir = migrationsDir(cwd);
35
+ await mkdir(mDir, { recursive: true });
36
+ const filename = `${snapshot.timestamp}_${slugify(description, "-")}.json`;
37
+ migrationFile = join(mDir, filename);
38
+ await writeFile(migrationFile, JSON.stringify(migration, null, 2) + "\n");
39
+ }
40
+ return { snapshot, migration, migrationFile, isBaseline };
41
+ }
42
+ async function generateBaselineMigration(snapshot, cwd, description) {
43
+ const sqlUp = [];
44
+ const sqlDown = [];
45
+ const apiUp = [];
46
+ const layers = [];
47
+ for (const [layer, info] of Object.entries(snapshot.manifest.layers)) {
48
+ if (!info.captured) continue;
49
+ layers.push(layer);
50
+ if (layer === "auth" || layer === "edge-functions") {
51
+ continue;
52
+ }
53
+ if (layer === "storage" && info.file === "storage-buckets.json") {
54
+ continue;
55
+ }
56
+ if (info.file.endsWith(".sql")) {
57
+ try {
58
+ const content = await readFile(join(snapshot.dir, info.file), "utf-8");
59
+ const statements = extractStatements(content);
60
+ if (statements.length > 0) {
61
+ sqlUp.push(...statements);
62
+ }
63
+ } catch {
64
+ }
65
+ }
66
+ }
67
+ return {
68
+ version: snapshot.timestamp,
69
+ description: `baseline: ${description}`,
70
+ parent: null,
71
+ layers,
72
+ up: { sql: sqlUp, api: apiUp },
73
+ down: { sql: sqlDown, api: [] }
74
+ };
75
+ }
76
+ async function generateDiffMigration(previousDir, snapshot, _cwd, description) {
77
+ const previousManifest = await loadSnapshot(previousDir);
78
+ const sqlUp = [];
79
+ const sqlDown = [];
80
+ const apiUp = [];
81
+ const apiDown = [];
82
+ const layers = [];
83
+ for (const layer of ["rls", "cron", "webhooks", "extensions", "storage-policies"]) {
84
+ const file = layerToFile(layer);
85
+ const prevFile = layerToFile(layer);
86
+ try {
87
+ const prevContent = await readFile(join(previousDir, prevFile), "utf-8").catch(() => "");
88
+ const newContent = await readFile(join(snapshot.dir, file), "utf-8").catch(() => "");
89
+ if (prevContent === newContent) continue;
90
+ const prevStatements = new Set(extractStatements(prevContent));
91
+ const newStatements = new Set(extractStatements(newContent));
92
+ const added = [...newStatements].filter((s) => !prevStatements.has(s));
93
+ const removed = [...prevStatements].filter((s) => !newStatements.has(s));
94
+ if (added.length > 0 || removed.length > 0) {
95
+ layers.push(layer === "storage-policies" ? "storage" : layer);
96
+ sqlUp.push(...added);
97
+ for (const statement of removed) {
98
+ const inverse = inverseStatement(statement);
99
+ if (inverse) sqlUp.push(inverse);
100
+ }
101
+ sqlDown.push(...removed);
102
+ for (const statement of added) {
103
+ const inverse = inverseStatement(statement);
104
+ if (inverse) sqlDown.push(inverse);
105
+ }
106
+ }
107
+ } catch {
108
+ }
109
+ }
110
+ for (const layer of ["auth", "storage-buckets", "edge-functions"]) {
111
+ const file = layerToFile(layer);
112
+ try {
113
+ const prevContent = await readFile(join(previousDir, file), "utf-8").catch(() => "{}");
114
+ const newContent = await readFile(join(snapshot.dir, file), "utf-8").catch(() => "{}");
115
+ if (prevContent === newContent) continue;
116
+ layers.push(layer === "storage-buckets" ? "storage" : layer);
117
+ } catch {
118
+ }
119
+ }
120
+ try {
121
+ const prevSchema = await readFile(join(previousDir, "schema.json"), "utf-8").catch(() => "");
122
+ const newSchema = await readFile(join(snapshot.dir, "schema.json"), "utf-8").catch(() => "");
123
+ if (prevSchema !== newSchema) {
124
+ layers.push("schema");
125
+ sqlUp.push(...schemaChangeNotes(prevSchema, newSchema));
126
+ }
127
+ } catch {
128
+ }
129
+ return {
130
+ version: snapshot.timestamp,
131
+ description,
132
+ parent: previousManifest.timestamp,
133
+ layers: [...new Set(layers)],
134
+ up: { sql: sqlUp, api: apiUp },
135
+ down: { sql: sqlDown, api: apiDown }
136
+ };
137
+ }
138
+ async function loadMigrations(cwd = process.cwd()) {
139
+ const dir = migrationsDir(cwd);
140
+ try {
141
+ const entries = await readdir(dir);
142
+ const jsonFiles = entries.filter((e) => e.endsWith(".json")).sort();
143
+ const migrations = [];
144
+ for (const file of jsonFiles) {
145
+ const raw = await readFile(join(dir, file), "utf-8");
146
+ migrations.push(JSON.parse(raw));
147
+ }
148
+ return migrations;
149
+ } catch {
150
+ return [];
151
+ }
152
+ }
153
+ async function listMigrationFiles(cwd = process.cwd()) {
154
+ const dir = migrationsDir(cwd);
155
+ try {
156
+ const entries = await readdir(dir);
157
+ const jsonFiles = entries.filter((e) => e.endsWith(".json")).sort();
158
+ const results = [];
159
+ for (const file of jsonFiles) {
160
+ const raw = await readFile(join(dir, file), "utf-8");
161
+ const m = JSON.parse(raw);
162
+ results.push({ file, version: m.version, description: m.description, layers: m.layers });
163
+ }
164
+ return results;
165
+ } catch {
166
+ return [];
167
+ }
168
+ }
169
+ function layerToFile(layer) {
170
+ switch (layer) {
171
+ case "rls":
172
+ return "rls.sql";
173
+ case "cron":
174
+ return "cron.sql";
175
+ case "webhooks":
176
+ return "webhooks.sql";
177
+ case "extensions":
178
+ return "extensions.sql";
179
+ case "storage-policies":
180
+ return "storage-policies.sql";
181
+ case "auth":
182
+ return "auth.json";
183
+ case "storage-buckets":
184
+ return "storage-buckets.json";
185
+ case "edge-functions":
186
+ return "edge-functions.json";
187
+ default:
188
+ return `${layer}.sql`;
189
+ }
190
+ }
191
+ function extractStatements(content) {
192
+ if (!content) return [];
193
+ return splitSqlStatements(content).filter((statement) => !isCommentOnly(statement)).map(stripLeadingComments).filter((statement) => statement.length > 0).map((statement) => statement.endsWith(";") ? statement : `${statement};`);
194
+ }
195
+ function stripLeadingComments(statement) {
196
+ const lines = statement.split("\n");
197
+ let start = 0;
198
+ while (start < lines.length) {
199
+ const line = lines[start].trim();
200
+ if (line === "" || line.startsWith("--")) {
201
+ start++;
202
+ continue;
203
+ }
204
+ break;
205
+ }
206
+ return lines.slice(start).join("\n").trim();
207
+ }
208
+ function inverseStatement(statement) {
209
+ const sql = statement.trim();
210
+ const cron = /\bcron\.schedule\s*\(\s*('(?:[^']|'')*')/i.exec(sql);
211
+ if (cron) return `SELECT cron.unschedule(${cron[1]});`;
212
+ const policy = /\bCREATE\s+POLICY\s+("[^"]+"|[\w$]+)\s+ON\s+((?:"[^"]+"|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|[\w$]+))?)/i.exec(sql);
213
+ if (policy) return `DROP POLICY IF EXISTS ${policy[1]} ON ${policy[2]};`;
214
+ const trigger = /\bCREATE\s+TRIGGER\s+("[^"]+"|[\w$]+)[\s\S]*?\bON\s+((?:"[^"]+"|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|[\w$]+))?)/i.exec(sql);
215
+ if (trigger) return `DROP TRIGGER IF EXISTS ${trigger[1]} ON ${trigger[2]};`;
216
+ const extension = /\bCREATE\s+EXTENSION\s+(?:IF\s+NOT\s+EXISTS\s+)?("[^"]+"|[\w$]+)/i.exec(sql);
217
+ if (extension) return `DROP EXTENSION IF EXISTS ${extension[1]};`;
218
+ return null;
219
+ }
220
+ function schemaChangeNotes(previousJson, currentJson) {
221
+ const notes = [
222
+ "-- The schema changed. This migration carries no DDL for it: deriving one",
223
+ "-- from two introspection documents is what @dbdiff/cli does, and it needs",
224
+ "-- two live databases. Generate it with `supaforge migrate create`."
225
+ ];
226
+ try {
227
+ const before = JSON.parse(previousJson);
228
+ const after = JSON.parse(currentJson);
229
+ for (const kind of ["tables", "views", "functions", "triggers", "sequences", "enums"]) {
230
+ const names = (list) => new Set((list ?? []).map((o) => `${o.schema ?? "public"}.${o.name ?? "?"}`));
231
+ const from = names(before[kind]);
232
+ const to = names(after[kind]);
233
+ const added = [...to].filter((n) => !from.has(n)).sort();
234
+ const removed = [...from].filter((n) => !to.has(n)).sort();
235
+ if (added.length > 0) notes.push(`-- ${kind} added: ${added.join(", ")}`);
236
+ if (removed.length > 0) notes.push(`-- ${kind} removed: ${removed.join(", ")}`);
237
+ }
238
+ } catch {
239
+ }
240
+ return notes;
241
+ }
242
+
243
+ export {
244
+ backup,
245
+ loadMigrations,
246
+ listMigrationFiles
247
+ };
248
+ //# sourceMappingURL=chunk-KIFJGON5.js.map