@akal/supaforge 0.0.33 → 0.0.35

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 (55) hide show
  1. package/README.md +67 -14
  2. package/dist/base-command.d.ts +1 -1
  3. package/dist/base-command.js +4 -3
  4. package/dist/{branch-C4ndfoj5.d.ts → branch-BppjQBv_.d.ts} +1 -1
  5. package/dist/{chunk-4IVN7QVY.js → chunk-44UVQJV2.js} +159 -18
  6. package/dist/{chunk-3HGAV5CC.js → chunk-4AGJRRBT.js} +390 -43
  7. package/dist/{chunk-SQPCWGQO.js → chunk-4M6OQLPO.js} +22 -121
  8. package/dist/{chunk-2SELREHW.js → chunk-5Q6LSLA3.js} +56 -9
  9. package/dist/{chunk-7NAZGZPV.js → chunk-7N63OPFN.js} +28 -21
  10. package/dist/chunk-AGONS5JJ.js +242 -0
  11. package/dist/chunk-GQPGH6YR.js +50 -0
  12. package/dist/{chunk-GEHPTPNZ.js → chunk-H2D3YSKM.js} +7 -3
  13. package/dist/{chunk-6Q7MHFBM.js → chunk-HNJ6BNNZ.js} +2 -2
  14. package/dist/{chunk-6WAMNZLO.js → chunk-KNXHLVF7.js} +126 -4
  15. package/dist/{chunk-DMIWAJRB.js → chunk-NEM5AEPQ.js} +172 -22
  16. package/dist/{chunk-6LJERPUN.js → chunk-NX2KKUS7.js} +20 -12
  17. package/dist/{chunk-SC2XHGIS.js → chunk-O5ERC2SE.js} +3 -3
  18. package/dist/{chunk-MIRLB5JM.js → chunk-SM7HP6EP.js} +64 -182
  19. package/dist/{chunk-BUOWHE36.js → chunk-T7GMPGUO.js} +613 -66
  20. package/dist/{chunk-G2DIPIYU.js → chunk-WK5YTINL.js} +29 -2
  21. package/dist/{chunk-UWAVXC57.js → chunk-WNTCZM2J.js} +34 -482
  22. package/dist/{chunk-GZREXCQZ.js → chunk-XLZCX6R2.js} +17 -10
  23. package/dist/{chunk-ORQJVE57.js → chunk-YWERIWFD.js} +18 -17
  24. package/dist/{chunk-NTUASFQ3.js → chunk-YZM76W22.js} +5 -5
  25. package/dist/{chunk-BLKJWDTL.js → chunk-ZI435CAU.js} +2 -2
  26. package/dist/commands/clone.d.ts +2 -2
  27. package/dist/commands/clone.js +14 -13
  28. package/dist/commands/diff.d.ts +37 -23
  29. package/dist/commands/diff.js +20 -17
  30. package/dist/commands/hukam.d.ts +2 -3
  31. package/dist/commands/hukam.js +16 -15
  32. package/dist/commands/init.d.ts +1 -1
  33. package/dist/commands/init.js +5 -1
  34. package/dist/commands/mcp.js +16 -10
  35. package/dist/commands/migrate/baseline.d.ts +1 -1
  36. package/dist/commands/migrate/baseline.js +5 -4
  37. package/dist/commands/migrate/create.d.ts +1 -1
  38. package/dist/commands/migrate/create.js +15 -9
  39. package/dist/commands/migrate/list.d.ts +1 -1
  40. package/dist/commands/migrate/list.js +6 -5
  41. package/dist/commands/migrate/run.d.ts +4 -1
  42. package/dist/commands/migrate/run.js +10 -8
  43. package/dist/commands/report.d.ts +1 -1
  44. package/dist/commands/report.js +5 -4
  45. package/dist/commands/restore.d.ts +1 -1
  46. package/dist/commands/restore.js +14 -13
  47. package/dist/commands/snapshot.d.ts +8 -1
  48. package/dist/commands/snapshot.js +37 -9
  49. package/dist/commands/sync.d.ts +2 -3
  50. package/dist/commands/sync.js +16 -15
  51. package/dist/{config-CTbeRlJk.d.ts → config-l3ggjw9r.d.ts} +2 -0
  52. package/dist/index.d.ts +21 -4
  53. package/dist/index.js +15 -15
  54. package/package.json +2 -2
  55. package/dist/chunk-DQQ5E563.js +0 -64
@@ -1,10 +1,26 @@
1
1
  // src/utils/sql-split.ts
2
+ var ROUTINE_HEAD = /^CREATE\s+(?:OR\s+REPLACE\s+)?(?:FUNCTION|PROCEDURE)\b/i;
3
+ function withoutLeadingComments(text) {
4
+ let rest = text.trimStart();
5
+ for (; ; ) {
6
+ if (rest.startsWith("--")) {
7
+ const newline = rest.indexOf("\n");
8
+ rest = newline === -1 ? "" : rest.slice(newline + 1).trimStart();
9
+ } else if (rest.startsWith("/*")) {
10
+ const close = rest.indexOf("*/");
11
+ rest = close === -1 ? "" : rest.slice(close + 2).trimStart();
12
+ } else {
13
+ return rest;
14
+ }
15
+ }
16
+ }
2
17
  var DOLLAR_TAG = /^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/;
3
18
  function splitSqlStatements(sql) {
4
19
  const statements = [];
5
20
  let start = 0;
6
21
  let i = 0;
7
22
  let blockDepth = 0;
23
+ let beginDepth = 0;
8
24
  const push = (end) => {
9
25
  const piece = sql.slice(start, end).trim();
10
26
  if (piece.length > 0) statements.push(piece);
@@ -61,7 +77,18 @@ function splitSqlStatements(sql) {
61
77
  i++;
62
78
  continue;
63
79
  }
64
- if (ch === ";") {
80
+ if (/[A-Za-z_]/.test(ch)) {
81
+ const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(sql.slice(i, i + 64))[0];
82
+ const upper = word.toUpperCase();
83
+ if ((upper === "BEGIN" || upper === "CASE") && ROUTINE_HEAD.test(withoutLeadingComments(sql.slice(start, i)))) {
84
+ beginDepth++;
85
+ } else if (upper === "END" && beginDepth > 0) {
86
+ beginDepth--;
87
+ }
88
+ i += word.length;
89
+ continue;
90
+ }
91
+ if (ch === ";" && beginDepth === 0) {
65
92
  push(i);
66
93
  i++;
67
94
  start = i;
@@ -91,4 +118,4 @@ export {
91
118
  stripPsqlMetaCommands,
92
119
  isPsqlMetaCommand
93
120
  };
94
- //# sourceMappingURL=chunk-G2DIPIYU.js.map
121
+ //# sourceMappingURL=chunk-WK5YTINL.js.map
@@ -1,474 +1,11 @@
1
- import {
2
- bareName,
3
- createdPolicies,
4
- createdTriggers,
5
- createsOnlyPolicies,
6
- createsOnlyTriggers,
7
- destructiveReason,
8
- identifierMatcher,
9
- orderStatements,
10
- parseStatements,
11
- referencedTables,
12
- sqlSkeleton
13
- } from "./chunk-BUOWHE36.js";
14
- import {
15
- isCommentOnly,
16
- splitSqlStatements
17
- } from "./chunk-G2DIPIYU.js";
18
- import {
19
- globToRegExp,
20
- matchesGlob,
21
- parseFlagList
22
- } from "./chunk-DQQ5E563.js";
23
1
  import {
24
2
  Check,
25
- errMsg,
26
- pgClientConfig,
27
3
  pgQuery,
28
4
  quoteName
29
- } from "./chunk-SQPCWGQO.js";
5
+ } from "./chunk-4M6OQLPO.js";
30
6
  import {
31
7
  SUPABASE_PLATFORM_SCHEMAS
32
- } from "./chunk-6WAMNZLO.js";
33
-
34
- // src/utils/table-filter.ts
35
- var parseTableList = parseFlagList;
36
- function resolveTableFilter(config, cli = {}) {
37
- const cliTables = parseTableList(cli.tables);
38
- const cliExclude = parseTableList(cli.excludeTables);
39
- const configTables = Array.isArray(config?.checks?.tables) ? config.checks.tables : [];
40
- const configExclude = Array.isArray(config?.checks?.excludeTables) ? config.checks.excludeTables : [];
41
- const tables = cliTables.length > 0 ? cliTables : parseTableList(configTables);
42
- const excludeTables = [.../* @__PURE__ */ new Set([...parseTableList(configExclude), ...cliExclude])];
43
- const filter = {};
44
- if (tables.length > 0) filter.tables = tables;
45
- if (excludeTables.length > 0) filter.excludeTables = excludeTables;
46
- return filter;
47
- }
48
- function isFiltered(filter) {
49
- return Boolean(filter?.tables?.length || filter?.excludeTables?.length);
50
- }
51
- function describeTableFilter(filter) {
52
- if (!isFiltered(filter)) return null;
53
- const parts = [];
54
- if (filter?.tables?.length) parts.push(`only ${filter.tables.join(", ")}`);
55
- if (filter?.excludeTables?.length) parts.push(`excluding ${filter.excludeTables.join(", ")}`);
56
- return `Scoped to ${parts.join(", ")} \u2014 applies to the schema and data checks; other layers are unfiltered.`;
57
- }
58
- function matchesPattern(name, pattern) {
59
- const candidates = [name.toLowerCase()];
60
- const dot = name.indexOf(".");
61
- if (dot !== -1) candidates.push(name.slice(dot + 1).toLowerCase());
62
- const rx = globToRegExp(pattern.toLowerCase());
63
- return candidates.some((c) => rx.test(c));
64
- }
65
- function applyTableFilter(names, filter) {
66
- if (!isFiltered(filter)) return names;
67
- let out = names;
68
- if (filter?.tables?.length) {
69
- out = out.filter((n) => filter.tables.some((p) => matchesPattern(n, p)));
70
- }
71
- if (filter?.excludeTables?.length) {
72
- out = out.filter((n) => !filter.excludeTables.some((p) => matchesPattern(n, p)));
73
- }
74
- return out;
75
- }
76
-
77
- // src/types/drift.ts
78
- var CHECK_NAMES = [
79
- "schema",
80
- "rls",
81
- "rls-coverage",
82
- "edge-functions",
83
- "storage",
84
- "auth",
85
- "cron",
86
- "data",
87
- "webhooks",
88
- "realtime",
89
- "vault",
90
- "extensions",
91
- "migrations",
92
- "roles"
93
- ];
94
- var CHECK_META = {
95
- "schema": { number: 1, emoji: "\u{1F5C4}\uFE0F", label: "Schema" },
96
- "rls": { number: 2, emoji: "\u{1F512}", label: "RLS Policies" },
97
- "rls-coverage": { number: 3, emoji: "\u{1F6E1}\uFE0F", label: "RLS Coverage" },
98
- "edge-functions": { number: 4, emoji: "\u26A1", label: "Edge Functions" },
99
- "storage": { number: 5, emoji: "\u{1FAA3}", label: "Storage" },
100
- "auth": { number: 6, emoji: "\u{1F511}", label: "Auth Config" },
101
- "cron": { number: 7, emoji: "\u23F0", label: "Cron Jobs" },
102
- "data": { number: 8, emoji: "\u{1F5C3}\uFE0F", label: "Reference Data" },
103
- "webhooks": { number: 9, emoji: "\u26A1\u{1F517}", label: "Webhooks" },
104
- "realtime": { number: 10, emoji: "\u{1F4E1}", label: "Realtime Publications" },
105
- "vault": { number: 11, emoji: "\u{1F510}", label: "Vault Secrets" },
106
- "extensions": { number: 12, emoji: "\u{1F9E9}", label: "Postgres Extensions" },
107
- "migrations": { number: 13, emoji: "\u{1F4CB}", label: "Migration History" },
108
- "roles": { number: 14, emoji: "\u{1F464}", label: "Postgres Roles & Grants" }
109
- };
110
- var CHECK_KIND = {
111
- "schema": "comparison",
112
- "rls": "comparison",
113
- "rls-coverage": "posture",
114
- "edge-functions": "comparison",
115
- "storage": "comparison",
116
- "auth": "comparison",
117
- "cron": "comparison",
118
- "data": "comparison",
119
- "webhooks": "comparison",
120
- "realtime": "comparison",
121
- "vault": "comparison",
122
- "extensions": "comparison",
123
- "migrations": "posture",
124
- "roles": "comparison"
125
- };
126
- function isComparisonCheck(name) {
127
- return CHECK_KIND[name] === "comparison";
128
- }
129
-
130
- // src/promote.ts
131
- import pg from "pg";
132
-
133
- // src/pg-errors.ts
134
- var ABSENT_ON_TARGET = /* @__PURE__ */ new Set(["42P01", "42883", "3F000", "42704"]);
135
- var UNDEFINED_COLUMN = "42703";
136
- var EXTENSION_UNAVAILABLE = /* @__PURE__ */ new Set(["0A000", "58P01"]);
137
- function sqlState(err) {
138
- const code = err?.code;
139
- return typeof code === "string" ? code : void 0;
140
- }
141
-
142
- // src/promote.ts
143
- function outOfScopeReason(sql, filter) {
144
- if (!isFiltered(filter)) return null;
145
- const referenced = referencedTables(sql);
146
- if (referenced.length === 0) return null;
147
- const excluded = referenced.filter((t) => applyTableFilter([t], filter).length === 0);
148
- if (excluded.length === 0) return null;
149
- const names = excluded.map((t) => `'${t}'`).join(", ");
150
- const flag = filter?.tables?.length ? "--tables" : "--exclude-tables";
151
- const noun = excluded.length === 1 ? "table" : "tables";
152
- return `Depends on ${noun} ${names}, excluded by ${flag}`;
153
- }
154
- function isSelected(issueId, only) {
155
- if (!only?.length) return true;
156
- return only.some((pattern) => matchesGlob(issueId, pattern));
157
- }
158
- function withDefaultGrantRevokes(scanResult, only) {
159
- if (!only?.length) return only;
160
- const issues = scanResult.checks.flatMap((c) => c.issues);
161
- const created = new Set(issues.filter((i) => i.sql?.up && isSelected(i.id, only)).flatMap((i) => relationsCreatedBy(i.sql.up)));
162
- if (created.size === 0) return only;
163
- const companions = issues.filter((i) => i.id.startsWith("roles-grant-default-") && [...created].some((rel) => rel.endsWith("(") ? i.id.toLowerCase().includes(`.${rel}`) : i.id.toLowerCase().endsWith(`.${rel}`))).map((i) => i.id);
164
- return [...only, ...companions];
165
- }
166
- function relationsCreatedBy(sql) {
167
- const statements = parseStatements(sql);
168
- if (!statements) return [];
169
- return statements.flatMap(({ kind, node }) => {
170
- if (kind === "CreateFunctionStmt") {
171
- const parts = (node.funcname ?? []).map((n) => n.String?.sval ?? "");
172
- const name = parts.at(-1);
173
- return name ? [`${(parts.length > 1 ? parts.at(-2) : "public").toLowerCase()}.${name.toLowerCase()}(`] : [];
174
- }
175
- const rel = kind === "CreateStmt" ? node.relation : kind === "ViewStmt" ? node.view : kind === "CreateTableAsStmt" ? node.into?.rel : void 0;
176
- return rel?.relname ? [`${(rel.schemaname || "public").toLowerCase()}.${String(rel.relname).toLowerCase()}`] : [];
177
- });
178
- }
179
- function classifyIssue(issue, options, recreatedPolicies = /* @__PURE__ */ new Set()) {
180
- if (!isSelected(issue.id, options.only)) {
181
- return { kind: "skip", reason: "Not selected by --only" };
182
- }
183
- if (issue.manualOnly) return { kind: "skip", reason: issue.manualOnly };
184
- if (!issue.sql?.up) {
185
- if (issue.action?.method === "DELETE" && !options.allowDestructive) {
186
- return { kind: "skip", reason: `Destructive \u2014 ${issue.action.label}; re-run with --allow-destructive to apply` };
187
- }
188
- if (issue.action) return { kind: "api", action: issue.action };
189
- return { kind: "skip", reason: issue.manualOnly ?? "No SQL fix or API action available" };
190
- }
191
- if (!options.allowDestructive) {
192
- const why = issue.destructive ?? destructiveReason(issue.sql.up, recreatedPolicies);
193
- if (why) {
194
- return { kind: "skip", reason: `Destructive \u2014 ${why}; re-run with --allow-destructive to apply` };
195
- }
196
- }
197
- const outOfScope = outOfScopeReason(issue.sql.up, options.tableFilter);
198
- if (outOfScope) return { kind: "skip", reason: outOfScope };
199
- return { kind: "sql", sql: issue.sql.up };
200
- }
201
- function policiesCreatedBySelectedFixes(checks, options) {
202
- const created = /* @__PURE__ */ new Set();
203
- for (const check of checks) {
204
- const askedForExplicitly = options.checks?.includes(check.check) ?? false;
205
- if (!isComparisonCheck(check.check) && !options.applyPosture && !askedForExplicitly) continue;
206
- for (const issue of check.issues) {
207
- const sql = issue.sql?.up;
208
- if (!sql || !isSelected(issue.id, options.only)) continue;
209
- if (!options.allowDestructive && destructiveReason(sql)) continue;
210
- if (outOfScopeReason(sql, options.tableFilter)) continue;
211
- for (const key of createdPolicies(sql)) created.add(key);
212
- }
213
- }
214
- return created;
215
- }
216
- function planWork(scanResult, options = {}) {
217
- options = { ...options, only: withDefaultGrantRevokes(scanResult, options.only) };
218
- const plan = { sqlStatements: [], apiActions: [], skipped: [] };
219
- const relevant = scanResult.checks.filter(
220
- (c) => c.status === "drifted" && (!options.checks || options.checks.includes(c.check))
221
- );
222
- const recreatedPolicies = policiesCreatedBySelectedFixes(relevant, options);
223
- const keptBack = [];
224
- for (const checkResult of relevant) {
225
- const askedForExplicitly = options.checks?.includes(checkResult.check) ?? false;
226
- if (!isComparisonCheck(checkResult.check) && !options.applyPosture && !askedForExplicitly) {
227
- for (const issue of checkResult.issues) {
228
- plan.skipped.push({
229
- check: checkResult.check,
230
- issueId: issue.id,
231
- reason: "Posture finding about the target, not drift from the source \u2014 applying it would create drift. Use --apply-posture to apply anyway."
232
- });
233
- }
234
- continue;
235
- }
236
- for (const issue of checkResult.issues) {
237
- const at = { check: checkResult.check, issueId: issue.id };
238
- const outcome = classifyIssue(issue, options, recreatedPolicies);
239
- if (outcome.kind === "sql") plan.sqlStatements.push({ ...at, sql: outcome.sql });
240
- else if (outcome.kind === "api") plan.apiActions.push({ ...at, action: outcome.action });
241
- else {
242
- plan.skipped.push({ ...at, reason: outcome.reason });
243
- if (outcome.reason.startsWith("Destructive") && issue.sql?.down) {
244
- keptBack.push({ issueId: issue.id, definition: issue.sql.down });
245
- }
246
- }
247
- }
248
- }
249
- plan.sqlStatements = holdBackDropsStillInUse(plan.sqlStatements, keptBack, plan.skipped, downsOf(relevant));
250
- const dbdiffOrder = new Map(plan.sqlStatements.filter((s) => s.check === "schema").map((s, i) => [s, i]));
251
- plan.sqlStatements = orderStatements(plan.sqlStatements, (s) => s.sql, (s) => dbdiffOrder.get(s));
252
- plan.sqlStatements = dropDuplicateObjectFixes(plan.sqlStatements, plan.skipped);
253
- return plan;
254
- }
255
- var DROPS_SUPPORTING_OBJECT = /^\s*DROP\s+(?:TYPE|DOMAIN|FUNCTION|PROCEDURE|ROUTINE|SEQUENCE)\s+(?:IF\s+EXISTS\s+)?((?:"[^"]+"|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|[\w$]+))?)/i;
256
- function holdBackDropsStillInUse(statements, keptBack, skipped, downs = /* @__PURE__ */ new Map()) {
257
- const kept = keptBack.map((k) => ({ issueId: k.issueId, skeleton: sqlSkeleton(k.definition) }));
258
- let remaining = statements;
259
- for (let changed = kept.length > 0; changed; ) {
260
- changed = false;
261
- remaining = remaining.filter((statement) => {
262
- const names = droppedSupportingObjects(statement.sql);
263
- if (names.length === 0) return true;
264
- const user = kept.find((k) => names.some((n) => identifierMatcher(bareName(n)).test(k.skeleton)));
265
- if (!user) return true;
266
- skipped.push({
267
- check: statement.check,
268
- issueId: statement.issueId,
269
- reason: `Still used by what ${user.issueId} keeps, which is held back as destructive; re-run with --allow-destructive to apply both`
270
- });
271
- const definition = downs.get(statement.issueId);
272
- if (definition) kept.push({ issueId: user.issueId, skeleton: sqlSkeleton(definition) });
273
- changed = true;
274
- return false;
275
- });
276
- }
277
- return remaining;
278
- }
279
- function droppedSupportingObjects(sql) {
280
- const parts = splitSqlStatements(sql).filter((s) => !isCommentOnly(s));
281
- const names = parts.map((s) => DROPS_SUPPORTING_OBJECT.exec(sqlSkeleton(s))?.[1]);
282
- return names.length > 0 && names.every((n) => n !== void 0) ? names : [];
283
- }
284
- function downsOf(checks) {
285
- const downs = /* @__PURE__ */ new Map();
286
- for (const check of checks) {
287
- for (const issue of check.issues) {
288
- if (issue.sql?.down) downs.set(issue.id, issue.sql.down);
289
- }
290
- }
291
- return downs;
292
- }
293
- function dropDuplicateObjectFixes(statements, skipped) {
294
- const kinds = [
295
- { what: "policy", created: createdPolicies, onlyThis: createsOnlyPolicies, seen: /* @__PURE__ */ new Set() },
296
- { what: "trigger", created: createdTriggers, onlyThis: createsOnlyTriggers, seen: /* @__PURE__ */ new Set() }
297
- ];
298
- const kept = [];
299
- for (const statement of statements) {
300
- const duplicate = kinds.find((kind) => {
301
- const names = kind.created(statement.sql);
302
- return names.length > 0 && names.every((n) => kind.seen.has(n)) && kind.onlyThis(statement.sql);
303
- });
304
- if (duplicate) {
305
- skipped.push({
306
- check: statement.check,
307
- issueId: statement.issueId,
308
- reason: `Already created by the schema fix for the same ${duplicate.what}`
309
- });
310
- continue;
311
- }
312
- for (const kind of kinds) {
313
- for (const name of kind.created(statement.sql)) kind.seen.add(name);
314
- }
315
- kept.push(statement);
316
- }
317
- return kept;
318
- }
319
- async function executeSql(dbUrl, statements, result, transactional) {
320
- if (statements.length === 0) return;
321
- const client = new pg.Client(pgClientConfig(dbUrl));
322
- await client.connect();
323
- try {
324
- if (transactional) await runInTransaction(client, statements, result);
325
- else await runIndependently(client, statements, result);
326
- } finally {
327
- await client.end();
328
- }
329
- }
330
- async function runLikeApply(dbUrl, statements) {
331
- const result = { applied: [], skipped: [], errors: [] };
332
- await executeSql(dbUrl, statements, result, true);
333
- return result;
334
- }
335
- async function runIndependently(client, statements, result) {
336
- for (const stmt of statements) {
337
- try {
338
- await client.query(stmt.sql);
339
- result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
340
- } catch (err) {
341
- result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) });
342
- }
343
- }
344
- }
345
- function isEnumValueAddition(sql) {
346
- const statements = splitSqlStatements(sql).filter((s) => !isCommentOnly(s));
347
- return statements.length > 0 && statements.every((s) => /^\s*ALTER\s+TYPE\s+\S+\s+ADD\s+VALUE\b/i.test(sqlSkeleton(s)));
348
- }
349
- async function runInTransaction(client, statements, result) {
350
- const additions = statements.filter((s) => isEnumValueAddition(s.sql));
351
- const rest = statements.filter((s) => !isEnumValueAddition(s.sql));
352
- if (additions.length > 0 && !await runBatch(client, additions, result)) return;
353
- await runBatch(client, rest, result);
354
- }
355
- function unmetDependency(sql, err) {
356
- const code = sqlState(err);
357
- if (!code) return void 0;
358
- if (/^\s*CREATE\s+EXTENSION\b/i.test(sqlSkeleton(sql))) {
359
- return EXTENSION_UNAVAILABLE.has(code) ? "this server does not ship it" : void 0;
360
- }
361
- if (ABSENT_ON_TARGET.has(code) || code === UNDEFINED_COLUMN) {
362
- return "it needs something the target does not have";
363
- }
364
- return void 0;
365
- }
366
- async function runBatch(client, statements, result) {
367
- if (statements.length === 0) return true;
368
- const done = [];
369
- await client.query("BEGIN");
370
- let pending = statements;
371
- let unmet = [];
372
- while (pending.length > 0) {
373
- unmet = [];
374
- for (const stmt of pending) {
375
- await client.query("SAVEPOINT sf_fix");
376
- try {
377
- await client.query(stmt.sql);
378
- await client.query("RELEASE SAVEPOINT sf_fix");
379
- done.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
380
- } catch (err) {
381
- const why = unmetDependency(stmt.sql, err);
382
- if (why && await client.query("ROLLBACK TO SAVEPOINT sf_fix").then(() => true, () => false)) {
383
- unmet.push({ stmt, err, why });
384
- continue;
385
- }
386
- await client.query("ROLLBACK").catch(() => {
387
- });
388
- result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) });
389
- result.rolledBack = [...result.rolledBack ?? [], ...done];
390
- return false;
391
- }
392
- }
393
- if (unmet.length === pending.length) break;
394
- pending = unmet.map((u) => u.stmt);
395
- }
396
- await client.query("COMMIT");
397
- result.applied.push(...done);
398
- for (const { stmt, err, why } of unmet) {
399
- result.errors.push({
400
- check: stmt.check,
401
- issueId: stmt.issueId,
402
- error: `${errMsg(err)} \u2014 not applied: ${why}. The other fixes were.`
403
- });
404
- }
405
- return true;
406
- }
407
- async function executeApiActions(actions, fetchFn, result) {
408
- for (const act of actions) {
409
- try {
410
- const init = {
411
- method: act.action.method,
412
- headers: { "Content-Type": "application/json", ...act.action.headers }
413
- };
414
- if (act.action.body !== void 0) {
415
- init.body = JSON.stringify(act.action.body);
416
- }
417
- const res = await fetchFn(act.action.url, init);
418
- if (!res.ok) {
419
- const text = await res.text().catch(() => res.statusText);
420
- throw new Error(`${act.action.method} ${act.action.url} \u2192 ${res.status}: ${text}`);
421
- }
422
- result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label });
423
- } catch (err) {
424
- result.errors.push({ check: act.check, issueId: act.issueId, error: errMsg(err) });
425
- }
426
- }
427
- }
428
- async function promote(options) {
429
- const {
430
- dbUrl,
431
- scanResult,
432
- checks,
433
- dryRun = false,
434
- allowDestructive = false,
435
- tableFilter,
436
- only,
437
- applyPosture = false,
438
- transactional = true,
439
- fetchFn = globalThis.fetch.bind(globalThis)
440
- } = options;
441
- const { sqlStatements, apiActions, skipped } = planWork(scanResult, {
442
- checks,
443
- allowDestructive,
444
- tableFilter,
445
- only,
446
- applyPosture
447
- });
448
- const result = { applied: [], skipped, errors: [] };
449
- if (dryRun) {
450
- for (const stmt of sqlStatements) {
451
- result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
452
- }
453
- for (const act of apiActions) {
454
- result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label });
455
- }
456
- return result;
457
- }
458
- await executeSql(dbUrl, sqlStatements, result, transactional);
459
- if (result.rolledBack) {
460
- for (const act of apiActions) {
461
- result.skipped.push({
462
- check: act.check,
463
- issueId: act.issueId,
464
- reason: "Not attempted \u2014 the SQL fixes were rolled back"
465
- });
466
- }
467
- return result;
468
- }
469
- await executeApiActions(apiActions, fetchFn, result);
470
- return result;
471
- }
8
+ } from "./chunk-KNXHLVF7.js";
472
9
 
473
10
  // src/checks/roles.ts
474
11
  var PLATFORM_ROLES = [
@@ -695,7 +232,8 @@ var RolesCheck = class extends Check {
695
232
  ...diffRoles(sourceRoles, targetRoles),
696
233
  ...diffGrants(
697
234
  [...sourceAll, ...sourceColumns ?? []].filter((g) => comparable(g) && !byDefault(g)),
698
- [...targetAll, ...targetColumns ?? []].filter(comparable)
235
+ [...targetAll, ...targetColumns ?? []].filter(comparable),
236
+ absentOn(targetRoles, sourceRoles)
699
237
  ),
700
238
  ...defaultGrantsToRevoke(
701
239
  sourceObjects,
@@ -706,6 +244,10 @@ var RolesCheck = class extends Check {
706
244
  ];
707
245
  }
708
246
  };
247
+ function absentOn(target, source) {
248
+ const present = new Set((target ?? []).map((r) => r.rolname));
249
+ return new Set((source ?? []).map((r) => r.rolname).filter((name) => !present.has(name)));
250
+ }
709
251
  function roleAttrs(r) {
710
252
  const attrs = [];
711
253
  if (r.rolsuper) attrs.push("SUPERUSER");
@@ -842,12 +384,34 @@ function describeGroup(gs) {
842
384
  return `${gs.map((g) => g.privilege_type).join(", ")} ${column}ON ${describeObject(gs[0])} TO ${gs[0].grantee}`;
843
385
  }
844
386
  var groupKey = (gs) => grantKey(gs[0]).replace(/\.[^.]+$/, "");
845
- function diffGrants(source, target) {
387
+ function grantsToMissingRoles(grants) {
388
+ const byRole = /* @__PURE__ */ new Map();
389
+ for (const g of grants) byRole.set(g.grantee, [...byRole.get(g.grantee) ?? [], g]);
390
+ return [...byRole].map(([role, gs]) => {
391
+ const groups = grouped(gs);
392
+ const objects = new Set(gs.map((g) => describeObject(g))).size;
393
+ const what = `${gs.length} privilege${gs.length === 1 ? "" : "s"} on ${objects} object${objects === 1 ? "" : "s"}`;
394
+ return {
395
+ id: `roles-grant-missing-role-${role}`,
396
+ check: "roles",
397
+ severity: "warning",
398
+ title: `Missing grants: ${what} to ${role}, a role the target does not have`,
399
+ description: `The source grants ${what} to "${role}", which the target lacks. They can only be applied once the role exists (see "Missing role"); on a target that is not meant to have it, skip the roles check.`,
400
+ sourceValue: gs,
401
+ sql: {
402
+ up: groups.map((g) => `GRANT ${groupTarget(g)} TO ${granteeSql(role)}${g[0].is_grantable ? " WITH GRANT OPTION" : ""};`).join("\n"),
403
+ down: groups.map((g) => `REVOKE ${groupTarget(g)} FROM ${granteeSql(role)};`).reverse().join("\n")
404
+ }
405
+ };
406
+ });
407
+ }
408
+ function diffGrants(source, target, missingRoles = /* @__PURE__ */ new Set()) {
846
409
  const issues = [];
847
410
  const sourceMap = new Map(source.map((g) => [grantKey(g), g]));
848
411
  const targetMap = new Map(target.map((g) => [grantKey(g), g]));
849
412
  const missing = [...sourceMap].filter(([key]) => !targetMap.has(key)).map(([, g]) => g);
850
- for (const gs of grouped(missing)) {
413
+ issues.push(...grantsToMissingRoles(missing.filter((g) => missingRoles.has(g.grantee))));
414
+ for (const gs of grouped(missing.filter((g) => !missingRoles.has(g.grantee)))) {
851
415
  const plural = gs.length > 1 ? "s" : "";
852
416
  issues.push({
853
417
  id: `roles-grant-missing-${groupKey(gs)}`,
@@ -898,19 +462,7 @@ function diffGrants(source, target) {
898
462
  }
899
463
 
900
464
  export {
901
- resolveTableFilter,
902
- isFiltered,
903
- describeTableFilter,
904
- applyTableFilter,
905
- CHECK_NAMES,
906
- CHECK_META,
907
- isComparisonCheck,
908
465
  PLATFORM_ROLES,
909
- RolesCheck,
910
- ABSENT_ON_TARGET,
911
- EXTENSION_UNAVAILABLE,
912
- planWork,
913
- runLikeApply,
914
- promote
466
+ RolesCheck
915
467
  };
916
- //# sourceMappingURL=chunk-UWAVXC57.js.map
468
+ //# sourceMappingURL=chunk-WNTCZM2J.js.map
@@ -1,17 +1,21 @@
1
1
  import {
2
2
  DEFAULT_MIGRATIONS_DIR,
3
- Preflight,
4
- describeFailure,
5
- redactUrls
6
- } from "./chunk-SQPCWGQO.js";
3
+ Preflight
4
+ } from "./chunk-4M6OQLPO.js";
5
+ import {
6
+ installProcessGuard,
7
+ noteJsonWritten
8
+ } from "./chunk-GQPGH6YR.js";
7
9
  import {
8
10
  RUN_LOG_DIR,
9
11
  RUN_LOG_FILE,
10
12
  RUN_LOG_MAX_ENTRIES,
13
+ describeFailure,
11
14
  loadConfig,
15
+ redactUrls,
12
16
  validateConfig,
13
17
  validateSingleEnvConfig
14
- } from "./chunk-6WAMNZLO.js";
18
+ } from "./chunk-KNXHLVF7.js";
15
19
 
16
20
  // src/base-command.ts
17
21
  import { formatWithOptions } from "util";
@@ -85,6 +89,7 @@ var BaseCommand = class extends Command {
85
89
  /** The command's result as JSON, on stdout. */
86
90
  json(value) {
87
91
  this._jsonWritten = true;
92
+ noteJsonWritten();
88
93
  process.stdout.write(JSON.stringify(value, null, 2) + "\n");
89
94
  }
90
95
  /** Call after scan() to attach per-check metadata to the run log entry. */
@@ -94,6 +99,7 @@ var BaseCommand = class extends Command {
94
99
  async init() {
95
100
  await super.init();
96
101
  this._startTime = Date.now();
102
+ installProcessGuard(this.argv);
97
103
  }
98
104
  async catch(err) {
99
105
  this._logWritten = true;
@@ -130,10 +136,11 @@ var BaseCommand = class extends Command {
130
136
  async loadConfigOrFail() {
131
137
  try {
132
138
  return await loadConfig();
133
- } catch {
134
- this.error(
135
- 'Could not load supaforge.config.json. Run "supaforge init" first.'
136
- );
139
+ } catch (err) {
140
+ if (err?.code === "ENOENT") {
141
+ this.error('Could not load supaforge.config.json. Run "supaforge init" first.');
142
+ }
143
+ this.error(`Could not load supaforge.config.json: ${redactUrls(describeFailure(err))}`);
137
144
  }
138
145
  }
139
146
  /**
@@ -204,4 +211,4 @@ export {
204
211
  readRunLog,
205
212
  BaseCommand
206
213
  };
207
- //# sourceMappingURL=chunk-GZREXCQZ.js.map
214
+ //# sourceMappingURL=chunk-XLZCX6R2.js.map